public static ToneAnalysis ToneAnalyzer(AppSettings appSettings, ToneAnalyzerRequest requestBody)
        {
            string  methodName = "ToneAnalyzer";
            dynamic result     = new ExpandoObject();

            try
            {
                ToneAnalyzer     settings      = appSettings.WatsonServices.ToneAnalyzer;
                IamAuthenticator authenticator = new IamAuthenticator(apikey: $"{requestBody.Apikey}");
                IBM.Watson.ToneAnalyzer.v3.ToneAnalyzerService toneAnalyzer = new IBM.Watson.ToneAnalyzer.v3.ToneAnalyzerService($"{settings.Version}", authenticator);
                toneAnalyzer.SetServiceUrl($"{requestBody.Endpoint}");
                ToneInput toneInput = new ToneInput()
                {
                    Text = requestBody.Text
                };
                result = toneAnalyzer.Tone(
                    toneInput: new MemoryStream(Encoding.UTF8.GetBytes(requestBody.Text)),
                    sentences: requestBody.Sentences,
                    contentLanguage: requestBody.ContentLanguage != null ? requestBody.ContentLanguage : "en",
                    acceptLanguage: requestBody.AcceptLanguage
                    ).Result;
                return(result);
            }
            catch (Exception e)
            {
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {JsonConvert.SerializeObject(requestBody)}");
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {e.Source + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace}");
                throw e;
            }
        }
Exemple #2
0
        public ToneAnalysis Tone(ToneInput body, string tones = null, bool?sentences = null)
        {
            if (body == null)
            {
                throw new ArgumentNullException(nameof(body));
            }

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

            ToneAnalysis result = null;

            try
            {
                result = this.Client.WithAuthentication(this.UserName, this.Password)
                         .PostAsync($"{this.Endpoint}/v3/tone")
                         .WithArgument("version", VersionDate)
                         .WithArgument("tones", tones)
                         .WithArgument("sentences", sentences)
                         .WithBody <ToneInput>(body)
                         .As <ToneAnalysis>()
                         .Result;
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        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)));
        }
Exemple #4
0
        public WatsonApiResponse Anaylze(string text)
        {
            ToneInput input = new ToneInput();

            input.Text = text;
            WatsonApiResponse objResponse = new WatsonApiResponse();


            try
            {
                string jsonResponse = toneAnalyzer.Tone(input).ResponseJson;
                objResponse       = WatsonApiResponse.FromJson(jsonResponse);
                objResponse.Error = false;
                if (objResponse.SentencesTone == null)
                {
                    objResponse.SentencesTone = new List <SentencesTone>().ToArray();
                }
            }
            catch
            {
                objResponse.Error     = true;
                objResponse.ErrorText = "Counld not get Watson API data. ";
            }

            return(objResponse);
        }
Exemple #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");
        }
Exemple #6
0
        public IEnumerator TestTone()
        {
            Log.Debug("ToneAnalyzerServiceV3IntegrationTests", "Attempting to Tone...");
            ToneAnalysis toneResponse = null;
            ToneInput    toneInput    = new ToneInput()
            {
                Text = inputText
            };

            service.Tone(
                callback: (DetailedResponse <ToneAnalysis> response, IBMError error) =>
            {
                Log.Debug("ToneAnalyzerServiceV3IntegrationTests", "Tone result: {0}", response.Response);
                toneResponse = response.Result;
                Assert.IsNotNull(toneResponse);
                Assert.IsNotNull(toneResponse.SentencesTone);
                Assert.IsNotNull(toneResponse.DocumentTone);
                Assert.IsNull(error);
            },
                toneInput: toneInput,
                contentLanguage: "en",
                acceptLanguage: "en",
                contentType: "text/plain"
                );

            while (toneResponse == null)
            {
                yield return(null);
            }
        }
