Exemplo n.º 1
0
        public void ToneChat()
        {
            IamConfig config = new IamConfig(
                apikey: apikey
                );

            ToneAnalyzerService service = new ToneAnalyzerService(versionDate, config);

            service.SetEndpoint(url);

            var utterances = new List <Utterance>()
            {
                new Utterance()
                {
                    Text = "Hello! Welcome to IBM Watson! How can I help you?",
                    User = "******"
                }
            };

            var result = service.ToneChat(
                utterances: utterances,
                contentLanguage: "en-US",
                acceptLanguage: "en-US"
                );

            Console.WriteLine(result.Response);
        }
Exemplo n.º 2
0
        public void Constructor()
        {
            ToneAnalyzerService service =
                new ToneAnalyzerService(new IBMHttpClient());

            Assert.IsNotNull(service);
        }
Exemplo n.º 3
0
        public void ToneChat()
        {
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = apikey,
                ServiceUrl = url
            };

            ToneAnalyzerService service = new ToneAnalyzerService(tokenOptions, versionDate);

            var utterances = new List<Utterance>()
            {
                new Utterance()
                {
                    Text = "Hello! Welcome to IBM Watson! How can I help you?",
                    User = "******"
                }
            };

            var result = service.ToneChat(
                utterances: utterances,
                contentLanguage: "en-US",
                acceptLanguage: "en-US"
                );

            Console.WriteLine(result.Response);
        }
Exemplo n.º 4
0
        public void Tone()
        {
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = apikey,
                ServiceUrl = url
            };

            ToneAnalyzerService service = new ToneAnalyzerService(tokenOptions, versionDate);

            ToneInput toneInput = new ToneInput()
            {
                Text = "Hello! Welcome to IBM Watson! How can I help you?"
            };

            var result = service.Tone(
                toneInput: toneInput,
                contentType: "text/html",
                sentences: true,
                contentLanguage: "en-US",
                acceptLanguage: "en-US"
                );

            Console.WriteLine(result.Response);
        }
Exemplo n.º 5
0
        public void Tone_Catch_Exception()
        {
            #region Mock IClient
            IClient client = CreateClient();

            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;

            ToneInput toneInput = new ToneInput()
            {
                Text = "test"
            };

            service.Tone(toneInput, "application/json");
        }
        public void ToneChat_Success()
        {
            IClient  client  = Substitute.For <IClient>();
            IRequest request = Substitute.For <IRequest>();

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

            ToneAnalyzerService service = new ToneAnalyzerService(client);
            var versionDate             = "versionDate";

            service.VersionDate = versionDate;

            var utterances      = new List <Utterance>();
            var contentLanguage = "contentLanguage";
            var acceptLanguage  = "acceptLanguage";

            var result = service.ToneChat(utterances: utterances, contentLanguage: contentLanguage, acceptLanguage: acceptLanguage);

            JObject bodyObject = new JObject();

            if (utterances != null && utterances.Count > 0)
            {
                bodyObject["utterances"] = JToken.FromObject(utterances);
            }
            var json = JsonConvert.SerializeObject(bodyObject);

            request.Received().WithArgument("version", versionDate);
            request.Received().WithBodyContent(Arg.Is <StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
        }
Exemplo n.º 7
0
        private IEnumerator CreateService()
        {
            if (string.IsNullOrEmpty(iamApikey))
            {
                throw new IBMException("Plesae provide IAM ApiKey for the service.");
            }

            //  Create credential and instantiate service
            Credentials credentials = null;

            //  Authenticate using iamApikey
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = iamApikey
            };

            credentials = new Credentials(tokenOptions, serviceUrl);

            //  Wait for tokendata
            while (!credentials.HasIamTokenData())
            {
                yield return(null);
            }

            service = new ToneAnalyzerService(versionDate, credentials);

            Runnable.Run(Examples());
        }
Exemplo n.º 8
0
        public void Constructor()
        {
            ToneAnalyzerService service =
                new ToneAnalyzerService();

            Assert.IsNotNull(service);
        }
