private void OnGetToneAnalyze(ToneAnalysis resp, Dictionary <string, object> customData) { Log.Debug("ExampleToneAnalyzer.OnGetToneAnalyze()", "{0}", customData["json"].ToString()); _analyzeToneTested = true; string RAW = (customData["json"].ToString()); // works but long and cannot read string test = "{\"document_tone\":{\"tones\":[{\"score\":0.880435,\"tone_id\":\"joy\",\"tone_name\":\"Joy\"},{\"score\":0.946222,\"tone_id\":\"tentative\",\"tone_name\":\"Tentative\"}]}}"; var emotions = JsonUtility.FromJson <DocumentTone>(test); // //print(ex1.document_tone.tones[0].score); //print(ex1.health); //print(ex1.lives); /*RAW = string.Concat("Tone Response \n", RAW); * RAW = Regex.Replace(RAW, "tone_categories", ""); * RAW = Regex.Replace(RAW, "sentence_id", "\\\n"); * RAW = Regex.Replace(RAW, "}", ""); * RAW = Regex.Replace(RAW, "tone_id", " "); * RAW = Regex.Replace(RAW, "tone_name", " "); * RAW = Regex.Replace(RAW, "score", " "); * RAW = Regex.Replace(RAW, @"[{\\},:]", ""); * RAW = Regex.Replace(RAW, @"[\[\]']+", ""); * RAW = Regex.Replace(RAW, "\"", "");*/ EmotionResults.text = RAW; // Debug.Log(emotions.tones.ToArray()); // Debug.Log(RAW); }
public IEnumerator TestTone() { Log.Debug("ToneAnalyzerServiceV3IntegrationTests", "Attempting to Tone..."); ToneAnalysis toneResponse = null; byte[] bytes = Encoding.ASCII.GetBytes(inputText); MemoryStream toneInput = new MemoryStream(bytes); 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); } }
public string EmojiResponseGenerator(ToneAnalysis postReponse) { string responseMessage = null; double highestScore = 0; foreach (ToneScore tone in postReponse.DocumentTone.Tones) { if (tone.ToneId == "joy" && highestScore <= tone.Score) { responseMessage = $"\U0001F917 \n"; highestScore = (double)tone.Score; } else if (tone.ToneId == "sadness" && highestScore <= tone.Score) { responseMessage = $"\U0001F614 \n"; highestScore = (double)tone.Score; } else if (tone.ToneId == "fear" && highestScore <= tone.Score) { responseMessage = $"\U0001F61F \n"; highestScore = (double)tone.Score; } else if (tone.ToneId == "anger" && highestScore <= tone.Score) { responseMessage = $"\U0001F620 \n"; highestScore = (double)tone.Score; } } return(responseMessage); }
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); }
//calculates & saves the Tone Analysis. private void OnToneAnalysis(DetailedResponse <ToneAnalysis> resp, IBMError error) { activeAnalysis = resp.Result; if (resp.Result.DocumentTone.ToneCategories != null) { float sadnessScore = 0; float happinessScore = 0; for (int j = 0; j < resp.Result.DocumentTone.ToneCategories[0].Tones.Count; j++) { switch (resp.Result.DocumentTone.ToneCategories[0].Tones[j].ToneName) { case "Sadness": sadnessScore = (float)resp.Result.DocumentTone.ToneCategories[0].Tones[j].Score; break; case "Joy": happinessScore = (float)resp.Result.DocumentTone.ToneCategories[0].Tones[j].Score; break; } } emotionScore = happinessScore - sadnessScore; PlayerPrefs.SetFloat(activeFile, emotionScore); } else { UnityEngine.Debug.Log("Error, something happened."); } }
// Update is called once per frame void Update() { // Pull in the most recent emotional state for each of the modalities if (useFacialEmotion) { currentFacialEmotion = facialAnalyzer.getCurrentEmotions(); currentFacialEmotion2 = facialAnalyzer2.getCurrentEmotions(); currentFACS = facialAnalyzer.getCurrentFACS(); currentFACS2 = facialAnalyzer2.getCurrentFACS(); // Debug.Log("got facial emotion struct"); } if (useWordSentimentEmotion) { currentWordSentimentEmotion = wordAnalyzer.getCurrentEmotions(); } if (useVocalToneEmotion) { currentVocalEmotion = vocalAnalyzer.getVocalToneResults(); } //Set mood tracker attributes CalculateMoodTrackerGeometry(); }
/// <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); }
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"); }
public JsonResult getToneAnalyzer(string text) { List <ToneAnalysis> finalData = new List <ToneAnalysis>(); if (!string.IsNullOrEmpty(text)) { ToneAnalysis data = WatsonToneAnalyzerHelper.PostDataAndGetResponse(text, "<UID>", "<PWD>"); finalData.Add(data); } return(Json(finalData, JsonRequestBehavior.AllowGet)); }
public ActionResult Custom(string customText) { List <ToneAnalysis> finalData = new List <ToneAnalysis>(); if (!string.IsNullOrEmpty(customText)) { ToneAnalysis data = WatsonToneAnalyzerHelper.PostDataAndGetResponse(customText, "539f5087-eae9-4cab-bf67-0c8902c7a163", "PjCjY8PqfaXs"); finalData.Add(data); } return(View(finalData)); }
// Update is called once per frame void Update() { // Display the webcam input //planeRenderer.material.mainTexture = camInputScript.Texture; quadRenderer.material.mainTexture = camInputScript.Texture; if (gameManagerScript.useVocalToneEmotion) { vocalToneResults = gameManagerScript.getCurrentVocalEmotion(); VocalPADText.text = "Temper: " + vocalToneResults.TemperVal + "\nArousal: " + vocalToneResults.ArousalVal + "\nValence: " + vocalToneResults.ValenceVal; } }
public static ToneAnalysis PostDataAndGetResponse(string input, string userId, string password) { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; string _Server = string.Format("https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version={0}", DateTime.Today.ToString("yyyy-MM-dd")); // Get the data to be analyzed for tone string postData = "{\"text\": \"" + input + "\"}"; // Create the web request var request = (HttpWebRequest)WebRequest.Create(_Server); // Configure the BlueMix credentials string auth = string.Format("{0}:{1}", userId, password); string auth64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth)); string credentials = string.Format("{0} {1}", "Basic", auth64); // Set the web request parameters request.Headers[HttpRequestHeader.Authorization] = credentials; request.Method = "POST"; request.Accept = "application/json"; request.ContentType = "application/json"; byte[] byteArray = Encoding.UTF8.GetBytes(JsonHelper.FormatJson(postData)); // Set the ContentLength property of the WebRequest request.ContentLength = byteArray.Length; // Get the request stream Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Get the response WebResponse response = request.GetResponse(); // Display the status var status = ((HttpWebResponse)response).StatusDescription; // Get the stream containing content returned by the service dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access StreamReader reader = new StreamReader(dataStream); // Read and format the content string responseFromServer = reader.ReadToEnd(); ToneAnalysis toneAnalysisData = new ToneAnalysis(); toneAnalysisData = JsonConvert.DeserializeObject <ToneAnalysis>(responseFromServer); toneAnalysisData.input = input; return(toneAnalysisData); }
public static List <ToneAnalysis> response(List <string> text) { List <ToneAnalysis> finalData = new List <ToneAnalysis>(); foreach (var item in text) { if (!string.IsNullOrEmpty(item)) { var regexCss = new Regex(@"(?></?\w+)(?>(?:[^>'""]+|'[^']*'|""[^""]*"")*)>", RegexOptions.Singleline | RegexOptions.IgnoreCase); var finalItem = regexCss.Replace(item, string.Empty); var newString = string.Join(" ", Regex.Split(finalItem, @"(?:\r\n|\n|\r|\t)")); StringBuilder sb = new StringBuilder(); char[] longChars = newString.ToCharArray(); int spaceCount = 0; //Using standard method with no library help for (int i = 0; i < longChars.Length; i++) { //If space then keep a count and move on until nonspace char is found if (longChars[i] == 32) { spaceCount++; continue; } //If more than one space then append a single space if (spaceCount > 1 && sb.Length > 0) { sb.Append(" "); } //Append the non space character sb.Append(longChars[i]); //Reset the space count spaceCount = 1; } ToneAnalysis data = WatsonToneAnalyzerHelper.PostDataAndGetResponse(sb.ToString(), "<UID>", "<PWD>"); finalData.Add(data); } } return(finalData); }
public ToneAnalysis AnalyzeTone(string text, List <Tone> filterTones, bool sentences = true) { ToneAnalysis result = null; if (string.IsNullOrEmpty(text)) { throw new ArgumentNullException("parameter: text"); } try { JObject json = new JObject( new JProperty("text", text)); IRequest request = this.Client.WithAuthentication(this.UserName, this.Password) .PostAsync(this.Endpoint + PATH_TONE) .WithArgument("version", VERSION_DATE_2016_05_19) .WithArgument("sentences", sentences); if (filterTones != null && filterTones.Count > 0) { request.WithArgument("tones", filterTones.Select(t => t.ToString().ToLower()) .Aggregate((a, b) => a + ", " + b)); } result = request.WithBody <JObject>(json, MediaTypeHeaderValue.Parse(HttpMediaType.APPLICATION_JSON)) .As <ToneAnalysis>() .Result; } catch (AggregateException ae) { throw ae.Flatten(); } return(result); }
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); }
public void AnalyzeTone_Success_With_Text() { IClient client = this.CreateClient(); IRequest request = Substitute.For <IRequest>(); #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 DocumentTone() { ToneCategories = new List <ToneCategory>() { new ToneCategory() { CategoryName = "string", CategoryId = "string", Tones = new List <ToneScore>() { new ToneScore() { ToneName = "string", ToneId = "string", Score = 0 } } } } } }; #endregion client.PostAsync(Arg.Any <string>()) .Returns(request); request.WithArgument(Arg.Any <string>(), Arg.Any <object>()) .Returns(request); request.WithBody <JObject>(Arg.Any <JObject>(), Arg.Any <MediaTypeHeaderValue>()) .Returns(request); request.As <ToneAnalysis>() .Returns(Task.FromResult(response)); ToneAnalyzerService service = new ToneAnalyzerService(client); var analyzeTone = service.AnalyzeTone("A word is dead when it is said, some say. Emily Dickinson"); Assert.IsNotNull(analyzeTone); client.Received().PostAsync(Arg.Any <string>()); Assert.IsTrue(analyzeTone.DocumentTone.ToneCategories.Count >= 1); }
public void Tone_Success_With_ToneInput() { IClient client = CreateClient(); #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 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.WithArgument(Arg.Any <string>(), Arg.Any <List <string> >()) .Returns(request); request.WithArgument(Arg.Any <string>(), Arg.Any <bool>()) .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"); Assert.IsNotNull(analyzeTone); client.Received().PostAsync(Arg.Any <string>()); Assert.IsNotNull(analyzeTone.DocumentTone); Assert.IsNotNull(analyzeTone.DocumentTone.ToneCategories); Assert.IsTrue(analyzeTone.DocumentTone.ToneCategories.Count >= 1); Assert.IsNotNull(analyzeTone.SentencesTone); Assert.IsTrue(analyzeTone.SentencesTone.Count >= 1); Assert.IsNotNull(analyzeTone.SentencesTone[0].ToneCategories); Assert.IsTrue(analyzeTone.SentencesTone[0].SentenceId == 0); Assert.IsTrue(analyzeTone.SentencesTone[0].Text == "string"); Assert.IsTrue(analyzeTone.SentencesTone[0].ToneCategories.Count >= 1); Assert.IsTrue(analyzeTone.SentencesTone[0].ToneCategories[0].CategoryId == "string"); Assert.IsTrue(analyzeTone.SentencesTone[0].ToneCategories[0].CategoryName == "string"); Assert.IsNotNull(analyzeTone.SentencesTone[0].ToneCategories[0].Tones); Assert.IsTrue(analyzeTone.SentencesTone[0].ToneCategories[0].Tones.Count >= 1); Assert.IsTrue(analyzeTone.SentencesTone[0].ToneCategories[0].Tones[0].ToneName == "string"); Assert.IsTrue(analyzeTone.SentencesTone[0].ToneCategories[0].Tones[0].ToneId == "string"); Assert.IsTrue(analyzeTone.SentencesTone[0].ToneCategories[0].Tones[0].Score == 0); }
public HeroCard ScatterResponseGenerator(ToneAnalysis postReponse, CounterState state, User currentUser) { double joy = 0; double anger = 0; double sadness = 0; double fear = 0; int x = 0; int y = 0; string[] userNames = { "-", "-", "-" }; foreach (ToneScore tone in postReponse.DocumentTone.Tones) { if (tone.ToneId == "joy") { joy = (double)tone.Score; } else if (tone.ToneId == "anger") { anger = (double)tone.Score; } else if (tone.ToneId == "sadness") { sadness = (double)tone.Score; } else if (tone.ToneId == "fear") { fear = (double)tone.Score; } } int numberOfTones = (int)(Math.Ceiling(joy) + Math.Ceiling(anger) + Math.Ceiling(fear) + Math.Ceiling(sadness)); if ((Math.Ceiling(joy) + Math.Ceiling(anger) + Math.Ceiling(fear) + Math.Ceiling(sadness)) != 0) { x = 50 + (int)Math.Ceiling(49 * ((0.5 * joy) + (0.5 * anger) + (0.8 * fear) - (0.6 * sadness)) / numberOfTones); y = 50 + (int)Math.Ceiling(49 * ((0.9 * joy) - (0.5 * anger) - (0.6 * fear) - (0.8 * sadness)) / numberOfTones); } if (currentUser.X == 0) { currentUser.X += x; } else { currentUser.X = (int)((0.4 * x) + (0.6 * currentUser.X)); } if (currentUser.Y == 0) { currentUser.Y += y; } else { currentUser.Y = (int)((0.4 * y) + (0.6 * currentUser.Y)); } List <User> updatedUsers = new List <User>(); string finalX = string.Empty; string finalY = string.Empty; foreach (User user in state.Users) { if (user.UserId == currentUser.UserId) { updatedUsers.Add(currentUser); finalX += currentUser.X + ","; finalY += currentUser.Y + ","; } else { updatedUsers.Add(user); finalX += user.X + ","; finalY += user.Y + ","; } userNames[state.Users.IndexOf(user)] = user.UserName; } state.Users = updatedUsers; /** * List<int> updatedRadius = new List<int>(); * state.Radius.ForEach(radius => updatedRadius.Add(radius - 10)); * updatedRadius.Add(100); * state.Radius = updatedRadius; * * string radiusString = string.Empty; * state.Radius.ForEach(radius => radiusString += radius + ","); * * radiusString = radiusString.Remove(radiusString.Length - 1); */ finalX = finalX.Remove(finalX.Length - 1); finalY = finalY.Remove(finalY.Length - 1); state.ScatterURL = "https://chart.googleapis.com/chart?cht=s&chs=470x400&chm=R,d10300,0,0.5,1|R,ffd800,0,0,0.5|r,008000,0,1,0.5&chco=000000|0c00fc|5700a3,ffffff&chxt=x,x,y,y&chdl=" + userNames[0] + "|" + userNames[1] + "|" + userNames[2] + "&chxr=0,-1,1|1,-1,1|2,-1,1|3,-1,1&chxl=1:|low%20arousal|high%20arousal|3:|displeasure|pleasure&chxs=0,ff0000|1,ff0000|2,0000ff|3,0000ff&chd=t:" + finalX + "|" + finalY; HeroCard heroCard = new HeroCard { Text = "Your current State: ", Images = new List <CardImage> { new CardImage(state.ScatterURL) }, }; return(heroCard); }
public HeroCard GraphResponseGenerator(ToneAnalysis postReponse, CounterState state) { state.TurnCount += 1; string graphURL = "https://chart.googleapis.com/chart?cht=lc&chco=FF0000,000000,00FF00,0000FF&chdl=Anger|Fear|Joy|Sadness&chxr=0,0," + state.TurnCount + "|1,0.5,1&chs=250x150&chxt=x,y&chd=t4:"; int joy = 0; int anger = 0; int sadness = 0; int fear = 0; foreach (ToneScore tone in postReponse.DocumentTone.Tones) { int score = (int)(100 * (tone.Score - 0.5) * 2); if (tone.ToneId == "joy") { joy = score; } else if (tone.ToneId == "anger") { anger = score; } else if (tone.ToneId == "sadness") { sadness = score; } else if (tone.ToneId == "fear") { fear = score; } } if (state.Joy == string.Empty) { state.Joy += joy; } else { state.Joy += "," + joy; } if (state.Anger == string.Empty) { state.Anger += anger; } else { state.Anger += "," + anger; } if (state.Sadness == string.Empty) { state.Sadness += sadness; } else { state.Sadness += "," + sadness; } if (state.Fear == string.Empty) { state.Fear += fear; } else { state.Fear += "," + fear; } graphURL = graphURL + state.Anger + '|' + state.Fear + '|' + state.Joy + '|' + state.Sadness; HeroCard heroCard = new HeroCard { Text = "Your current State: ", Images = new List <CardImage> { new CardImage(graphURL) }, }; return(heroCard); }
public void Tone_ContentTypeEmpty() { #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 ToneInput toneInput = new ToneInput() { Text = Arg.Any <string>() }; ToneAnalyzerService service = new ToneAnalyzerService("username", "password", versionDate); var analyzeTone = service.Tone(toneInput, null); }
private void OnGetToneAnalyze(ToneAnalysis resp, Dictionary <string, object> customData) { Log.Debug("ExampleToneAnalyzer.OnGetToneAnalyze()", "Tone Analyzer - Analyze Response: {0}", customData["json"].ToString()); Test(resp != null); _analyzeToneTested = true; }
private void OnGetToneAnalyze(ToneAnalysis resp, Dictionary <string, object> customData) { // Example response from Tone Analyzer ( Version 2017-05-25) // { "document_tone":{ "tones":[{"score":1.0,"tone_id":"joy","tone_name":"Joy"}]}} double anger = resp.DocumentTone.ToneCategories[0].Tones[0].Score.Value; double disgust = resp.DocumentTone.ToneCategories[0].Tones[1].Score.Value; double fear = resp.DocumentTone.ToneCategories[0].Tones[2].Score.Value; double joy = resp.DocumentTone.ToneCategories[0].Tones[3].Score.Value; double sadness = resp.DocumentTone.ToneCategories[0].Tones[4].Score.Value; var tones = new SortedDictionary <string, double> { { "anger", anger }, { "disgust", disgust }, { "fear", fear }, { "joy", joy }, { "sadness", sadness }, }; // max_tone gets the tone which has the highest value. string max_tone = tones.Aggregate((l, right) => l.Value > right.Value ? l : right).Key; //if this tone is bigger than the threshold we set, then we'll change the Octopus colour. if (tones[max_tone] > emotion_threshold) { Log.Debug("ToneHandler.OnGetToneAnalyze()", "Growing Max Tone = {0}", max_tone); //text_scroll.addline("test", max_tone); // emotional_states[max_tone] += emotional_growth; Color color = Color.red; // Default color to be overwritten. Tonea2.text = Tonea1.text; // Move old tone values up the debug log in the Debug Panel. TonePercenta2.text = TonePercenta1.text; Tonea1.text = ResultsField.text; TonePercenta1.text = PercentageField.text; ResultsField.text = max_tone; // Set the current value in the Debug Panel PercentageField.text = "(" + tones[max_tone] * 100 + "%)"; int intensity = 3; // This is by default, a new emotion we've not seen before if (Tonea1.text.CompareTo(ResultsField.text) == 0) { intensity = 2; // This is the same emotion twice if (Tonea2.text.CompareTo(ResultsField.text) == 0) { intensity = 1; // This is the same emotion three times } } // Set the color of the octopus depending on the tone from tone analyzer. // Multiply some of the RGB values to change the color based on intensity value set above. switch (max_tone) { case "joy": { color = new Color(0.2f * intensity, 0.9f, 0.2f * intensity); break; } case "anger": { color = new Color(0.9f, 0.2f * intensity, 0.2f * intensity); break; } case "fear": { color = new Color(0.9f, 0.9f, 0.2f * intensity); break; } case "sadness": { color = new Color(0.2f * intensity, 0.2f * intensity, 0.2f * intensity); break; } case "disgust": { color = new Color(0.9f, 0.2f * intensity, 0.9f); break; } } // Here we set the color - the Octopus has 3 renderers, one for the body (with 2 materials), and one for each eye - we'll adjust the color of each to the // same color here, but of course these could be set to different colors if you wanted just parts of the Octopus to change. Log.Debug("ToneHandler.OnGetToneAnalyze()", "Setting color = {0}", color); r = GameObject.Find("body").GetComponent <Renderer>(); rendEyeRight = GameObject.Find("eye - right").GetComponent <Renderer>(); rendEyeLeft = GameObject.Find("eye - left").GetComponent <Renderer>(); r.materials[0].SetColor("_Color", color); r.materials[1].SetColor("_Color", color); rendEyeLeft.material.SetColor("_Color", color); rendEyeRight.material.SetColor("_Color", color); Log.Debug("ToneHandler.OnGetToneAnalyze()", "Growing Max Tone = {0}", max_tone); } else // If the tone measured has a lower confidence level, then we'll indicate that we're not confident // and not change the color. { Log.Debug("ToneHandler.OnGetToneAnalyze()", "Max tone below Threshold {0}", emotion_threshold); Tonea2.text = Tonea1.text; TonePercenta2.text = TonePercenta1.text; Tonea1.text = ResultsField.text; TonePercenta1.text = PercentageField.text; PercentageField.text = ""; ResultsField.text = "Tone not clear"; } }
public void AnalyzeTone_Cath_Exception() { IClient client = this.CreateClient(); IRequest request = Substitute.For <IRequest>(); #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 DocumentTone() { ToneCategories = new List <ToneCategory>() { new ToneCategory() { CategoryName = "string", CategoryId = "string", Tones = new List <ToneScore>() { new ToneScore() { ToneName = "string", ToneId = "string", Score = 0 } } } } } }; #endregion client.PostAsync(Arg.Any <string>()) .Returns(request); request.WithArgument(Arg.Any <string>(), Arg.Any <object>()) .Returns(request); request.WithBody <JObject>(Arg.Any <JObject>(), Arg.Any <MediaTypeHeaderValue>()) .Returns(x => { throw new AggregateException(new Exception()); }); request.As <ToneAnalysis>() .Returns(Task.FromResult(response)); ToneAnalyzerService service = new ToneAnalyzerService(client); service.AnalyzeTone("A word is dead when it is said, some say. Emily Dickinson", new List <Tone>() { Tone.EMOTION, Tone.LANGUAGE, Tone.SOCIAL }, false); }