Exemple #7
0
//Synthesizes the sentence
    public void SynthesizeSentence(string sentence)
    {
        activeFile   = Regex.Replace(sentence, @"[^a-zA-Z0-9 -]", "").ToLower();
        activeFile   = Regex.Replace(activeFile, @"\s+", string.Empty);
        DialogueHash = activeFile;
        using (MD5 md5Hash = MD5.Create())
        {
            DialogueHash = GetMd5Hash(md5Hash, DialogueHash);
        }
        ttsSynthesing = true;
        if (voiceLines.ContainsKey(DialogueHash))
        {
            associatedSource.clip = WaveFile.ParseWAV(DialogueHash, voiceLines[DialogueHash]);
            ttsSynthesing         = false;
            //associatedSource.PlayOneShot(Resources.Load<AudioClip>("Sounds/" + fileNameSaveFile));
        }
        else
        {
            tts.Synthesize(OnSynthesize, sentence, "en-US_AllisonV3Voice", null, "audio/wav");
        }
        if (PlayerPrefs.HasKey(activeFile))
        {
            emotionScore = PlayerPrefs.GetFloat(activeFile);
        }
        else
        {
            ToneInput tempInput = new ToneInput();
            tempInput.Text = sentence;
            tas.Tone(OnToneAnalysis, tempInput, false, tones);
        }
    }
        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);
        }
Exemple #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);
        }
        /// <summary>
        /// Analyze general tone.
        ///
        /// Use the general purpose endpoint to analyze the tone of your input content. The service analyzes the content
        /// for emotional and language tones. The method always analyzes the tone of the full document; by default, it
        /// also analyzes the tone of each individual sentence of the content.
        ///
        /// You can submit no more than 128 KB of total input content and no more than 1000 individual sentences in
        /// JSON, plain text, or HTML format. The service analyzes the first 1000 sentences for document-level analysis
        /// and only the first 100 sentences for sentence-level analysis.
        ///
        /// Per the JSON specification, the default character encoding for JSON content is effectively always UTF-8; per
        /// the HTTP specification, the default encoding for plain text and HTML is ISO-8859-1 (effectively, the ASCII
        /// character set). When specifying a content type of plain text or HTML, include the `charset` parameter to
        /// indicate the character encoding of the input text; for example: `Content-Type: text/plain;charset=utf-8`.
        /// For `text/html`, the service removes HTML tags and analyzes only the textual content.
        /// </summary>
        /// <param name="toneInput">JSON, plain text, or HTML input that contains the content to be analyzed. For JSON
        /// input, provide an object of type `ToneInput`.</param>
        /// <param name="contentType">The type of the input. A character encoding can be specified by including a
        /// `charset` parameter. For example, 'text/plain;charset=utf-8'.</param>
        /// <param name="sentences">Indicates whether the service is to return an analysis of each individual sentence
        /// in addition to its analysis of the full document. If `true` (the default), the service returns results for
        /// each sentence. (optional, default to true)</param>
        /// <param name="tones">**`2017-09-21`:** Deprecated. The service continues to accept the parameter for
        /// backward-compatibility, but the parameter no longer affects the response.
        ///
        /// **`2016-05-19`:** A comma-separated list of tones for which the service is to return its analysis of the
        /// input; the indicated tones apply both to the full document and to individual sentences of the document. You
        /// can specify one or more of the valid values. Omit the parameter to request results for all three tones.
        /// (optional)</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="ToneAnalysis" />ToneAnalysis</returns>
        public ToneAnalysis Tone(ToneInput toneInput, string contentType, bool?sentences = null, List <string> tones = null, string contentLanguage = null, string acceptLanguage = null, Dictionary <string, object> customData = null)
        {
            if (toneInput == null)
            {
                throw new ArgumentNullException(nameof(toneInput));
            }
            if (string.IsNullOrEmpty(contentType))
            {
                throw new ArgumentNullException(nameof(contentType));
            }

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

            ToneAnalysis result = null;

            try
            {
                IClient client;
                if (_tokenManager == null)
                {
                    client = this.Client.WithAuthentication(this.UserName, this.Password);
                }
                else
                {
                    client = this.Client.WithAuthentication(_tokenManager.GetToken());
                }
                var restRequest = client.PostAsync($"{this.Endpoint}/v3/tone");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Content-Type", contentType);
                restRequest.WithHeader("Content-Language", contentLanguage);
                restRequest.WithHeader("Accept-Language", acceptLanguage);
                if (sentences != null)
                {
                    restRequest.WithArgument("sentences", sentences);
                }
                restRequest.WithArgument("tones", tones != null && tones.Count > 0 ? string.Join(",", tones.ToArray()) : null);
                restRequest.WithBody <ToneInput>(toneInput);
                if (customData != null)
                {
                    restRequest.WithCustomData(customData);
                }
                result = restRequest.As <ToneAnalysis>().Result;
                if (result == null)
                {
                    result = new ToneAnalysis();
                }
                result.CustomData = restRequest.CustomData;
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Exemple #11
0
//Function that calls the Tone Analyzer
    public void ReturnReaction(string text)
    {
        if (tAStarted)
        {
            ToneInput tempInput = new ToneInput();
            tempInput.Text = text;
            tas.Tone(OnToneAnalysis, tempInput, false, tones);
        }
    }
Exemple #12
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();
        }
Exemple #13
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");
        }