Exemplo n.º 9
0
        public void Tone()
        {
            IamConfig config = new IamConfig(
                apikey: apikey
                );

            ToneAnalyzerService service = new ToneAnalyzerService(versionDate, config);

            service.SetEndpoint(url);

            ToneInput toneInput = new ToneInput()
            {
                Text = "Hello! Welcome to IBM Watson! How can I help you?"
            };

            var result = service.Tone(
                toneInput: toneInput,
                contentType: "text/html",
                sentences: true,
                contentLanguage: "en-US",
                acceptLanguage: "en-US"
                );

            Console.WriteLine(result.Response);
        }
        public void Tone_Success()
        {
            IClient  client  = Substitute.For <IClient>();
            IRequest request = Substitute.For <IRequest>();

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

            ToneAnalyzerService service = new ToneAnalyzerService(client);
            var versionDate             = "versionDate";

            service.VersionDate = versionDate;

            var toneInput   = new ToneInput();
            var contentType = "contentType";
            var sentences   = false;
            var tones       = new List <string>()
            {
                "tones0", "tones1"
            };
            var contentLanguage = "contentLanguage";
            var acceptLanguage  = "acceptLanguage";

            var result = service.Tone(toneInput: toneInput, contentType: contentType, sentences: sentences, tones: tones, contentLanguage: contentLanguage, acceptLanguage: acceptLanguage);

            JObject bodyObject = new JObject();
            var     json       = JsonConvert.SerializeObject(bodyObject);

            request.Received().WithArgument("version", versionDate);
            request.Received().WithBodyContent(Arg.Is <StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
        }
Exemplo n.º 11
0
        public void ToneAnalyzeV3WithLoadedCredentials_Success()
        {
            ToneAnalyzerService service = new ToneAnalyzerService();

            Assert.IsTrue(!string.IsNullOrEmpty(service.ApiKey));
            Assert.IsTrue(!string.IsNullOrEmpty(service.Url));
        }
Exemplo n.º 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);

            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;

            var utterances = new List <Utterance>()
            {
                new Utterance()
                {
                    Text = "utteranceText",
                    User = "******"
                }
            };

            service.ToneChat(utterances);
        }
Exemplo n.º 13
0
        public void Constructor_With_UserName_Password()
        {
            ToneAnalyzerService service =
                new ToneAnalyzerService("username", "password", versionDate);

            Assert.IsNotNull(service);
        }
Exemplo n.º 14
0
        public async Task <IActionResult> ToneAnalyzerCustomer([FromBody] JObject request)
        {
            var         watch      = System.Diagnostics.Stopwatch.StartNew();
            string      methodName = "ToneAnalyzer";
            ResponseDTO response   = new ResponseDTO();

            try
            {
                Log.Write(appSettings, LogEnum.DEBUG.ToString(), label, className, methodName, $"REQUEST: {JsonConvert.SerializeObject(request)}");
                ToneAnalyzerRequest requestBody = request.ToObject <ToneAnalyzerRequest>();
                response.Result = await Task.Run(() => ToneAnalyzerService.ToneAnalyzerCustomer(appSettings, requestBody));

                response.Success = true;
                watch.Stop();
                Log.Write(appSettings, LogEnum.DEBUG.ToString(), label, className, methodName, $"RESULT: {JsonConvert.SerializeObject(response)} Execution Time: {watch.ElapsedMilliseconds} ms");
                return(Ok(response));
            }
            catch (Exception e)
            {
                response.Success = false;
                response.Msg     = e.Message;
                watch.Stop();
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {JsonConvert.SerializeObject(request)}");
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {e.Source + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace}");
                return(BadRequest(response));
            }
        }
        public WatsonToneAnalyzer(string apiKey, string serviceUrl, SaraDbContext db)
        {
            IamAuthenticator authenticator = new IamAuthenticator(apikey: apiKey);

            ToneAnalyzer = new ToneAnalyzerService("2017-09-21", authenticator);
            ToneAnalyzer.SetServiceUrl(serviceUrl);
            SaraDbContext = db;
        }
