//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 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 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 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))); }
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); }
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); }
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 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); }
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 static void Main(string[] args) { string credentials = string.Empty; try { credentials = Utility.SimpleGet( Environment.GetEnvironmentVariable("VCAP_URL"), Environment.GetEnvironmentVariable("VCAP_USERNAME"), Environment.GetEnvironmentVariable("VCAP_PASSWORD")).Result; } catch (Exception e) { Console.WriteLine(string.Format("Failed to get credentials: {0}", e.Message)); } Task.WaitAll(); var vcapServices = JObject.Parse(credentials); var _url = vcapServices["tone_analyzer"]["url"].Value <string>(); var _username = vcapServices["tone_analyzer"]["username"].Value <string>(); var _password = vcapServices["tone_analyzer"]["password"].Value <string>(); var versionDate = "2016-05-19"; ToneAnalyzerService _toneAnalyzer = new ToneAnalyzerService(_username, _password, versionDate); _toneAnalyzer.Endpoint = _url; // Test PostTone ToneInput toneInput = new ToneInput() { Text = "How are you doing? My name is Taj!" }; var postToneResult = _toneAnalyzer.Tone(toneInput, "application/json", null); Console.WriteLine(string.Format("post tone result: {0}", JsonConvert.SerializeObject(postToneResult, Formatting.Indented))); // Test ToneChat ToneChatInput toneChatInput = new ToneChatInput() { Utterances = new List <Utterance>() { new Utterance() { Text = "Hello how are you?" } } }; var toneChatResult = _toneAnalyzer.ToneChat(toneChatInput); Console.WriteLine(string.Format("tone chat result: {0}", JsonConvert.SerializeObject(toneChatResult, Formatting.Indented))); Console.ReadKey(); }
public 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 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"); }
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); }
internal ToneResponse AnalyzeInternal(ToneSubmission submission) { var result = _toneAnalyzer.Tone( toneInput: new ToneInput() { Text = submission.Message } ); return(new ToneResponse() { Moods = result.Result.DocumentTone.Tones.ConvertEnumerableToEnumEnumerable <ToneMood, ToneScore>(input => input.ToneId.ParseEnum <ToneMood>()).ToList(), StatusCode = result.StatusCode, Success = result.StatusCode != 200 }); }
private ToneAnalysis Tone(ToneInput toneInput, string contentType, bool?sentences = null, List <string> tones = null, string contentLanguage = null, string acceptLanguage = null) { Console.WriteLine("\nAttempting to Tone()"); var result = _service.Tone(toneInput: toneInput, contentType: contentType, sentences: sentences, tones: tones, contentLanguage: contentLanguage, acceptLanguage: acceptLanguage); if (result != null) { Console.WriteLine("Tone() succeeded:\n{0}", JsonConvert.SerializeObject(result, Formatting.Indented)); } else { Console.WriteLine("Failed to Tone()"); } return(result); }
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); }
public void PostTone_Success() { byte[] bytes = Encoding.ASCII.GetBytes(inputText); MemoryStream toneInput = new MemoryStream(bytes); 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 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); }
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 void Tone() { IamAuthenticator authenticator = new IamAuthenticator( apikey: "{apikey}"); ToneAnalyzerService service = new ToneAnalyzerService("2017-09-21", authenticator); service.SetServiceUrl("{serviceUrl}"); byte[] bytes = Encoding.ASCII.GetBytes("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!"); MemoryStream toneInput = new MemoryStream(bytes); var result = service.Tone( toneInput: toneInput ); Console.WriteLine(result.Response); }
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 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); }
public static void Main(string[] args) { string credentials = string.Empty; #region Get Credentials string _endpoint = string.Empty; string _username = string.Empty; string _password = string.Empty; if (string.IsNullOrEmpty(credentials)) { var parentDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.Parent.Parent.FullName; string credentialsFilepath = parentDirectory + Path.DirectorySeparatorChar + "sdk-credentials" + Path.DirectorySeparatorChar + "credentials.json"; if (File.Exists(credentialsFilepath)) { try { credentials = File.ReadAllText(credentialsFilepath); credentials = Utility.AddTopLevelObjectToJson(credentials, "VCAP_SERVICES"); } catch (Exception e) { throw new Exception(string.Format("Failed to load credentials: {0}", e.Message)); } VcapCredentials vcapCredentials = JsonConvert.DeserializeObject <VcapCredentials>(credentials); var vcapServices = JObject.Parse(credentials); Credential credential = vcapCredentials.GetCredentialByname("tone-analyzer-sdk")[0].Credentials; _endpoint = credential.Url; _username = credential.Username; _password = credential.Password; } else { Console.WriteLine("Credentials file does not exist. Please define credentials."); _username = ""; _password = ""; _endpoint = ""; } } #endregion var versionDate = "2016-05-19"; ToneAnalyzerService _toneAnalyzer = new ToneAnalyzerService(_username, _password, versionDate); _toneAnalyzer.SetEndpoint(_endpoint); // Test PostTone ToneInput toneInput = new ToneInput() { Text = "How are you doing? My name is Taj!" }; var postToneResult = _toneAnalyzer.Tone(toneInput, "application/json", null); Console.WriteLine(string.Format("post tone result: {0}", JsonConvert.SerializeObject(postToneResult, Formatting.Indented))); // Test ToneChat ToneChatInput toneChatInput = new ToneChatInput() { Utterances = new List <Utterance>() { new Utterance() { Text = "Hello how are you?" } } }; var toneChatResult = _toneAnalyzer.ToneChat(toneChatInput); Console.WriteLine(string.Format("tone chat result: {0}", JsonConvert.SerializeObject(toneChatResult, Formatting.Indented))); Console.ReadKey(); }
/// <summary> /// Every conversation turn for our Echo Bot will call this method. /// There are no dialogs used, since it's "single turn" processing, meaning a single /// request and response. /// </summary> /// <param name="turnContext">A <see cref="ITurnContext"/> containing all the data needed /// for processing this conversation turn. </param> /// <param name="cancellationToken">(Optional) A <see cref="CancellationToken"/> that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns> /// <seealso cref="BotStateSet"/> /// <seealso cref="ConversationState"/> /// <seealso cref="IMiddleware"/> public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken)) { // Handle Message activity type, which is the main activity type for shown within a conversational interface // Message activities may contain text, speech, interactive cards, and binary or unknown attachments. // see https://aka.ms/about-bot-activity-message to learn more about the message and other activity types if (turnContext.Activity.Type == ActivityTypes.Message) { var response = turnContext.Activity.CreateReply(); // Get the conversation state from the turn context. var state = await _accessors.CounterState.GetAsync(turnContext, () => new CounterState()); bool exist = false; bool notAdmin = true; User currentUser = new User(); TimeSpan difference = DateTime.Now - state.Date; /* * IMongoCollection<Conversation> conversationCollection = null; * * var client = new MongoClient("mongodb://*****:*****@affectivefeedback-shard-00-00-advf9.azure.mongodb.net:27017,affectivefeedback-shard-00-01-advf9.azure.mongodb.net:27017,affectivefeedback-shard-00-02-advf9.azure.mongodb.net:27017/test?ssl=true&replicaSet=AffectiveFeedback-shard-0&authSource=admin&retryWrites=true"); * var database = client.GetDatabase("AffectiveFeedback"); * * if (state.CollectionName == string.Empty) * { * string collectionName = "ChatHistory-" + DateTime.Now.ToLongTimeString() + ".sqlite"; * collectionName = collectionName.Replace(":", "-"); * * state.CollectionName = collectionName; * * database.CreateCollection(state.CollectionName); * conversationCollection = database.GetCollection<Conversation>(state.CollectionName); * } * else * { * conversationCollection = database.GetCollection<Conversation>(state.CollectionName); * } */ if (turnContext.Activity.From.Id == "UECMZ1UKV:TEAAW1S5V" || turnContext.Activity.From.Id == "UEF40P8QP:TEDA8FEEL") { notAdmin = false; } else if (turnContext.Activity.Text.ToLower() == "emoji") { state.FeedbackType = turnContext.Activity.Text.ToLower(); response.Text = "Feedback Type changed to: Emoji"; state.NeededDifference = TimeSpan.FromMinutes(0); } else if (turnContext.Activity.Text.ToLower() == "graph") { state.FeedbackType = turnContext.Activity.Text.ToLower(); response.Text = "Feedback Type changed to: Graph"; state.NeededDifference = TimeSpan.FromSeconds(60); } else if (turnContext.Activity.Text.ToLower() == "empathy") { state.FeedbackType = turnContext.Activity.Text.ToLower(); response.Text = "Feedback Type changed to: Empathy"; state.NeededDifference = TimeSpan.FromSeconds(60); } else if (turnContext.Activity.Text.ToLower() == "scatter") { state.FeedbackType = turnContext.Activity.Text.ToLower(); response.Text = "Feedback Type changed to: Scatter"; state.NeededDifference = TimeSpan.FromSeconds(60); } else if (turnContext.Activity.Text == "Yes, I want to see our current state.") { HeroCard heroCard = new HeroCard { Title = "You're current State", Images = new List <CardImage> { new CardImage(state.ScatterURL) }, }; response.Attachments = new List <Attachment>() { heroCard.ToAttachment() }; state.SendImage = true; } else if (turnContext.Activity.Text == "Gib den usernamen aus!.!") { response.Text += turnContext.Activity.From.Id; } else { foreach (User user in state.Users) { if (user.UserId == turnContext.Activity.From.Id) { exist = true; currentUser = user; } } if (exist == false) { currentUser = new User(turnContext.Activity.From.Id); currentUser.UserName = turnContext.Activity.From.Name; if (turnContext.Activity.From.Name == "jordyn77") { currentUser.UserName = "******"; } else if (turnContext.Activity.From.Name == "zayo") { currentUser.UserName = "******"; } else if (turnContext.Activity.From.Name == "sihicracip") { currentUser.UserName = "******"; } else { currentUser.UserName = turnContext.Activity.From.Name; } state.Users.Add(currentUser); } string username = "******"; string password = "******"; var versionDate = "2017-09-21"; var versionDate1 = "2018-03-19"; string apikey = "X8a8d3FSqoadDqcWMsRe2hDd5uSeQR9E6gcm92zIxXMA"; string url = "https://gateway-fra.watsonplatform.net/natural-language-understanding/api"; /* * TokenOptions iamAssistantTokenOptions = new TokenOptions() * { * IamApiKey = apikey, * ServiceUrl = url, * }; * * NaturalLanguageUnderstandingService understandingService = new NaturalLanguageUnderstandingService(iamAssistantTokenOptions, versionDate1); * * Parameters parameters = new Parameters() * { * Text = "This is very good news!!", * }; * * var result = understandingService.Analyze(parameters); */ ToneAnalyzerService toneAnalyzer = new ToneAnalyzerService(username, password, versionDate); ToneInput toneInput = new ToneInput() { Text = turnContext.Activity.Text, }; var postToneResult = toneAnalyzer.Tone(toneInput, "application/json", null); Conversation conversation = new Conversation(turnContext.Activity.From.Id, turnContext.Activity.Text, postToneResult.ToString()); // conversationCollection.InsertOne(conversation); // foreach (Tone tone in tones) if (state.FeedbackType == "emoji") { response.Text = EmojiResponseGenerator(postToneResult); } else if (state.FeedbackType == "graph") { response.Attachments = new List <Attachment>() { GraphResponseGenerator(postToneResult, state).ToAttachment() }; } else if (state.FeedbackType == "scatter") { response.Attachments = new List <Attachment>() { ScatterResponseGenerator(postToneResult, state, currentUser).ToAttachment() }; } else if (state.FeedbackType == "empathy") { HeroCard heroCard = EmpathyResponseGenerator(postToneResult, state, currentUser); string responseText = string.Empty; foreach (User user1 in state.Users) { foreach (User user2 in state.Users) { double distance = Math.Abs(Math.Sqrt(Math.Pow(user1.X - user2.X, 2) + Math.Pow(user1.Y - user2.Y, 2))); if (distance > 50 && responseText == string.Empty) { responseText = "Your team mood is dispersed."; } } if (user1.X >= 40 && user1.X < 60 && user1.Y < 40 && responseText == string.Empty) { responseText = "You're working hard. Keep on trying. \n \U0001F917"; } } foreach (User user1 in state.Users) { if (user1.X < 40 && user1.Y < 40 && responseText == string.Empty) { responseText = "Don't let yourself down. You can do this. \n \U0001F917"; } } foreach (User user1 in state.Users) { if (user1.X >= 60 && user1.Y < 40 && responseText == string.Empty) { responseText = "Don't worry. You can do this. \n \U0001F917"; } } foreach (User user1 in state.Users) { if (user1.X >= 40 && user1.X < 70 && user1.Y >= 40 && user1.Y < 50 && responseText == string.Empty) { responseText = "You're working hard. Keep on trying. \n \U0001F917"; } } foreach (User user1 in state.Users) { if (user1.X >= 70 && user1.Y >= 40 && user1.Y < 50 && responseText == string.Empty) { responseText = "You're doing great. \n \U0001F917"; } } heroCard.Title = responseText; response.Attachments = new List <Attachment>() { heroCard.ToAttachment() }; } } if (notAdmin && (difference >= state.NeededDifference || state.SendImage)) { await turnContext.SendActivityAsync(response); if (!state.SendImage) { state.Date = DateTime.Now; } state.SendImage = false; } notAdmin = true; // Set the property using the accessor. await _accessors.CounterState.SetAsync(turnContext, state); // Save the new turn count into the conversation state. await _accessors.ConversationState.SaveChangesAsync(turnContext); } else { await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected"); } }
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); }
public void Tone_ToneInputEmpty() { #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 ToneAnalyzerService service = new ToneAnalyzerService(versionDate, new NoAuthAuthenticator()); var analyzeTone = service.Tone(null, "application/json"); }