Exemple #1
0
        public UtteranceAnalyses ToneChat(ToneChatInput utterances, string acceptLanguage = null)
        {
            if (utterances == null)
            {
                throw new ArgumentNullException(nameof(utterances));
            }
            if (string.IsNullOrEmpty(versionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            try
            {
                var result = RepositoryClient.WithAuthentication(ApiKeys.ToneAnalyzerUsername, ApiKeys.ToneAnalyzerPassword)
                             .PostAsync($"{ApiKeys.ToneAnalyzerEndpoint}{toneChatUrl}")
                             .WithArgument("version", versionDate)
                             .WithHeader("Accept-Language", acceptLanguage)
                             .WithBody <ToneChatInput>(utterances)
                             .As <UtteranceAnalyses>()
                             .Result;

                return(result);
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }
        }
        public UtteranceAnalyses ToneChat(ToneChatInput utterances, string acceptLanguage = null)
        {
            if (utterances == null)
            {
                throw new ArgumentNullException(nameof(utterances));
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            UtteranceAnalyses result = null;

            try
            {
                result = this.Client.WithAuthentication(this.UserName, this.Password)
                         .PostAsync($"{this.Endpoint}/v3/tone_chat")
                         .WithArgument("version", VersionDate)
                         .WithHeader("Accept-Language", acceptLanguage)
                         .WithBody <ToneChatInput>(utterances)
                         .As <UtteranceAnalyses>()
                         .Result;
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        /// <summary>
        /// Analyze customer engagement tone.
        ///
        /// Use the customer engagement endpoint to analyze the tone of customer service and customer support
        /// conversations. For each utterance of a conversation, the method reports the most prevalent subset of the
        /// following seven tones: sad, frustrated, satisfied, excited, polite, impolite, and sympathetic.
        ///
        /// If you submit more than 50 utterances, the service returns a warning for the overall content and analyzes
        /// only the first 50 utterances. If you submit a single utterance that contains more than 500 characters, the
        /// service returns an error for that utterance and does not analyze the utterance. The request fails if all
        /// utterances have more than 500 characters. Per the JSON specification, the default character encoding for
        /// JSON content is effectively always UTF-8.
        ///
        /// **See also:** [Using the customer-engagement
        /// endpoint](https://cloud.ibm.com/docs/services/tone-analyzer/using-tone-chat.html#using-the-customer-engagement-endpoint).
        /// </summary>
        /// <param name="utterances">An object that contains the content to be analyzed.</param>
        /// <param name="contentLanguage">The language of the input text for the request: English or French. Regional
        /// variants are treated as their parent language; for example, `en-US` is interpreted as `en`. The input
        /// content must match the specified language. Do not submit content that contains both languages. You can use
        /// different languages for **Content-Language** and **Accept-Language**.
        /// * **`2017-09-21`:** Accepts `en` or `fr`.
        /// * **`2016-05-19`:** Accepts only `en`. (optional, default to en)</param>
        /// <param name="acceptLanguage">The desired language of the response. For two-character arguments, regional
        /// variants are treated as their parent language; for example, `en-US` is interpreted as `en`. You can use
        /// different languages for **Content-Language** and **Accept-Language**. (optional, default to en)</param>
        /// <param name="customData">Custom data object to pass data including custom request headers.</param>
        /// <returns><see cref="UtteranceAnalyses" />UtteranceAnalyses</returns>
        public UtteranceAnalyses ToneChat(ToneChatInput utterances, string contentLanguage = null, string acceptLanguage = null, Dictionary <string, object> customData = null)
        {
            if (utterances == null)
            {
                throw new ArgumentNullException(nameof(utterances));
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            UtteranceAnalyses result = null;

            try
            {
                IClient client = this.Client;
                if (_tokenManager != null)
                {
                    client = this.Client.WithAuthentication(_tokenManager.GetToken());
                }
                if (_tokenManager == null)
                {
                    client = this.Client.WithAuthentication(this.UserName, this.Password);
                }

                var restRequest = client.PostAsync($"{this.Endpoint}/v3/tone_chat");

                restRequest.WithArgument("version", VersionDate);
                if (!string.IsNullOrEmpty(contentLanguage))
                {
                    restRequest.WithHeader("Content-Language", contentLanguage);
                }
                if (!string.IsNullOrEmpty(acceptLanguage))
                {
                    restRequest.WithHeader("Accept-Language", acceptLanguage);
                }
                restRequest.WithBody <ToneChatInput>(utterances);
                if (customData != null)
                {
                    restRequest.WithCustomData(customData);
                }

                restRequest.WithHeader("X-IBMCloud-SDK-Analytics", "service_name=tone_analyzer;service_version=v3;operation_id=ToneChat");
                result = restRequest.As <UtteranceAnalyses>().Result;
                if (result == null)
                {
                    result = new UtteranceAnalyses();
                }
                result.CustomData = restRequest.CustomData;
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Exemple #4
0
        public static void Main(string[] args)
        {
            string credentials = string.Empty;

            try
            {
                credentials = Utility.SimpleGet(
                    Environment.GetEnvironmentVariable("VCAP_URL"),
                    Environment.GetEnvironmentVariable("VCAP_USERNAME"),
                    Environment.GetEnvironmentVariable("VCAP_PASSWORD")).Result;
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("Failed to get credentials: {0}", e.Message));
            }

            Task.WaitAll();

            var vcapServices = JObject.Parse(credentials);
            var _url         = vcapServices["tone_analyzer"]["url"].Value <string>();
            var _username    = vcapServices["tone_analyzer"]["username"].Value <string>();
            var _password    = vcapServices["tone_analyzer"]["password"].Value <string>();
            var versionDate  = "2016-05-19";

            ToneAnalyzerService _toneAnalyzer = new ToneAnalyzerService(_username, _password, versionDate);

            _toneAnalyzer.Endpoint = _url;

            //  Test PostTone
            ToneInput toneInput = new ToneInput()
            {
                Text = "How are you doing? My name is Taj!"
            };

            var postToneResult = _toneAnalyzer.Tone(toneInput, "application/json", null);

            Console.WriteLine(string.Format("post tone result: {0}", JsonConvert.SerializeObject(postToneResult, Formatting.Indented)));

            //  Test ToneChat
            ToneChatInput toneChatInput = new ToneChatInput()
            {
                Utterances = new List <Utterance>()
                {
                    new Utterance()
                    {
                        Text = "Hello how are you?"
                    }
                }
            };

            var toneChatResult = _toneAnalyzer.ToneChat(toneChatInput);

            Console.WriteLine(string.Format("tone chat result: {0}", JsonConvert.SerializeObject(toneChatResult, Formatting.Indented)));


            Console.ReadKey();
        }
        public UtteranceAnalyses ToneChat(ToneChatInput utterances, string acceptLanguage = null)
        {
            try
            {
                var result = ToneAnalyzerRepository.ToneChat(utterances, acceptLanguage);

                return(result);
            }
            catch (Exception ex)
            {
                Logger.Error("ToneAnalyzerService.ToneChat failed", this, ex);
            }

            return(null);
        }
        private UtteranceAnalyses ToneChat(ToneChatInput utterances, string contentLanguage = null, string acceptLanguage = null, Dictionary <string, object> customData = null)
        {
            Console.WriteLine("\nAttempting to ToneChat()");
            var result = service.ToneChat(utterances: utterances, contentLanguage: contentLanguage, acceptLanguage: acceptLanguage, customData: customData);

            if (result != null)
            {
                Console.WriteLine("ToneChat() succeeded:\n{0}", JsonConvert.SerializeObject(result, Formatting.Indented));
            }
            else
            {
                Console.WriteLine("Failed to ToneChat()");
            }

            return(result);
        }
        public void ToneChat_Success()
        {
            ToneChatInput toneChatInput = new ToneChatInput()
            {
                Utterances = new List <Utterance>()
                {
                    new Utterance()
                    {
                        Text = inputText,
                        User = chatUser
                    }
                }
            };
            var result = service.ToneChat(toneChatInput);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.UtterancesTone.Count > 0);
        }
Exemple #8
0
        public void ToneChat_Empty_Version()
        {
            ToneAnalyzerService service = new ToneAnalyzerService("username", "password", versionDate);

            service.VersionDate = null;

            ToneChatInput toneChatInput = new ToneChatInput()
            {
                Utterances = new List <Utterance>()
                {
                    new Utterance()
                    {
                        Text = "utteranceText",
                        User = "******"
                    }
                }
            };

            service.ToneChat(toneChatInput);
        }
        public void ToneChat_Success()
        {
            _service = new ToneAnalyzerService(_username, _password, versionDate);

            ToneChatInput toneChatInput = new ToneChatInput()
            {
                Utterances = new List <Utterance>()
                {
                    new Utterance()
                    {
                        Text = inputText,
                        User = chatUser
                    }
                }
            };
            var result = _service.ToneChat(toneChatInput);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.UtterancesTone.Count > 0);
        }
Exemple #10
0
        /// <summary>
        /// Analyze customer engagement tone. Use the customer engagement endpoint to analyze the tone of customer service and customer support conversations. For each utterance of a conversation, the method reports the most prevalent subset of the following seven tones: sad, frustrated, satisfied, excited, polite, impolite, and sympathetic.   If you submit more than 50 utterances, the service returns a warning for the overall content and analyzes only the first 50 utterances. If you submit a single utterance that contains more than 500 characters, the service returns an error for that utterance and does not analyze the utterance. The request fails if all utterances have more than 500 characters.   Per the JSON specification, the default character encoding for JSON content is effectively always UTF-8.
        /// </summary>
        /// <param name="utterances">An object that contains the content to be analyzed.</param>
        /// <param name="contentLanguage">The language of the input text for the request: English or French. Regional variants are treated as their parent language; for example, `en-US` is interpreted as `en`. The input content must match the specified language. Do not submit content that contains both languages. You can use different languages for **Content-Language** and **Accept-Language**. * **`2017-09-21`:** Accepts `en` or `fr`. * **`2016-05-19`:** Accepts only `en`. (optional, default to en)</param>
        /// <param name="acceptLanguage">The desired language of the response. For two-character arguments, regional variants are treated as their parent language; for example, `en-US` is interpreted as `en`. You can use different languages for **Content-Language** and **Accept-Language**. (optional, default to en)</param>
        /// <param name="customData">Custom data object to pass data including custom request headers.</param>
        /// <returns><see cref="UtteranceAnalyses" />UtteranceAnalyses</returns>
        public UtteranceAnalyses ToneChat(ToneChatInput utterances, string contentLanguage = null, string acceptLanguage = null, Dictionary <string, object> customData = null)
        {
            if (utterances == null)
            {
                throw new ArgumentNullException(nameof(utterances));
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            UtteranceAnalyses result = null;

            try
            {
                var request = this.Client.WithAuthentication(this.UserName, this.Password)
                              .PostAsync($"{this.Endpoint}/v3/tone_chat");
                request.WithArgument("version", VersionDate);
                request.WithHeader("Content-Language", contentLanguage);
                request.WithHeader("Accept-Language", acceptLanguage);
                request.WithBody <ToneChatInput>(utterances);
                if (customData != null)
                {
                    request.WithCustomData(customData);
                }
                result = request.As <UtteranceAnalyses>().Result;
                if (result == null)
                {
                    result = new UtteranceAnalyses();
                }
                result.CustomData = request.CustomData;
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        public static void Main(string[] args)
        {
            var    environmentVariable = Environment.GetEnvironmentVariable("VCAP_SERVICES");
            var    fileContent         = File.ReadAllText(environmentVariable);
            var    vcapServices        = JObject.Parse(fileContent);
            var    _username           = vcapServices["tone_analyzer"][0]["credentials"]["username"];
            var    _password           = vcapServices["tone_analyzer"][0]["credentials"]["password"];
            string versionDate         = "2016-05-19";

            ToneAnalyzerService _toneAnalyzer = new ToneAnalyzerService(_username.ToString(), _password.ToString(), versionDate);

            //  Test PostTone
            ToneInput toneInput = new ToneInput()
            {
                Text = "How are you doing? My name is Taj!"
            };

            var postToneResult = _toneAnalyzer.Tone(toneInput, null, null);

            Console.WriteLine(string.Format("postToneResult: {0}", postToneResult.SentencesTone));

            //  Test ToneChat
            ToneChatInput toneChatInput = new ToneChatInput()
            {
                Utterances = new List <Utterance>()
                {
                    new Utterance()
                    {
                        Text = "Hello how are you?"
                    }
                }
            };

            var toneChatResult = _toneAnalyzer.ToneChat(toneChatInput);

            Console.WriteLine(string.Format("toneChatResult: {0}", toneChatResult));


            Console.ReadKey();
        }
Exemple #12
0
        public void ToneChat_Catch_Exception()
        {
            #region Mock IClient

            IClient client = Substitute.For <IClient>();

            client.WithAuthentication(Arg.Any <string>(), Arg.Any <string>())
            .Returns(client);

            client.WithAuthentication(Arg.Any <string>(), Arg.Any <string>())
            .Returns(client);

            IRequest request = Substitute.For <IRequest>();
            client.PostAsync(Arg.Any <string>())
            .Returns(x =>
            {
                throw new AggregateException(new ServiceResponseException(Substitute.For <IResponse>(),
                                                                          Substitute.For <HttpResponseMessage>(HttpStatusCode.BadRequest),
                                                                          string.Empty));
            });

            #endregion

            ToneAnalyzerService service = new ToneAnalyzerService(client);
            service.VersionDate = versionDate;

            ToneChatInput toneChatInput = new ToneChatInput()
            {
                Utterances = new List <Utterance>()
                {
                    new Utterance()
                    {
                        Text = "utteranceText",
                        User = "******"
                    }
                }
            };
            service.ToneChat(toneChatInput);
        }
Exemple #13
0
        public void ToneChat_Success_With_ToneChatInput()
        {
            IClient client = CreateClient();

            #region response
            UtteranceAnalyses response = new UtteranceAnalyses()
            {
                UtterancesTone = new List <UtteranceAnalysis>()
                {
                    new UtteranceAnalysis()
                    {
                        UtteranceId   = 100,
                        UtteranceText = "utteranceText",
                        Tones         = new List <ToneChatScore>()
                        {
                            new ToneChatScore()
                            {
                                ToneName = "string",
                                ToneId   = ToneChatScore.ToneIdEnum.SAD,
                                Score    = 0
                            }
                        }
                    }
                }
            };
            #endregion

            ToneChatInput toneChatInput = new ToneChatInput()
            {
                Utterances = new List <Utterance>()
                {
                    new Utterance()
                    {
                        Text = "utteranceText",
                        User = "******"
                    }
                }
            };

            IRequest request = Substitute.For <IRequest>();

            client.PostAsync(Arg.Any <string>())
            .Returns(request);

            request.WithArgument(Arg.Any <string>(), Arg.Any <string>())
            .Returns(request);
            request.WithHeader(Arg.Any <string>(), Arg.Any <string>())
            .Returns(request);
            request.WithBody(Arg.Any <ToneChatInput>())
            .Returns(request);
            request.As <UtteranceAnalyses>()
            .Returns(Task.FromResult(response));

            ToneAnalyzerService service = new ToneAnalyzerService(client);
            service.VersionDate = versionDate;

            var result = service.ToneChat(toneChatInput);

            Assert.IsNotNull(result);
            client.Received().PostAsync(Arg.Any <string>());
            Assert.IsTrue(result.UtterancesTone.Count >= 1);
            Assert.IsTrue(result.UtterancesTone[0].Tones.Count >= 1);
            Assert.IsTrue(result.UtterancesTone[0].Tones[0].ToneName == "string");
        }
Exemple #14
0
        public static void Main(string[] args)
        {
            string credentials = string.Empty;

            #region Get Credentials
            string _endpoint = string.Empty;
            string _username = string.Empty;
            string _password = string.Empty;

            if (string.IsNullOrEmpty(credentials))
            {
                var    parentDirectory     = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.Parent.Parent.FullName;
                string credentialsFilepath = parentDirectory + Path.DirectorySeparatorChar + "sdk-credentials" + Path.DirectorySeparatorChar + "credentials.json";
                if (File.Exists(credentialsFilepath))
                {
                    try
                    {
                        credentials = File.ReadAllText(credentialsFilepath);
                        credentials = Utility.AddTopLevelObjectToJson(credentials, "VCAP_SERVICES");
                    }
                    catch (Exception e)
                    {
                        throw new Exception(string.Format("Failed to load credentials: {0}", e.Message));
                    }

                    VcapCredentials vcapCredentials = JsonConvert.DeserializeObject <VcapCredentials>(credentials);
                    var             vcapServices    = JObject.Parse(credentials);

                    Credential credential = vcapCredentials.GetCredentialByname("tone-analyzer-sdk")[0].Credentials;
                    _endpoint = credential.Url;
                    _username = credential.Username;
                    _password = credential.Password;
                }
                else
                {
                    Console.WriteLine("Credentials file does not exist. Please define credentials.");
                    _username = "";
                    _password = "";
                    _endpoint = "";
                }
            }
            #endregion

            var versionDate = "2016-05-19";
            ToneAnalyzerService _toneAnalyzer = new ToneAnalyzerService(_username, _password, versionDate);
            _toneAnalyzer.SetEndpoint(_endpoint);

            //  Test PostTone
            ToneInput toneInput = new ToneInput()
            {
                Text = "How are you doing? My name is Taj!"
            };

            var postToneResult = _toneAnalyzer.Tone(toneInput, "application/json", null);
            Console.WriteLine(string.Format("post tone result: {0}", JsonConvert.SerializeObject(postToneResult, Formatting.Indented)));

            //  Test ToneChat
            ToneChatInput toneChatInput = new ToneChatInput()
            {
                Utterances = new List <Utterance>()
                {
                    new Utterance()
                    {
                        Text = "Hello how are you?"
                    }
                }
            };

            var toneChatResult = _toneAnalyzer.ToneChat(toneChatInput);
            Console.WriteLine(string.Format("tone chat result: {0}", JsonConvert.SerializeObject(toneChatResult, Formatting.Indented)));


            Console.ReadKey();
        }