Exemplo n.º 16
0
        public void Tone_ToneInputEmpty()
        {
            #region response
            ToneAnalysis response = new ToneAnalysis()
            {
                SentencesTone = new List <SentenceAnalysis>()
                {
                    new SentenceAnalysis()
                    {
                        SentenceId     = 0,
                        InputFrom      = 0,
                        InputTo        = 0,
                        Text           = "string",
                        ToneCategories = new List <ToneCategory>()
                        {
                            new ToneCategory()
                            {
                                CategoryName = "string",
                                CategoryId   = "string",
                                Tones        = new List <ToneScore>()
                                {
                                    new ToneScore()
                                    {
                                        ToneName = "string",
                                        ToneId   = "string",
                                        Score    = 0
                                    }
                                }
                            }
                        }
                    }
                },
                DocumentTone = new DocumentAnalysis()
                {
                    ToneCategories = new List <ToneCategory>()
                    {
                        new ToneCategory()
                        {
                            CategoryName = "string",
                            CategoryId   = "string",
                            Tones        = new List <ToneScore>()
                            {
                                new ToneScore()
                                {
                                    ToneName = "string",
                                    ToneId   = "string",
                                    Score    = 0
                                }
                            }
                        }
                    }
                }
            };
            #endregion

            ToneAnalyzerService service = new ToneAnalyzerService("username", "password", versionDate);
            var analyzeTone             = service.Tone(null, "application/json");
        }
Exemplo n.º 17
0
        public ToneService(IConfiguration configuration)
        {
            _authenticator = new IamAuthenticator(
                apikey: configuration["Watson:ApiKey"]
                );
            _toneAnalyzer = new ToneAnalyzerService("2017-09-21", _authenticator);

            _toneAnalyzer.SetServiceUrl(configuration["Watson:ApiUrl"]);
        }
Exemplo n.º 18
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();
        }
Exemplo n.º 19
0
        public WatsonApi(string key, string url, string version)
        {
            TokenOptions ReportTokenOptions = new TokenOptions()
            {
                IamApiKey  = key,
                ServiceUrl = url
            };

            toneAnalyzer = new ToneAnalyzerService(ReportTokenOptions, version);
        }
        public void AnalyzeTone_Success()
        {
            ToneAnalyzerService service = new ToneAnalyzerService();

            service.Endpoint = "https://watson-api-explorer.mybluemix.net/tone-analyzer/api";
            var results = service.AnalyzeTone("A word is dead when it is said, some say. Emily Dickinson");

            Assert.IsNotNull(results);
            Assert.IsTrue(results.DocumentTone.ToneCategories.Count >= 1);
        }
        public void ConstructorExternalConfig()
        {
            var apikey = System.Environment.GetEnvironmentVariable("TONE_ANALYZER_APIKEY");

            System.Environment.SetEnvironmentVariable("TONE_ANALYZER_APIKEY", "apikey");
            ToneAnalyzerService service = Substitute.For <ToneAnalyzerService>("versionDate");

            Assert.IsNotNull(service);
            System.Environment.SetEnvironmentVariable("TONE_ANALYZER_APIKEY", apikey);
        }
        public IEnumerator UnityTestSetup()
        {
            if (service == null)
            {
                service = new ToneAnalyzerService(versionDate);
            }

            while (!service.Credentials.HasIamTokenData())
            {
                yield return(null);
            }
        }
Exemplo n.º 23
0
        public void Setup()
        {
            //Todo: Refactor this out into a service contract
            //Todo: This key needs to be injected by the build or inject by Ioc
            _authenticator = new IamAuthenticator(
                apikey: "key"
                );
            _toneAnalyzer = new ToneAnalyzerService("2017-09-21", _authenticator);

            //Todo: This key needs to be injected by the build or inject by Ioc
            _toneAnalyzer.SetServiceUrl("https://watson-api-explorer.mybluemix.net/apis/tone-analyzer-v3#!/tone/GetTone");
        }
        public IEnumerator UnityTestSetup()
        {
            if (service == null)
            {
                service = new ToneAnalyzerService(versionDate);
            }

            while (!service.Authenticator.CanAuthenticate())
            {
                yield return(null);
            }
        }