Exemple #14
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");
        }
        public void PostTone_Success()
        {
            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);
        }
        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);
        }
        public ToneAnalysis Tone(ToneInput toneInput, string contentType, bool?sentences = null, List <string> tones = null, string contentLanguage = null, string acceptLanguage = null)
        {
            try
            {
                var result = ToneAnalyzerRepository.Tone(toneInput, contentType, sentences, tones, contentLanguage, acceptLanguage);

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

            return(null);
        }
Exemple #18
0
        public void Tone_Returns_200_OK()
        {
            //Arrange
            var toneInput = new ToneInput()
            {
                Text = "Wahey!"
            };

            //Act
            var result = _toneAnalyzer.Tone(
                toneInput: toneInput
                );

            //Assert
            Assert.AreEqual(result.StatusCode, 200);
        }
        private ToneAnalysis Tone(ToneInput toneInput, string contentType, bool?sentences = null, List <string> tones = null, string contentLanguage = null, string acceptLanguage = null, Dictionary <string, object> customData = null)
        {
            Console.WriteLine("\nAttempting to Tone()");
            var result = service.Tone(toneInput: toneInput, contentType: contentType, sentences: sentences, tones: tones, contentLanguage: contentLanguage, acceptLanguage: acceptLanguage, customData: customData);

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

            return(result);
        }
Exemple #20
0
        public ToneAnalysisResultBLDto AnalyzeTextTone(int userId, string textForToneAnalysis)
        {
            IamAuthenticator authenticator = new IamAuthenticator(
                apikey: "");
            var service = new ToneAnalyzerService("", authenticator);

            service.SetServiceUrl("");
            ToneInput toneInput = new ToneInput()
            {
                Text = textForToneAnalysis
            };
            var result = service.Tone(
                toneInput: toneInput
                );
            WatsonResponseBLDto     watsonResponse = JsonConvert.DeserializeObject <WatsonResponseBLDto>(result.Response);
            ToneAnalysisResultBLDto analysisResult = new ToneAnalysisResultBLDto {
                UserID           = userId,
                Date             = DateTime.Now,
                Text             = textForToneAnalysis,
                DetectedEmotions = watsonResponse.document_tone.tones
            };
            double emotionScore      = 0;
            string prevailingEmotion = "";

            foreach (var emotion in analysisResult.DetectedEmotions)
            {
                if (emotion.score > emotionScore)
                {
                    emotionScore      = emotion.score;
                    prevailingEmotion = emotion.tone_name;
                }
            }
            foreach (KeyValuePair <string, List <string> > emotionType in GetListOfEmotions())
            {
                if (emotionType.Value.Contains(prevailingEmotion))
                {
                    analysisResult.PrevailingEmotion = emotionType.Key;
                }
            }
            if (analysisResult.PrevailingEmotion == null)
            {
                analysisResult.PrevailingEmotion = "OtherEmotion";
            }
            return(analysisResult);
        }
Exemple #21
0
        public void Tone_Returns_Appropriate_Mood(string message, ToneMood mood)
        {
            //Arrange
            var toneInput = new ToneInput()
            {
                Text = message
            };

            //Act
            var result = _toneAnalyzer.Tone(
                toneInput: toneInput
                );
            var analysis = result.Result.DocumentTone.Tones.FirstOrDefault(w => w.ToneId == mood.ToString());


            //Assert
            Assert.IsNotNull(analysis);
            Assert.AreEqual(mood, analysis.ToneId.ParseEnum <ToneMood>());
        }
        public string AnalyseText(string text)
        {
            IamAuthenticator authenticator = new IamAuthenticator(apikey: ApiKey);

            ToneAnalyzerService toneAnalyzer = new ToneAnalyzerService("2017-09-21", authenticator);

            toneAnalyzer.SetServiceUrl(ApiEndpoint);

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

            var result = toneAnalyzer.Tone(toneInput: toneInput);

            string deserializedResult = DeserializeResult(result.Response);

            return(deserializedResult);
        }
Exemple #23
0
        public void Tone()
        {
            IamAuthenticator authenticator = new IamAuthenticator(
                apikey: "{apikey}");

            ToneAnalyzerService service = new ToneAnalyzerService("2017-09-21", authenticator);

            service.SetServiceUrl("{serviceUrl}");

            ToneInput toneInput = new ToneInput()
            {
                Text = "Team, I know that times are tough! Product sales have been disappointing for the past three quarters. We have a competitive product, but we need to do a better job of selling it!"
            };

            var result = service.Tone(
                toneInput: toneInput
                );

            Console.WriteLine(result.Response);
        }
        public void PostTone_Success()
        {
            ToneInput toneInput = new ToneInput()
            {
                Text = inputText
            };

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

            Assert.IsNotNull(result.Result);
            Assert.IsTrue(result.Result.DocumentTone.ToneCategories.Count >= 1);
            Assert.IsTrue(result.Result.DocumentTone.ToneCategories[0].Tones.Count >= 1);
        }
        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();
        }
        private IEnumerator Examples()
        {
            ToneInput toneInput = new ToneInput()
            {
                Text = stringToTestTone
            };

            List <string> tones = new List <string>()
            {
                "emotion",
                "language",
                "social"
            };

            service.Tone(callback: OnTone, toneInput: toneInput, sentences: true, tones: tones, contentLanguage: "en", acceptLanguage: "en", contentType: "application/json");

            while (!toneTested)
            {
                yield return(null);
            }


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

            service.ToneChat(callback: OnToneChat, utterances: utterances, contentLanguage: "en", acceptLanguage: "en");

            while (!toneChatTested)
            {
                yield return(null);
            }

            Log.Debug("ExampleToneAnalyzerV3.Examples()", "Examples complete!");
        }
        public ToneAnalysis Tone(ToneInput toneInput, string contentType, bool?sentences = null, List <string> tones = null, string contentLanguage = null, string acceptLanguage = null)
        {
            if (toneInput == null)
            {
                throw new ArgumentNullException(nameof(toneInput));
            }
            if (string.IsNullOrEmpty(contentType))
            {
                throw new ArgumentNullException(nameof(contentType));
            }

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

            ToneAnalysis result = null;

            try
            {
                result = this.Client.WithAuthentication(this.UserName, this.Password)
                         .PostAsync($"{this.Endpoint}/v3/tone")
                         .WithArgument("version", VersionDate)
                         .WithHeader("Content-Type", contentType)
                         .WithHeader("Content-Language", contentLanguage)
                         .WithHeader("Accept-Language", acceptLanguage)
                         .WithArgument("sentences", sentences)
                         .WithArgument("tones", tones != null && tones.Count > 0 ? string.Join(",", tones.ToArray()) : null)
                         .WithBody <ToneInput>(toneInput)
                         .As <ToneAnalysis>()
                         .Result;
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Exemple #28
0
        public ToneAnalysis Tone(ToneInput toneInput, string contentType, bool?sentences = null, List <string> tones = null, string contentLanguage = null, string acceptLanguage = null)
        {
            if (toneInput == null)
            {
                throw new ArgumentNullException(nameof(toneInput));
            }
            if (string.IsNullOrEmpty(contentType))
            {
                throw new ArgumentNullException(nameof(contentType));
            }
            if (string.IsNullOrEmpty(versionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            try
            {
                var result = RepositoryClient.WithAuthentication(ApiKeys.ToneAnalyzerUsername, ApiKeys.ToneAnalyzerPassword)
                             .PostAsync($"{ApiKeys.ToneAnalyzerEndpoint}{toneUrl}")
                             .WithArgument("version", versionDate)
                             .WithHeader("Content-Type", contentType)
                             .WithHeader("Content-Language", contentLanguage)
                             .WithHeader("Accept-Language", acceptLanguage)
                             .WithArgument("sentences", sentences)
                             .WithArgument("tones", tones != null && tones.Count > 0 ? string.Join(",", tones.ToArray()) : null)
                             .WithBody <ToneInput>(toneInput)
                             .As <ToneAnalysis>()
                             .Result;

                return(result);
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }
        }
Exemple #29
0
        public void Tone_Success_With_ToneInput()
        {
            IClient client = CreateClient();

            #region response
            var response = new DetailedResponse <ToneAnalysis>()
            {
                Result = 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

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

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

            request.WithHeader(Arg.Any <string>(), Arg.Any <string>())
            .Returns(request);
            request.WithArgument(Arg.Any <string>(), Arg.Any <bool>())
            .Returns(request);
            request.WithArgument(Arg.Any <string>(), Arg.Any <List <string> >())
            .Returns(request);
            request.WithBody <ToneInput>(Arg.Any <ToneInput>())
            .Returns(request);
            request.As <ToneAnalysis>()
            .Returns(Task.FromResult(response));

            ToneAnalyzerService service = new ToneAnalyzerService(client);
            service.VersionDate = "2016-05-19";
            service.UserName    = "******";
            service.Password    = "******";

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

            var analyzeTone = service.Tone(toneInput, "text/html");

            //client.Received().PostAsync(Arg.Any<string>());
            Assert.IsNotNull(analyzeTone);
            Assert.IsNotNull(analyzeTone.Result.DocumentTone);
            Assert.IsNotNull(analyzeTone.Result.DocumentTone.ToneCategories);
            Assert.IsTrue(analyzeTone.Result.DocumentTone.ToneCategories.Count >= 1);
            Assert.IsNotNull(analyzeTone.Result.SentencesTone);
            Assert.IsTrue(analyzeTone.Result.SentencesTone.Count >= 1);
            Assert.IsNotNull(analyzeTone.Result.SentencesTone[0].ToneCategories);
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].SentenceId == 0);
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].Text == "string");
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].ToneCategories.Count >= 1);
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].ToneCategories[0].CategoryId == "string");
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].ToneCategories[0].CategoryName == "string");
            Assert.IsNotNull(analyzeTone.Result.SentencesTone[0].ToneCategories[0].Tones);
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].ToneCategories[0].Tones.Count >= 1);
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].ToneCategories[0].Tones[0].ToneName == "string");
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].ToneCategories[0].Tones[0].ToneId == "string");
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].ToneCategories[0].Tones[0].Score == 0);
        }
        /// <summary>
        /// Analyze general tone.
        ///
        /// Use the general-purpose endpoint to analyze the tone of your input content. The service analyzes the content
        /// for emotional and language tones. The method always analyzes the tone of the full document; by default, it
        /// also analyzes the tone of each individual sentence of the content.
        ///
        /// You can submit no more than 128 KB of total input content and no more than 1000 individual sentences in
        /// JSON, plain text, or HTML format. The service analyzes the first 1000 sentences for document-level analysis
        /// and only the first 100 sentences for sentence-level analysis.
        ///
        /// Per the JSON specification, the default character encoding for JSON content is effectively always UTF-8; per
        /// the HTTP specification, the default encoding for plain text and HTML is ISO-8859-1 (effectively, the ASCII
        /// character set). When specifying a content type of plain text or HTML, include the `charset` parameter to
        /// indicate the character encoding of the input text; for example: `Content-Type: text/plain;charset=utf-8`.
        /// For `text/html`, the service removes HTML tags and analyzes only the textual content.
        ///
        /// **See also:** [Using the general-purpose
        /// endpoint](https://cloud.ibm.com/docs/tone-analyzer?topic=tone-analyzer-utgpe#utgpe).
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <param name="toneInput">JSON, plain text, or HTML input that contains the content to be analyzed. For JSON
        /// input, provide an object of type `ToneInput`.</param>
        /// <param name="contentType">The type of the input. A character encoding can be specified by including a
        /// `charset` parameter. For example, 'text/plain;charset=utf-8'. (optional)</param>
        /// <param name="sentences">Indicates whether the service is to return an analysis of each individual sentence
        /// in addition to its analysis of the full document. If `true` (the default), the service returns results for
        /// each sentence. (optional, default to true)</param>
        /// <param name="tones">**`2017-09-21`:** Deprecated. The service continues to accept the parameter for
        /// backward-compatibility, but the parameter no longer affects the response.
        ///
        /// **`2016-05-19`:** A comma-separated list of tones for which the service is to return its analysis of the
        /// input; the indicated tones apply both to the full document and to individual sentences of the document. You
        /// can specify one or more of the valid values. Omit the parameter to request results for all three tones.
        /// (optional)</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>
        /// <returns><see cref="ToneAnalysis" />ToneAnalysis</returns>
        public bool Tone(Callback <ToneAnalysis> callback, ToneInput toneInput, string contentType = null, bool?sentences = null, List <string> tones = null, string contentLanguage = null, string acceptLanguage = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `Tone`");
            }
            if (toneInput == null)
            {
                throw new ArgumentNullException("`toneInput` is required for `Tone`");
            }

            RequestObject <ToneAnalysis> req = new RequestObject <ToneAnalysis>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbPOST,
                DisableSslVerification = DisableSslVerification
            };

            foreach (KeyValuePair <string, string> kvp in customRequestHeaders)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("tone_analyzer", "V3", "Tone"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"] = VersionDate;
            if (sentences != null)
            {
                req.Parameters["sentences"] = (bool)sentences ? "true" : "false";
            }
            if (tones != null && tones.Count > 0)
            {
                req.Parameters["tones"] = string.Join(",", tones.ToArray());
            }
            req.Headers["Accept"] = "application/json";

            if (!string.IsNullOrEmpty(contentType))
            {
                req.Headers["Content-Type"] = contentType;
            }

            if (!string.IsNullOrEmpty(contentLanguage))
            {
                req.Headers["Content-Language"] = contentLanguage;
            }

            if (!string.IsNullOrEmpty(acceptLanguage))
            {
                req.Headers["Accept-Language"] = acceptLanguage;
            }
            req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(toneInput));

            req.OnResponse = OnToneResponse;

            Connector.URL = GetServiceUrl() + "/v3/tone";
            Authenticator.Authenticate(Connector);

            return(Connector.Send(req));
        }