Exemplo n.º 25
0
        public void Tone_Empty_Version()
        {
            ToneAnalyzerService service = new ToneAnalyzerService(versionDate, new NoAuthAuthenticator());

            service.VersionDate = null;

            ToneInput toneInput = new ToneInput()
            {
                Text = Arg.Any <string>()
            };

            var analyzeTone = service.Tone(toneInput, "application/json");
        }
Exemplo n.º 26
0
        public void Tone_Empty_Version()
        {
            ToneAnalyzerService service = new ToneAnalyzerService("username", "password", versionDate);

            service.VersionDate = null;

            ToneInput toneInput = new ToneInput()
            {
                Text = Arg.Any <string>()
            };

            var analyzeTone = service.Tone(toneInput, "application/json");
        }
Exemplo n.º 27
0
        public void ConstructorNoUrl()
        {
            var apikey = System.Environment.GetEnvironmentVariable("TONE_ANALYZER_APIKEY");

            System.Environment.SetEnvironmentVariable("TONE_ANALYZER_APIKEY", "apikey");
            var url = System.Environment.GetEnvironmentVariable("TONE_ANALYZER_URL");

            System.Environment.SetEnvironmentVariable("TONE_ANALYZER_URL", null);
            ToneAnalyzerService service = Substitute.For <ToneAnalyzerService>("versionDate");

            Assert.IsTrue(service.ServiceUrl == "https://gateway.watsonplatform.net/tone-analyzer/api");
            System.Environment.SetEnvironmentVariable("TONE_ANALYZER_URL", url);
            System.Environment.SetEnvironmentVariable("TONE_ANALYZER_APIKEY", apikey);
        }
        public void ConstructorNoUrl()
        {
            var apikey = System.Environment.GetEnvironmentVariable("TONE_ANALYZER_APIKEY");

            System.Environment.SetEnvironmentVariable("TONE_ANALYZER_APIKEY", "apikey");
            var url = System.Environment.GetEnvironmentVariable("TONE_ANALYZER_URL");

            System.Environment.SetEnvironmentVariable("TONE_ANALYZER_URL", null);
            ToneAnalyzerService service = Substitute.For <ToneAnalyzerService>("versionDate");

            Assert.IsTrue(service.ServiceUrl == "https://api.us-south.tone-analyzer.watson.cloud.ibm.com");
            System.Environment.SetEnvironmentVariable("TONE_ANALYZER_URL", url);
            System.Environment.SetEnvironmentVariable("TONE_ANALYZER_APIKEY", apikey);
        }
        public void PostTone_Success()
        {
            _service = new ToneAnalyzerService(_username, _password, versionDate);

            ToneInput toneInput = new ToneInput()
            {
                Text = inputText
            };

            var result = _service.Tone(toneInput, "text/html", null);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.DocumentTone.ToneCategories.Count >= 1);
            Assert.IsTrue(result.DocumentTone.ToneCategories[0].Tones.Count >= 1);
        }
Exemplo n.º 30
0
        public static IServiceCollection AddToneAnalyzerServices(this IServiceCollection services,
                                                                 IConfiguration configuration)
        {
            services.AddScoped <IToneAnalyzerService>(sp =>
            {
                services.Configure <ToneAnalyzerOptions>(configuration.GetSection(ToneAnalyzerOptions.ToneAnalyzer));
                var toneAnalyzerOptions = configuration.GetSection(ToneAnalyzerOptions.ToneAnalyzer).Get <ToneAnalyzerOptions>();
                var authenticator       = new IamAuthenticator(apikey: toneAnalyzerOptions.ApiKey);
                var toneAnalyzerService = new ToneAnalyzerService(toneAnalyzerOptions.Version, authenticator);
                toneAnalyzerService.SetServiceUrl(toneAnalyzerOptions.Endpoint);

                return(toneAnalyzerService);
            });

            return(services);
        }