public void Setup() { #region Get Credentials 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)); } } else { Console.WriteLine("Credentials file does not exist."); } VcapCredentials vcapCredentials = JsonConvert.DeserializeObject <VcapCredentials>(credentials); var vcapServices = JObject.Parse(credentials); Credential credential = vcapCredentials.GetCredentialByname("language-translator-sdk")[0].Credentials; _endpoint = credential.Url; _username = credential.Username; _password = credential.Password; } #endregion }
private IEnumerator GetCredentials() { //Credentials credentials = new Credentials(_username, _password, _url); #region Get Credentials via internal service VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; var vcapUrl = Environment.GetEnvironmentVariable("VCAP_URL"); var vcapUsername = Environment.GetEnvironmentVariable("VCAP_USERNAME"); var vcapPassword = Environment.GetEnvironmentVariable("VCAP_PASSWORD"); using (SimpleGet simpleGet = new SimpleGet(vcapUrl, vcapUsername, vcapPassword)) { while (!simpleGet.IsComplete) { yield return(null); } result = simpleGet.Result; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["conversation"]; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); //_workspaceId = credential.WorkspaceId.ToString(); #endregion // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); _service = new Assistant(credentials); _service.VersionDate = _versionDate; Runnable.Run(Examples()); }
private 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("text-to-speech-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 string _synthesizeText = "Hello, welcome to the Watson dotnet SDK!"; Text synthesizeText = new Text { _Text = _synthesizeText }; var _service = new TextToSpeechService(_username, _password); _service.SetEndpoint(_endpoint); // MemoryStream Result with .wav data var synthesizeResult = _service.Synthesize(synthesizeText, "audio/wav"); Console.ReadKey(); }
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; string _workspaceID = 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("conversation-sdk")[0].Credentials; _endpoint = credential.Url; _username = credential.Username; _password = credential.Password; _workspaceID = credential.WorkspaceId; } else { Console.WriteLine("Credentials file does not exist. Please define credentials."); _username = ""; _password = ""; _endpoint = ""; _workspaceID = ""; } } #endregion // Uncomment to run the service example. ConversationServiceExample _conversationExample = new ConversationServiceExample(_endpoint, _username, _password, _workspaceID); // Uncomment to run the context example. ConversationContextExample _converationContextExample = new ConversationContextExample(_endpoint, _username, _password, _workspaceID); Console.ReadKey(); }
public void Setup() { #region Get Credentials 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"; objectStorageCredentialsInputFilepath = parentDirectory + Path.DirectorySeparatorChar + "sdk-credentials" + Path.DirectorySeparatorChar + "cloud-object-storage-credentials-input.json"; objectStorageCredentialsOutputFilepath = parentDirectory + Path.DirectorySeparatorChar + "sdk-credentials" + Path.DirectorySeparatorChar + "cloud-object-storage-credentials-output.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)); } } else { Console.WriteLine("Credentials file does not exist."); } VcapCredentials vcapCredentials = JsonConvert.DeserializeObject <VcapCredentials>(credentials); var vcapServices = JObject.Parse(credentials); Credential credential = vcapCredentials.GetCredentialByname("compare-comply-sdk")[0].Credentials; endpoint = credential.Url; apikey = credential.IamApikey; } #endregion TokenOptions tokenOptions = new TokenOptions() { ServiceUrl = endpoint, IamApiKey = apikey }; service = new CompareComplyService(tokenOptions, versionDate); }
public void Setup() { Console.WriteLine(string.Format("\nSetting up test")); #region Get Credentials 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)); } } else { Console.WriteLine("Credentials file does not exist."); } VcapCredentials vcapCredentials = JsonConvert.DeserializeObject <VcapCredentials>(credentials); var vcapServices = JObject.Parse(credentials); Credential credential = vcapCredentials.GetCredentialByname("visual-recognition-iam-sdk")[0].Credentials; _endpoint = credential.Url; _apikey = credential.IamApikey; } #endregion TokenOptions tokenOptions = new TokenOptions() { IamApiKey = _apikey, ServiceUrl = _endpoint }; _service = new VisualRecognitionService(tokenOptions, "2018-03-19"); _service.Client.BaseClient.Timeout = TimeSpan.FromMinutes(120); }
public void Setup() { #region Get Credentials 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)); } } else { Console.WriteLine("Credentials file does not exist."); } VcapCredentials vcapCredentials = JsonConvert.DeserializeObject <VcapCredentials>(credentials); var vcapServices = JObject.Parse(credentials); Credential credential = vcapCredentials.GetCredentialByname("natural-language-understanding-sdk")[0].Credentials; endpoint = credential.Url; apikey = credential.IamApikey; } #endregion TokenOptions tokenOptions = new TokenOptions() { IamApiKey = apikey, ServiceUrl = endpoint }; service = new NaturalLanguageUnderstandingService(tokenOptions, "2017-02-27"); service.SetEndpoint(endpoint); }
static void Main(string[] args) { #region Get Credentials 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)); } } else { Console.WriteLine("Credentials file does not exist."); } VcapCredentials vcapCredentials = JsonConvert.DeserializeObject <VcapCredentials>(credentials); var vcapServices = JObject.Parse(credentials); Credential credential = vcapCredentials.GetCredentialByname("visual-recognition-sdk-cf")[0].Credentials; _endpoint = credential.Url; _apikey = credential.ApiKey; } #endregion VisualRecognitionServiceExample _visualRecognitionExample = new VisualRecognitionServiceExample(_apikey, _versionDate); Console.ReadKey(); }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; var vcapUrl = Environment.GetEnvironmentVariable("VCAP_URL"); var vcapUsername = Environment.GetEnvironmentVariable("VCAP_USERNAME"); var vcapPassword = Environment.GetEnvironmentVariable("VCAP_PASSWORD"); using (SimpleGet simpleGet = new SimpleGet(vcapUrl, vcapUsername, vcapPassword)) { while (!simpleGet.IsComplete) { yield return(null); } result = simpleGet.Result; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["conversation"]; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); _workspaceId = credential.WorkspaceId.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); _conversation = new Conversation(credentials); _conversation.VersionDate = _conversationVersionDate; // Test initate with empty string if (!_conversation.Message(OnSuccess, OnFail, _workspaceId, "")) { Log.Debug("TestConversation.RunTest()", "Failed to message!"); } // Test initiate with empty string message object MessageRequest messageRequest = new MessageRequest() { input = new Dictionary <string, object>() { { "text", "" } }, context = _context }; if (!_conversation.Message(OnSuccess, OnFail, _workspaceId, messageRequest)) { Log.Debug("TestConversation.RunTest()", "Failed to message!"); } if (!_conversation.Message(OnSuccess, OnFail, _workspaceId, "hello")) { Log.Debug("TestConversation.RunTest()", "Failed to message!"); } while (_waitingForResponse) { yield return(null); } _waitingForResponse = true; _questionCount++; AskQuestion(); while (_waitingForResponse) { yield return(null); } _questionCount++; _waitingForResponse = true; AskQuestion(); while (_waitingForResponse) { yield return(null); } _questionCount++; _waitingForResponse = true; AskQuestion(); while (_waitingForResponse) { yield return(null); } _questionCount++; _waitingForResponse = true; AskQuestion(); while (_waitingForResponse) { yield return(null); } Log.Debug("TestConversation.RunTest()", "Conversation examples complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; var vcapUrl = Environment.GetEnvironmentVariable("VCAP_URL"); var vcapUsername = Environment.GetEnvironmentVariable("VCAP_USERNAME"); var vcapPassword = Environment.GetEnvironmentVariable("VCAP_PASSWORD"); using (SimpleGet simpleGet = new SimpleGet(vcapUrl, vcapUsername, vcapPassword)) { while (!simpleGet.IsComplete) { yield return(null); } result = simpleGet.Result; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["text_to_speech"]; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; _textToSpeech = new TextToSpeech(credentials); // Synthesize Log.Debug("TestTextToSpeech.RunTest()", "Attempting synthesize."); _textToSpeech.Voice = VoiceType.en_US_Allison; _textToSpeech.ToSpeech(HandleToSpeechCallback, OnFail, _testString, true); while (!_synthesizeTested) { yield return(null); } // Synthesize Conversation string Log.Debug("TestTextToSpeech.RunTest()", "Attempting synthesize a string as returned by Watson Conversation."); _textToSpeech.Voice = VoiceType.en_US_Allison; _textToSpeech.ToSpeech(HandleConversationToSpeechCallback, OnFail, _testConversationString, true); while (!_synthesizeConversationTested) { yield return(null); } // Get Voices Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get voices."); _textToSpeech.GetVoices(OnGetVoices, OnFail); while (!_getVoicesTested) { yield return(null); } // Get Voice Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get voice {0}.", VoiceType.en_US_Allison); _textToSpeech.GetVoice(OnGetVoice, OnFail, VoiceType.en_US_Allison); while (!_getVoiceTested) { yield return(null); } // Get Pronunciation Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get pronunciation of {0}", _testWord); _textToSpeech.GetPronunciation(OnGetPronunciation, OnFail, _testWord, VoiceType.en_US_Allison); while (!_getPronuciationTested) { yield return(null); } // Get Customizations Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get a list of customizations"); _textToSpeech.GetCustomizations(OnGetCustomizations, OnFail); while (!_getCustomizationsTested) { yield return(null); } // Create Customization Log.Debug("TestTextToSpeech.RunTest()", "Attempting to create a customization"); _textToSpeech.CreateCustomization(OnCreateCustomization, OnFail, _customizationName, _customizationLanguage, _customizationDescription); while (!_createCustomizationTested) { yield return(null); } // Get Customization Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get a customization"); if (!_textToSpeech.GetCustomization(OnGetCustomization, OnFail, _createdCustomizationId)) { Log.Debug("TestTextToSpeech.RunTest()", "Failed to get custom voice model!"); } while (!_getCustomizationTested) { yield return(null); } // Update Customization Log.Debug("TestTextToSpeech.RunTest()", "Attempting to update a customization"); Word[] wordsToUpdateCustomization = { new Word() { word = "hello", translation = "hullo" }, new Word() { word = "goodbye", translation = "gbye" }, new Word() { word = "hi", translation = "ohioooo" } }; _customVoiceUpdate = new CustomVoiceUpdate() { words = wordsToUpdateCustomization, description = "My updated description", name = "My updated name" }; if (!_textToSpeech.UpdateCustomization(OnUpdateCustomization, OnFail, _createdCustomizationId, _customVoiceUpdate)) { Log.Debug("TestTextToSpeech.UpdateCustomization()", "Failed to update customization!"); } while (!_updateCustomizationTested) { yield return(null); } // Get Customization Words Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get a customization's words"); if (!_textToSpeech.GetCustomizationWords(OnGetCustomizationWords, OnFail, _createdCustomizationId)) { Log.Debug("TestTextToSpeech.GetCustomizationWords()", "Failed to get {0} words!", _createdCustomizationId); } while (!_getCustomizationWordsTested) { yield return(null); } // Add Customization Words Log.Debug("TestTextToSpeech.RunTest()", "Attempting to add words to a customization"); Word[] wordArrayToAddToCustomization = { new Word() { word = "bananna", translation = "arange" }, new Word() { word = "orange", translation = "gbye" }, new Word() { word = "tomato", translation = "tomahto" } }; Words wordsToAddToCustomization = new Words() { words = wordArrayToAddToCustomization }; if (!_textToSpeech.AddCustomizationWords(OnAddCustomizationWords, OnFail, _createdCustomizationId, wordsToAddToCustomization)) { Log.Debug("TestTextToSpeech.AddCustomizationWords()", "Failed to add words to {0}!", _createdCustomizationId); } while (!_addCustomizationWordsTested) { yield return(null); } // Get Customization Word Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get the translation of a custom voice model's word."); string customIdentifierWord = wordsToUpdateCustomization[0].word; if (!_textToSpeech.GetCustomizationWord(OnGetCustomizationWord, OnFail, _createdCustomizationId, customIdentifierWord)) { Log.Debug("TestTextToSpeech.GetCustomizationWord()", "Failed to get the translation of {0} from {1}!", customIdentifierWord, _createdCustomizationId); } while (!_getCustomizationWordTested) { yield return(null); } // Delete Customization Word Log.Debug("TestTextToSpeech.RunTest()", "Attempting to delete customization word from custom voice model."); string wordToDelete = "goodbye"; if (!_textToSpeech.DeleteCustomizationWord(OnDeleteCustomizationWord, OnFail, _createdCustomizationId, wordToDelete)) { Log.Debug("TestTextToSpeech.DeleteCustomizationWord()", "Failed to delete {0} from {1}!", wordToDelete, _createdCustomizationId); } while (!_deleteCustomizationWordTested) { yield return(null); } // Delete Customization Log.Debug("TestTextToSpeech.RunTest()", "Attempting to delete a customization"); if (!_textToSpeech.DeleteCustomization(OnDeleteCustomization, OnFail, _createdCustomizationId)) { Log.Debug("TestTextToSpeech.DeleteCustomization()", "Failed to delete custom voice model!"); } while (!_deleteCustomizationTested) { yield return(null); } Log.Debug("TestTextToSpeech.RunTest()", "Text to Speech examples complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; string credentialsFilepath = "../sdk-credentials/credentials.json"; // Load credentials file if it exists. If it doesn't exist, don't run the tests. if (File.Exists(credentialsFilepath)) { result = File.ReadAllText(credentialsFilepath); } else { yield break; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.GetCredentialByname("language-translator-sdk")[0].Credentials; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; _languageTranslator = new LanguageTranslator(credentials); _forcedGlossaryFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/glossary.tmx"; if (!_languageTranslator.GetTranslation(OnGetTranslation, OnFail, _pharseToTranslate, "en", "es")) { Log.Debug("TestLanguageTranslator.GetTranslation()", "Failed to translate."); } while (!_getTranslationTested) { yield return(null); } if (!_languageTranslator.GetModels(OnGetModels, OnFail)) { Log.Debug("TestLanguageTranslator.GetModels()", "Failed to get models."); } while (!_getModelsTested) { yield return(null); } if (!_languageTranslator.CreateModel(OnCreateModel, OnFail, _baseModelName, _customModelName, _forcedGlossaryFilePath)) { Log.Debug("TestLanguageTranslator.CreateModel()", "Failed to create model."); } while (!_createModelTested) { yield return(null); } if (!_languageTranslator.GetModel(OnGetModel, OnFail, _customLanguageModelId)) { Log.Debug("TestLanguageTranslator.GetModel()", "Failed to get model."); } while (!_getModelTested) { yield return(null); } if (!_languageTranslator.DeleteModel(OnDeleteModel, OnFail, _customLanguageModelId)) { Log.Debug("TestLanguageTranslator.DeleteModel()", "Failed to delete model."); } while (!_deleteModelTested) { yield return(null); } if (!_languageTranslator.Identify(OnIdentify, OnFail, _pharseToTranslate)) { Log.Debug("TestLanguageTranslator.Identify()", "Failed to identify language."); } while (!_identifyTested) { yield return(null); } if (!_languageTranslator.GetLanguages(OnGetLanguages, OnFail)) { Log.Debug("TestLanguageTranslator.GetLanguages()", "Failed to get languages."); } while (!_getLanguagesTested) { yield return(null); } Log.Debug("TestLanguageTranslator.RunTest()", "Language Translator examples complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; string credentialsFilepath = "../sdk-credentials/credentials.json"; // Load credentials file if it exists. If it doesn't exist, don't run the tests. if (File.Exists(credentialsFilepath)) { result = File.ReadAllText(credentialsFilepath); } else { yield break; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.GetCredentialByname("discovery-sdk")[0].Credentials; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); _discovery = new Discovery(credentials); _discovery.VersionDate = _discoveryVersionDate; _filePathToIngest = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/Discovery/constitution.pdf"; _documentFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/Discovery/constitution.pdf"; // Get Environments Log.Debug("TestDiscovery.RunTest()", "Attempting to get environments"); if (!_discovery.GetEnvironments(OnGetEnvironments, OnFail)) { Log.Debug("TestDiscovery.GetEnvironments()", "Failed to get environments"); } while (!_getEnvironmentsTested) { yield return(null); } // Wait for environment to be ready Runnable.Run(CheckEnvironmentState(0f)); while (!_isEnvironmentReady) { yield return(null); } // GetEnvironment Log.Debug("TestDiscovery.RunTest()", "Attempting to get environment"); if (!_discovery.GetEnvironment(OnGetEnvironment, OnFail, _environmentId)) { Log.Debug("TestDiscovery.GetEnvironment()", "Failed to get environment"); } while (!_getEnvironmentTested) { yield return(null); } // Get Configurations Log.Debug("TestDiscovery.RunTest()", "Attempting to get configurations"); if (!_discovery.GetConfigurations(OnGetConfigurations, OnFail, _environmentId)) { Log.Debug("TestDiscovery.GetConfigurations()", "Failed to get configurations"); } while (!_getConfigurationsTested) { yield return(null); } // Add Configuration Log.Debug("TestDiscovery.RunTest()", "Attempting to add configuration"); if (!_discovery.AddConfiguration(OnAddConfiguration, OnFail, _environmentId, _configurationJson.Replace("{guid}", System.Guid.NewGuid().ToString()))) { Log.Debug("TestDiscovery.AddConfiguration()", "Failed to add configuration"); } while (!_addConfigurationTested) { yield return(null); } // Get Configuration Log.Debug("TestDiscovery.RunTest()", "Attempting to get configuration"); if (!_discovery.GetConfiguration(OnGetConfiguration, OnFail, _environmentId, _createdConfigurationID)) { Log.Debug("TestDiscovery.GetConfiguration()", "Failed to get configuration"); } while (!_getConfigurationTested) { yield return(null); } // Preview Configuration Log.Debug("TestDiscovery.RunTest()", "Attempting to preview configuration"); if (!_discovery.PreviewConfiguration(OnPreviewConfiguration, OnFail, _environmentId, _createdConfigurationID, null, _filePathToIngest, _metadata)) { Log.Debug("TestDiscovery.PreviewConfiguration()", "Failed to preview configuration"); } while (!_previewConfigurationTested) { yield return(null); } // Get Collections Log.Debug("TestDiscovery.RunTest()", "Attempting to get collections"); if (!_discovery.GetCollections(OnGetCollections, OnFail, _environmentId)) { Log.Debug("TestDiscovery.GetCollections()", "Failed to get collections"); } while (!_getCollectionsTested) { yield return(null); } // Add Collection Log.Debug("TestDiscovery.RunTest()", "Attempting to add collection"); if (!_discovery.AddCollection(OnAddCollection, OnFail, _environmentId, _createdCollectionName + System.Guid.NewGuid().ToString(), _createdCollectionDescription, _createdConfigurationID)) { Log.Debug("TestDiscovery.AddCollection()", "Failed to add collection"); } while (!_addCollectionTested) { yield return(null); } // Get Collection Log.Debug("TestDiscovery.RunTest()", "Attempting to get collection"); if (!_discovery.GetCollection(OnGetCollection, OnFail, _environmentId, _createdCollectionId)) { Log.Debug("TestDiscovery.GetCollection()", "Failed to get collection"); } while (!_getCollectionTested) { yield return(null); } if (!_discovery.GetFields(OnGetFields, OnFail, _environmentId, _createdCollectionId)) { Log.Debug("TestDiscovery.GetFields()", "Failed to get fields"); } while (!_getFieldsTested) { yield return(null); } // Add Document Log.Debug("TestDiscovery.RunTest()", "Attempting to add document"); if (!_discovery.AddDocument(OnAddDocument, OnFail, _environmentId, _createdCollectionId, _documentFilePath, _createdConfigurationID, null)) { Log.Debug("TestDiscovery.AddDocument()", "Failed to add document"); } while (!_addDocumentTested) { yield return(null); } // Get Document Log.Debug("TestDiscovery.RunTest()", "Attempting to get document"); if (!_discovery.GetDocument(OnGetDocument, OnFail, _environmentId, _createdCollectionId, _createdDocumentID)) { Log.Debug("TestDiscovery.GetDocument()", "Failed to get document"); } while (!_getDocumentTested) { yield return(null); } // Update Document Log.Debug("TestDiscovery.RunTest()", "Attempting to update document"); if (!_discovery.UpdateDocument(OnUpdateDocument, OnFail, _environmentId, _createdCollectionId, _createdDocumentID, _documentFilePath, _createdConfigurationID, null)) { Log.Debug("TestDiscovery.UpdateDocument()", "Failed to update document"); } while (!_updateDocumentTested) { yield return(null); } // Query Log.Debug("TestDiscovery.RunTest()", "Attempting to query"); if (!_discovery.Query(OnQuery, OnFail, _environmentId, _createdCollectionId, naturalLanguageQuery: _query)) { while (!_queryTested) { yield return(null); } } // List Credentials Log.Debug("TestDiscovery.RunTest()", "Attempting to list credentials"); _discovery.ListCredentials(OnListCredentials, OnFail, _environmentId); while (!_listCredentialsTested) { yield return(null); } // Create Credentials Log.Debug("TestDiscovery.RunTest()", "Attempting to create credentials"); SourceCredentials credentialsParameter = new SourceCredentials() { SourceType = SourceCredentials.SourceTypeEnum.box, CredentialDetails = new CredentialDetails() { CredentialType = CredentialDetails.CredentialTypeEnum.oauth2, EnterpriseId = "myEnterpriseId", ClientId = "myClientId", ClientSecret = "myClientSecret", PublicKeyId = "myPublicIdKey", Passphrase = "myPassphrase", PrivateKey = "myPrivateKey" } }; _discovery.CreateCredentials(OnCreateCredentials, OnFail, _environmentId, credentialsParameter); while (!_createCredentialsTested) { yield return(null); } // Get Credential Log.Debug("TestDiscovery.RunTest()", "Attempting to get credential"); _discovery.GetCredential(OnGetCredential, OnFail, _environmentId, _createdCredentialId); while (!_getCredentialTested) { yield return(null); } // Get metrics event rate Log.Debug("TestDiscovery.RunTest()", "Attempting to Get metrics event rate"); _discovery.GetMetricsEventRate(OnGetMetricsEventRate, OnFail); while (!_getMetricsEventRateTested) { yield return(null); } // Get metrics query Log.Debug("TestDiscovery.RunTest()", "Attempting to Get metrics query"); _discovery.GetMetricsQuery(OnGetMetricsQuery, OnFail); while (!_getMetricsQueryTested) { yield return(null); } // Get metrics query event Log.Debug("TestDiscovery.RunTest()", "Attempting to Get metrics query event"); _discovery.GetMetricsQueryEvent(OnGetMetricsQueryEvent, OnFail); while (!_getMetricsQueryEventTested) { yield return(null); } // Get metrics query no result Log.Debug("TestDiscovery.RunTest()", "Attempting to Get metrics query no result"); _discovery.GetMetricsQueryNoResults(OnGetMetricsQueryNoResult, OnFail); while (!_getMetricsQueryNoResultTested) { yield return(null); } // Get metrics query token event Log.Debug("TestDiscovery.RunTest()", "Attempting to Get metrics query token event"); _discovery.GetMetricsQueryTokenEvent(OnGetMetricsQueryTokenEvent, OnFail); while (!_getMetricsQueryTokenEventTested) { yield return(null); } // Query log Log.Debug("TestDiscovery.RunTest()", "Attempting to Query log"); _discovery.QueryLog(OnQueryLog, OnFail); while (!_queryLogTested) { yield return(null); } // Create event Log.Debug("TestDiscovery.RunTest()", "Attempting to create event"); CreateEventObject queryEvent = new CreateEventObject() { Type = CreateEventObject.TypeEnum.click, Data = new EventData() { EnvironmentId = _environmentId, SessionToken = _sessionToken, CollectionId = _createdCollectionId, DocumentId = _createdDocumentID } }; _discovery.CreateEvent(OnCreateEvent, OnFail, queryEvent); while (!_createEventTested) { yield return(null); } // DeleteCredential Log.Debug("TestDiscovery.RunTest()", "Attempting to delete credential"); _discovery.DeleteCredentials(OnDeleteCredentials, OnFail, _environmentId, _createdCredentialId); while (!_deleteCredentialsTested) { yield return(null); } // Delete Document Log.Debug("TestDiscovery.RunTest()", "Attempting to delete document {0}", _createdDocumentID); if (!_discovery.DeleteDocument(OnDeleteDocument, OnFail, _environmentId, _createdCollectionId, _createdDocumentID)) { Log.Debug("TestDiscovery.DeleteDocument()", "Failed to delete document"); } while (!_deleteDocumentTested) { yield return(null); } _isEnvironmentReady = false; Runnable.Run(CheckEnvironmentState(_waitTime)); while (!_isEnvironmentReady) { yield return(null); } // Delete Collection Log.Debug("TestDiscovery.RunTest()", "Attempting to delete collection {0}", _createdCollectionId); if (!_discovery.DeleteCollection(OnDeleteCollection, OnFail, _environmentId, _createdCollectionId)) { Log.Debug("TestDiscovery.DeleteCollection()", "Failed to delete collection"); } while (!_deleteCollectionTested) { yield return(null); } _isEnvironmentReady = false; Runnable.Run(CheckEnvironmentState(_waitTime)); while (!_isEnvironmentReady) { yield return(null); } // Delete Configuration Log.Debug("TestDiscovery.RunTest()", "Attempting to delete configuration {0}", _createdConfigurationID); if (!_discovery.DeleteConfiguration(OnDeleteConfiguration, OnFail, _environmentId, _createdConfigurationID)) { Log.Debug("TestDiscovery.DeleteConfiguration()", "Failed to delete configuration"); } while (!_deleteConfigurationTested) { yield return(null); } // Delete User Data Log.Debug("TestDiscovery.RunTest()", "Attempting to delete user data."); _discovery.DeleteUserData(OnDeleteUserData, OnFail, "test-unity-user-id"); while (!_deleteUserDataTested) { yield return(null); } Log.Debug("TestDiscovery.RunTest()", "Discovery unit tests complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; string credentialsFilepath = "../sdk-credentials/credentials.json"; // Load credentials file if it exists. If it doesn't exist, don't run the tests. if (File.Exists(credentialsFilepath)) { result = File.ReadAllText(credentialsFilepath); } else { yield break; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.GetCredentialByname("language-translator-sdk")[0].Credentials; _url = credential.Url.ToString(); // Create credential and instantiate service TokenOptions tokenOptions = new TokenOptions() { IamApiKey = credential.IamApikey, IamUrl = credential.IamUrl }; Credentials credentials = new Credentials(tokenOptions, credential.Url); // Wait for tokendata while (!credentials.HasIamTokenData()) { yield return(null); } _languageTranslator = new LanguageTranslator(_versionDate, credentials); if (!_languageTranslator.GetTranslation(OnGetTranslation, OnFail, _pharseToTranslate, "en", "es")) { Log.Debug("TestLanguageTranslator.GetTranslation()", "Failed to translate."); } while (!_getTranslationTested) { yield return(null); } if (!_languageTranslator.GetModels(OnGetModels, OnFail)) { Log.Debug("TestLanguageTranslator.GetModels()", "Failed to get models."); } while (!_getModelsTested) { yield return(null); } if (!_languageTranslator.GetModel(OnGetModel, OnFail, "en-es")) { Log.Debug("TestLanguageTranslator.GetModel()", "Failed to get model."); } while (!_getModelTested) { yield return(null); } if (!_languageTranslator.Identify(OnIdentify, OnFail, _pharseToTranslate)) { Log.Debug("TestLanguageTranslator.Identify()", "Failed to identify language."); } while (!_identifyTested) { yield return(null); } if (!_languageTranslator.GetLanguages(OnGetLanguages, OnFail)) { Log.Debug("TestLanguageTranslator.GetLanguages()", "Failed to get languages."); } while (!_getLanguagesTested) { yield return(null); } Log.Debug("TestLanguageTranslator.RunTest()", "Language Translator examples complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); try { VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; // Get credentials from a credential file defined in environmental variables in the VCAP_SERVICES format. // See https://www.ibm.com/watson/developercloud/doc/common/getting-started-variables.html. var environmentalVariable = Environment.GetEnvironmentVariable("VCAP_SERVICES"); var fileContent = File.ReadAllText(environmentalVariable); // Add in a parent object because Unity does not like to deserialize root level collection types. fileContent = Utility.AddTopLevelObjectToJson(fileContent, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(fileContent, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["language_translator"][TestCredentialIndex].Credentials; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); } catch { Log.Debug("TestLanguageTranslator", "Failed to get credentials from VCAP_SERVICES file. Please configure credentials to run this test. For more information, see: https://github.com/watson-developer-cloud/unity-sdk/#authentication"); } // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; _languageTranslator = new LanguageTranslator(credentials); _forcedGlossaryFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/glossary.tmx"; if (!_languageTranslator.GetTranslation(_pharseToTranslate, "en", "es", OnGetTranslation)) { Log.Debug("TestLanguageTranslator", "Failed to translate."); } while (!_getTranslationTested) { yield return(null); } if (!_languageTranslator.GetModels(OnGetModels)) { Log.Debug("TestLanguageTranslator", "Failed to get models."); } while (!_getModelsTested) { yield return(null); } if (!_languageTranslator.CreateModel(OnCreateModel, _baseModelName, _customModelName, _forcedGlossaryFilePath)) { Log.Debug("TestLanguageTranslator", "Failed to create model."); } while (!_createModelTested) { yield return(null); } if (!_languageTranslator.GetModel(OnGetModel, _customLanguageModelId)) { Log.Debug("TestLanguageTranslator", "Failed to get model."); } while (!_getModelTested) { yield return(null); } if (!_languageTranslator.DeleteModel(OnDeleteModel, _customLanguageModelId)) { Log.Debug("TestLanguageTranslator", "Failed to delete model."); } while (!_deleteModelTested) { yield return(null); } if (!_languageTranslator.Identify(OnIdentify, _pharseToTranslate)) { Log.Debug("TestLanguageTranslator", "Failed to identify language."); } while (!_identifyTested) { yield return(null); } if (!_languageTranslator.GetLanguages(OnGetLanguages)) { Log.Debug("TestLanguageTranslator", "Failed to get languages."); } while (!_getLanguagesTested) { yield return(null); } Log.Debug("TestLanguageTranslator", "Language Translator examples complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; string credentialsFilepath = "../sdk-credentials/credentials.json"; // Load credentials file if it exists. If it doesn't exist, don't run the tests. if (File.Exists(credentialsFilepath)) { result = File.ReadAllText(credentialsFilepath); } else { yield break; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.GetCredentialByname("assistant-sdk")[0].Credentials; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); _workspaceId = credential.WorkspaceId.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); _service = new Assistant(credentials); _service.VersionDate = _assistantVersionDate; // List Workspaces _service.ListWorkspaces(OnListWorkspaces, OnFail); while (!_listWorkspacesTested) { yield return(null); } // Create Workspace CreateWorkspace workspace = new CreateWorkspace() { Name = _createdWorkspaceName, Description = _createdWorkspaceDescription, Language = _createdWorkspaceLanguage, LearningOptOut = true }; _service.CreateWorkspace(OnCreateWorkspace, OnFail, workspace); while (!_createWorkspaceTested) { yield return(null); } // Get Workspace _service.GetWorkspace(OnGetWorkspace, OnFail, _createdWorkspaceId); while (!_getWorkspaceTested) { yield return(null); } // Update Workspace UpdateWorkspace updateWorkspace = new UpdateWorkspace() { Name = _createdWorkspaceName + "-updated", Description = _createdWorkspaceDescription + "-updated", Language = _createdWorkspaceLanguage }; _service.UpdateWorkspace(OnUpdateWorkspace, OnFail, _createdWorkspaceId, updateWorkspace); while (!_updateWorkspaceTested) { yield return(null); } // Message with customerID // Create customData object Dictionary <string, object> customData = new Dictionary <string, object>(); // Create a dictionary of custom headers Dictionary <string, string> customHeaders = new Dictionary <string, string>(); // Add to the header dictionary customHeaders.Add("X-Watson-Metadata", "customer_id=" + _unitySdkTestCustomerID); // Add the header dictionary to the custom data object customData.Add(Constants.String.CUSTOM_REQUEST_HEADERS, customHeaders); Dictionary <string, object> input = new Dictionary <string, object>(); input.Add("text", _inputString); MessageRequest messageRequest = new MessageRequest() { Input = input }; _service.Message(OnMessage, OnFail, _workspaceId, messageRequest, null, customData); while (!_messageTested) { yield return(null); } _messageTested = false; input["text"] = _conversationString0; MessageRequest messageRequest0 = new MessageRequest() { Input = input, Context = _context }; _service.Message(OnMessage, OnFail, _workspaceId, messageRequest0); while (!_messageTested) { yield return(null); } _messageTested = false; input["text"] = _conversationString1; MessageRequest messageRequest1 = new MessageRequest() { Input = input, Context = _context }; _service.Message(OnMessage, OnFail, _workspaceId, messageRequest1); while (!_messageTested) { yield return(null); } _messageTested = false; input["text"] = _conversationString2; MessageRequest messageRequest2 = new MessageRequest() { Input = input, Context = _context }; _service.Message(OnMessage, OnFail, _workspaceId, messageRequest2); while (!_messageTested) { yield return(null); } // List Intents _service.ListIntents(OnListIntents, OnFail, _createdWorkspaceId); while (!_listIntentsTested) { yield return(null); } // Create Intent CreateIntent createIntent = new CreateIntent() { Intent = _createdIntent, Description = _createdIntentDescription }; _service.CreateIntent(OnCreateIntent, OnFail, _createdWorkspaceId, createIntent); while (!_createIntentTested) { yield return(null); } // Get Intent _service.GetIntent(OnGetIntent, OnFail, _createdWorkspaceId, _createdIntent); while (!_getIntentTested) { yield return(null); } // Update Intents string updatedIntent = _createdIntent + "-updated"; string updatedIntentDescription = _createdIntentDescription + "-updated"; UpdateIntent updateIntent = new UpdateIntent() { Intent = updatedIntent, Description = updatedIntentDescription }; _service.UpdateIntent(OnUpdateIntent, OnFail, _createdWorkspaceId, _createdIntent, updateIntent); while (!_updateIntentTested) { yield return(null); } // List Examples _service.ListExamples(OnListExamples, OnFail, _createdWorkspaceId, updatedIntent); while (!_listExamplesTested) { yield return(null); } // Create Examples CreateExample createExample = new CreateExample() { Text = _createdExample }; _service.CreateExample(OnCreateExample, OnFail, _createdWorkspaceId, updatedIntent, createExample); while (!_createExampleTested) { yield return(null); } // Get Example _service.GetExample(OnGetExample, OnFail, _createdWorkspaceId, updatedIntent, _createdExample); while (!_getExampleTested) { yield return(null); } // Update Examples string updatedExample = _createdExample + "-updated"; UpdateExample updateExample = new UpdateExample() { Text = updatedExample }; _service.UpdateExample(OnUpdateExample, OnFail, _createdWorkspaceId, updatedIntent, _createdExample, updateExample); while (!_updateExampleTested) { yield return(null); } // List Entities _service.ListEntities(OnListEntities, OnFail, _createdWorkspaceId); while (!_listEntitiesTested) { yield return(null); } // Create Entities CreateEntity entity = new CreateEntity() { Entity = _createdEntity, Description = _createdEntityDescription }; _service.CreateEntity(OnCreateEntity, OnFail, _createdWorkspaceId, entity); while (!_createEntityTested) { yield return(null); } // Get Entity _service.GetEntity(OnGetEntity, OnFail, _createdWorkspaceId, _createdEntity); while (!_getEntityTested) { yield return(null); } // Update Entities string updatedEntity = _createdEntity + "-updated"; string updatedEntityDescription = _createdEntityDescription + "-updated"; UpdateEntity updateEntity = new UpdateEntity() { Entity = updatedEntity, Description = updatedEntityDescription }; _service.UpdateEntity(OnUpdateEntity, OnFail, _createdWorkspaceId, _createdEntity, updateEntity); while (!_updateEntityTested) { yield return(null); } // List Values _service.ListValues(OnListValues, OnFail, _createdWorkspaceId, updatedEntity); while (!_listValuesTested) { yield return(null); } // Create Values CreateValue value = new CreateValue() { Value = _createdValue }; _service.CreateValue(OnCreateValue, OnFail, _createdWorkspaceId, updatedEntity, value); while (!_createValueTested) { yield return(null); } // Get Value _service.GetValue(OnGetValue, OnFail, _createdWorkspaceId, updatedEntity, _createdValue); while (!_getValueTested) { yield return(null); } // Update Values string updatedValue = _createdValue + "-updated"; UpdateValue updateValue = new UpdateValue() { Value = updatedValue }; _service.UpdateValue(OnUpdateValue, OnFail, _createdWorkspaceId, updatedEntity, _createdValue, updateValue); while (!_updateValueTested) { yield return(null); } // List Synonyms _service.ListSynonyms(OnListSynonyms, OnFail, _createdWorkspaceId, updatedEntity, updatedValue); while (!_listSynonymsTested) { yield return(null); } // Create Synonyms CreateSynonym synonym = new CreateSynonym() { Synonym = _createdSynonym }; _service.CreateSynonym(OnCreateSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, synonym); while (!_createSynonymTested) { yield return(null); } // Get Synonym _service.GetSynonym(OnGetSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, _createdSynonym); while (!_getSynonymTested) { yield return(null); } // Update Synonyms string updatedSynonym = _createdSynonym + "-updated"; UpdateSynonym updateSynonym = new UpdateSynonym() { Synonym = updatedSynonym }; _service.UpdateSynonym(OnUpdateSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, _createdSynonym, updateSynonym); while (!_updateSynonymTested) { yield return(null); } // List Dialog Nodes _service.ListDialogNodes(OnListDialogNodes, OnFail, _createdWorkspaceId); while (!_listDialogNodesTested) { yield return(null); } // Create Dialog Nodes CreateDialogNode createDialogNode = new CreateDialogNode() { DialogNode = _dialogNodeName, Description = _dialogNodeDesc }; _service.CreateDialogNode(OnCreateDialogNode, OnFail, _createdWorkspaceId, createDialogNode); while (!_createDialogNodeTested) { yield return(null); } // Get Dialog Node _service.GetDialogNode(OnGetDialogNode, OnFail, _createdWorkspaceId, _dialogNodeName); while (!_getDialogNodeTested) { yield return(null); } // Update Dialog Nodes string updatedDialogNodeName = _dialogNodeName + "_updated"; string updatedDialogNodeDescription = _dialogNodeDesc + "_updated"; UpdateDialogNode updateDialogNode = new UpdateDialogNode() { DialogNode = updatedDialogNodeName, Description = updatedDialogNodeDescription }; _service.UpdateDialogNode(OnUpdateDialogNode, OnFail, _createdWorkspaceId, _dialogNodeName, updateDialogNode); while (!_updateDialogNodeTested) { yield return(null); } // List Logs In Workspace _service.ListLogs(OnListLogs, OnFail, _createdWorkspaceId); while (!_listLogsInWorkspaceTested) { yield return(null); } // List All Logs var filter = "(language::en,request.context.metadata.deployment::deployment_1)"; _service.ListAllLogs(OnListAllLogs, OnFail, filter); while (!_listAllLogsTested) { yield return(null); } // List Counterexamples _service.ListCounterexamples(OnListCounterexamples, OnFail, _createdWorkspaceId); while (!_listCounterexamplesTested) { yield return(null); } // Create Counterexamples CreateCounterexample example = new CreateCounterexample() { Text = _createdCounterExampleText }; _service.CreateCounterexample(OnCreateCounterexample, OnFail, _createdWorkspaceId, example); while (!_createCounterexampleTested) { yield return(null); } // Get Counterexample _service.GetCounterexample(OnGetCounterexample, OnFail, _createdWorkspaceId, _createdCounterExampleText); while (!_getCounterexampleTested) { yield return(null); } // Update Counterexamples string updatedCounterExampleText = _createdCounterExampleText + "-updated"; UpdateCounterexample updateCounterExample = new UpdateCounterexample() { Text = updatedCounterExampleText }; _service.UpdateCounterexample(OnUpdateCounterexample, OnFail, _createdWorkspaceId, _createdCounterExampleText, updateCounterExample); while (!_updateCounterexampleTested) { yield return(null); } // Delete Counterexample _service.DeleteCounterexample(OnDeleteCounterexample, OnFail, _createdWorkspaceId, updatedCounterExampleText); while (!_deleteCounterexampleTested) { yield return(null); } // Delete Dialog Node _service.DeleteDialogNode(OnDeleteDialogNode, OnFail, _createdWorkspaceId, updatedDialogNodeName); while (!_deleteDialogNodeTested) { yield return(null); } // Delete Synonym _service.DeleteSynonym(OnDeleteSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, updatedSynonym); while (!_deleteSynonymTested) { yield return(null); } // Delete Value _service.DeleteValue(OnDeleteValue, OnFail, _createdWorkspaceId, updatedEntity, updatedValue); while (!_deleteValueTested) { yield return(null); } // Delete Entity _service.DeleteEntity(OnDeleteEntity, OnFail, _createdWorkspaceId, updatedEntity); while (!_deleteEntityTested) { yield return(null); } // Delete Example _service.DeleteExample(OnDeleteExample, OnFail, _createdWorkspaceId, updatedIntent, updatedExample); while (!_deleteExampleTested) { yield return(null); } // Delete Intent _service.DeleteIntent(OnDeleteIntent, OnFail, _createdWorkspaceId, updatedIntent); while (!_deleteIntentTested) { yield return(null); } // Delete Workspace _service.DeleteWorkspace(OnDeleteWorkspace, OnFail, _createdWorkspaceId); while (!_deleteWorkspaceTested) { yield return(null); } // Delete User Data _service.DeleteUserData(OnDeleteUserData, OnFail, _unitySdkTestCustomerID); while (!_deleteUserDataTested) { yield return(null); } Log.Debug("TestAssistant.RunTest()", "Assistant examples complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; string credentialsFilepath = "../sdk-credentials/credentials.json"; // Load credentials file if it exists. If it doesn't exist, don't run the tests. if (File.Exists(credentialsFilepath)) { result = File.ReadAllText(credentialsFilepath); } else { yield break; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.GetCredentialByname("assistant-sdk")[0].Credentials; // Create credential and instantiate service TokenOptions tokenOptions = new TokenOptions() { IamApiKey = credential.IamApikey, }; _assistantId = credential.AssistantId.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(tokenOptions, _url); // Wait for tokendata while (!credentials.HasIamTokenData()) { yield return(null); } _service = new Assistant(credentials); _service.VersionDate = _assistantVersionDate; Log.Debug("TestAssistantV2.RunTest()", "Attempting to CreateSession"); _service.CreateSession(OnCreateSession, OnFail, _assistantId); while (!_createSessionTested) { yield return(null); } Log.Debug("TestAssistantV2.RunTest()", "Attempting to Message"); _service.Message(OnMessage0, OnFail, _assistantId, _sessionId); while (!_messageTested0) { yield return(null); } Log.Debug("TestAssistantV2.RunTest()", "Are you open on Christmas?"); MessageRequest messageRequest1 = new MessageRequest() { Input = new MessageInput() { Text = "Are you open on Christmas?" } }; _service.Message(OnMessage1, OnFail, _assistantId, _sessionId, messageRequest1); while (!_messageTested1) { yield return(null); } Log.Debug("TestAssistantV2.RunTest()", "What are your hours?"); MessageRequest messageRequest2 = new MessageRequest() { Input = new MessageInput() { Text = "What are your hours?" } }; _service.Message(OnMessage2, OnFail, _assistantId, _sessionId, messageRequest2); while (!_messageTested2) { yield return(null); } Log.Debug("TestAssistantV2.RunTest()", "I'd like to make an appointment for 12pm."); MessageRequest messageRequest3 = new MessageRequest() { Input = new MessageInput() { Text = "I'd like to make an appointment for 12pm." } }; _service.Message(OnMessage3, OnFail, _assistantId, _sessionId, messageRequest3); while (!_messageTested3) { yield return(null); } Log.Debug("TestAssistantV2.RunTest()", "On Friday please."); MessageRequest messageRequest4 = new MessageRequest() { Input = new MessageInput() { Text = "On Friday please." } }; _service.Message(OnMessage4, OnFail, _assistantId, _sessionId, messageRequest4); while (!_messageTested4) { yield return(null); } Log.Debug("TestAssistantV2.RunTest()", "Attempting to delete session"); _service.DeleteSession(OnDeleteSession, OnFail, _assistantId, _sessionId); while (!_deleteSessionTested) { yield return(null); } }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; var vcapUrl = Environment.GetEnvironmentVariable("VCAP_URL"); var vcapUsername = Environment.GetEnvironmentVariable("VCAP_USERNAME"); var vcapPassword = Environment.GetEnvironmentVariable("VCAP_PASSWORD"); using (SimpleGet simpleGet = new SimpleGet(vcapUrl, vcapUsername, vcapPassword)) { while (!simpleGet.IsComplete) { yield return(null); } result = simpleGet.Result; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["natural_language_classifier"]; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; naturalLanguageClassifier = new NaturalLanguageClassifier(credentials); // Get classifiers if (!naturalLanguageClassifier.GetClassifiers(OnGetClassifiers, OnFail)) { Log.Debug("TestNaturalLanguageClassifier.GetClassifiers()", "Failed to get classifiers!"); } while (!_getClassifiersTested) { yield return(null); } if (_classifierIds.Count == 0) { Log.Debug("TestNaturalLanguageClassifier.Examples()", "There are no trained classifiers. Please train a classifier..."); } if (_classifierIds.Count > 0) { // Get each classifier foreach (string classifierId in _classifierIds) { if (!naturalLanguageClassifier.GetClassifier(OnGetClassifier, OnFail, classifierId)) { Log.Debug("TestNaturalLanguageClassifier.GetClassifier()", "Failed to get classifier {0}!", classifierId); } } while (!_getClassifierTested) { yield return(null); } } if (!_areAnyClassifiersAvailable && _classifierIds.Count > 0) { Log.Debug("TestNaturalLanguageClassifier.Examples()", "All classifiers are training..."); } // Train classifier #if TRAIN_CLASSIFIER string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/weather_data_train.csv"; var trainingContent = File.ReadAllText(dataPath); if (!naturalLanguageClassifier.TrainClassifier(OnTrainClassifier, OnFail, _classifierName + "/" + DateTime.Now.ToString(), "en", trainingContent)) { Log.Debug("TestNaturalLanguageClassifier.TrainClassifier()", "Failed to train clasifier!"); } while (!_trainClassifierTested) { yield return(null); } #endif #if DELETE_TRAINED_CLASSIFIER if (!string.IsNullOrEmpty(_classifierToDelete)) { if (!naturalLanguageClassifier.DeleteClassifer(OnDeleteTrainedClassifier, OnFail, _classifierToDelete)) { Log.Debug("TestNaturalLanguageClassifier.DeleteClassifer()", "Failed to delete clasifier {0}!", _classifierToDelete); } } #endif // Classify if (_areAnyClassifiersAvailable) { if (!naturalLanguageClassifier.Classify(OnClassify, OnFail, _classifierId, _inputString)) { Log.Debug("TestNaturalLanguageClassifier.Classify()", "Failed to classify!"); } while (!_classifyTested) { yield return(null); } } // Classify Collection ClassifyCollectionInput classifyCollectionInput = new ClassifyCollectionInput() { collection = new List <ClassifyInput>() { new ClassifyInput() { text = "Is it hot outside?" }, new ClassifyInput() { text = "Is it going to rain?" } } }; if (_areAnyClassifiersAvailable) { if (!naturalLanguageClassifier.ClassifyCollection(OnClassifyCollection, OnFail, _classifierId, classifyCollectionInput)) { Log.Debug("TestNaturalLanguageClassifier.ClassifyCollection()", "Failed to classify!"); } while (!_classifyCollectionTested) { yield return(null); } } Log.Debug("TestNaturalLanguageClassifier.RunTest()", "Natural language classifier examples complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; string credentialsFilepath = "../sdk-credentials/credentials.json"; // Load credentials file if it exists. If it doesn't exist, don't run the tests. if (File.Exists(credentialsFilepath)) { result = File.ReadAllText(credentialsFilepath); } else { yield break; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.GetCredentialByname("conversation-sdk")[0].Credentials; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); //_workspaceId = credential.WorkspaceId.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); _conversation = new Conversation(credentials); _conversation.VersionDate = _conversationVersionDate; // Test initate with empty string if (!_conversation.Message(OnSuccess, OnFail, _workspaceId, "")) { Log.Debug("TestConversation.RunTest()", "Failed to message!"); } // Test initiate with empty string message object MessageRequest messageRequest = new MessageRequest() { input = new Dictionary <string, object>() { { "text", "" } }, context = _context }; if (!_conversation.Message(OnSuccess, OnFail, _workspaceId, messageRequest)) { Log.Debug("TestConversation.RunTest()", "Failed to message!"); } if (!_conversation.Message(OnSuccess, OnFail, _workspaceId, "hello")) { Log.Debug("TestConversation.RunTest()", "Failed to message!"); } while (_waitingForResponse) { yield return(null); } _waitingForResponse = true; _questionCount++; AskQuestion(); while (_waitingForResponse) { yield return(null); } _questionCount++; _waitingForResponse = true; AskQuestion(); while (_waitingForResponse) { yield return(null); } _questionCount++; _waitingForResponse = true; AskQuestion(); while (_waitingForResponse) { yield return(null); } _questionCount++; _waitingForResponse = true; AskQuestion(); while (_waitingForResponse) { yield return(null); } // Delete User Data _conversation.DeleteUserData(OnDeleteUserData, OnFail, "test-unity-user-id"); while (!_deleteUserDataTested) { yield return(null); } Log.Debug("TestConversation.RunTest()", "Conversation examples complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); contractAFilepath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/compare-comply/contract_A.pdf"; contractBFilepath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/compare-comply/contract_B.pdf"; tableFilepath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/compare-comply/TestTable.pdf"; string objectStorageCredentialsInputFilepath = "../sdk-credentials/cloud-object-storage-credentials-input.json"; string objectStorageCredentialsOutputFilepath = "../sdk-credentials/cloud-object-storage-credentials-output.json"; #region Get Credentials VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; string credentialsFilepath = "../sdk-credentials/credentials.json"; // Load credentials file if it exists. If it doesn't exist, don't run the tests. if (File.Exists(credentialsFilepath)) { result = File.ReadAllText(credentialsFilepath); } else { yield break; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.GetCredentialByname("compare-comply-sdk")[0].Credentials; _url = credential.Url.ToString(); // Create credential and instantiate service TokenOptions tokenOptions = new TokenOptions() { IamApiKey = credential.IamApikey }; #endregion Credentials credentials = new Credentials(tokenOptions, credential.Url); // Wait for tokendata while (!credentials.HasIamTokenData()) { yield return(null); } compareComply = new CompareComply(credentials); compareComply.VersionDate = versionDate; byte[] contractA = File.ReadAllBytes(contractAFilepath); byte[] contractB = File.ReadAllBytes(contractBFilepath); byte[] table = File.ReadAllBytes(tableFilepath); byte[] objectStorageCredentialsInputData = File.ReadAllBytes(objectStorageCredentialsInputFilepath); byte[] objectStorageCredentialsOutputData = File.ReadAllBytes(objectStorageCredentialsOutputFilepath); compareComply.ConvertToHtml(OnConvertToHtml, OnFail, contractA, fileContentType: "application/pdf"); while (!convertToHtmlTested) { yield return(null); } compareComply.ClassifyElements(OnClassifyElements, OnFail, contractA); while (!classifyElementsTested) { yield return(null); } compareComply.ExtractTables(OnExtractTables, OnFail, table); while (!extractTablesTested) { yield return(null); } compareComply.CompareDocuments(OnCompareDocuments, OnFail, contractA, contractB, file1ContentType: "application/pdf", file2ContentType: "application/pdf"); while (!compareDocumentsTested) { yield return(null); } DateTime before = new DateTime(2018, 11, 15); DateTime after = new DateTime(2018, 11, 14); compareComply.ListFeedback( successCallback: OnListFeedback, failCallback: OnFail, feedbackType: "element_classification", before: before, after: after, documentTitle: "unity-test-feedback-doc", modelId: "contracts", modelVersion: "2.0.0", categoryRemoved: "Responsibilities", categoryAdded: "Amendments", categoryNotChanged: "Audits", typeRemoved: "End User:Exclusion", typeAdded: "Disclaimer:Buyer", typeNotChanged: "Obligation:IBM", pageLimit: 1 ); while (!listFeedbackTested) { yield return(null); } #region Feedback Data FeedbackInput feedbackData = new FeedbackInput() { UserId = "user_id_123x", Comment = "Test feedback comment", FeedbackData = new FeedbackDataInput() { FeedbackType = "element_classification", Document = new ShortDoc() { Hash = "", Title = "doc title" }, ModelId = "contracts", ModelVersion = "11.00", Location = new Location() { Begin = 241, End = 237 }, Text = "1. IBM will provide a Senior Managing Consultant / expert resource, for up to 80 hours, to assist Florida Power & Light (FPL) with the creation of an IT infrastructure unit cost model for existing infrastructure.", OriginalLabels = new OriginalLabelsIn() { Types = new List <TypeLabel>() { new TypeLabel() { Label = new Label() { Nature = "Obligation", Party = "IBM" }, ProvenanceIds = new List <string>() { "85f5981a-ba91-44f5-9efa-0bd22e64b7bc", "ce0480a1-5ef1-4c3e-9861-3743b5610795" } }, new TypeLabel() { Label = new Label() { Nature = "End User", Party = "Exclusion" }, ProvenanceIds = new List <string>() { "85f5981a-ba91-44f5-9efa-0bd22e64b7bc", "ce0480a1-5ef1-4c3e-9861-3743b5610795" } } }, Categories = new List <Category>() { new Category() { Label = "Responsibilities", ProvenanceIds = new List <string>() { } }, new Category() { Label = "Amendments", ProvenanceIds = new List <string>() { } } } }, UpdatedLabels = new UpdatedLabelsIn() { Types = new List <TypeLabel>() { new TypeLabel() { Label = new Label() { Nature = "Obligation", Party = "IBM" } }, new TypeLabel() { Label = new Label() { Nature = "Disclaimer", Party = "buyer" } } }, Categories = new List <Category>() { new Category() { Label = "Responsibilities", }, new Category() { Label = "Audits" } } } } }; #endregion compareComply.AddFeedback( successCallback: OnAddFeedback, failCallback: OnFail, feedbackData: feedbackData ); while (!addFeedbackTested) { yield return(null); } // temporary fix for a bug requiring `x-watson-metadata` header Dictionary <string, object> customData = new Dictionary <string, object>(); Dictionary <string, string> customHeaders = new Dictionary <string, string>(); customHeaders.Add("x-watson-metadata", "customer_id=sdk-test-customer-id"); customData.Add(Constants.String.CUSTOM_REQUEST_HEADERS, customHeaders); compareComply.GetFeedback( successCallback: OnGetFeedback, failCallback: OnFail, feedbackId: feedbackId, modelId: "contracts", customData: customData ); while (!getFeedbackTested) { yield return(null); } compareComply.DeleteFeedback( successCallback: OnDeleteFeedback, failCallback: OnFail, feedbackId: feedbackId, modelId: "contracts" ); while (!deleteFeedbackTested) { yield return(null); } compareComply.ListBatches( successCallback: OnListBatches, failCallback: OnFail ); while (!listBatchesTested) { yield return(null); } compareComply.CreateBatch( successCallback: OnCreateBatch, failCallback: OnFail, function: "html_conversion", inputCredentialsFile: objectStorageCredentialsInputData, inputBucketLocation: "us-south", inputBucketName: "compare-comply-integration-test-bucket-input", outputCredentialsFile: objectStorageCredentialsOutputData, outputBucketLocation: "us-south", outputBucketName: "compare-comply-integration-test-bucket-output" ); while (!createBatchTested) { yield return(null); } compareComply.GetBatch( successCallback: OnGetBatch, failCallback: OnFail, batchId: batchId ); while (!getBatchTestsed) { yield return(null); } compareComply.UpdateBatch( successCallback: OnUpdateBatch, failCallback: OnFail, batchId: batchId, action: "rescan", modelId: "contracts" ); while (!updateBatchTested) { yield return(null); } Log.Debug("TestCompareComplyV1.RunTests()", "Compare and Comply integration tests complete!"); }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); try { VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; // Get credentials from a credential file defined in environmental variables in the VCAP_SERVICES format. // See https://www.ibm.com/watson/developercloud/doc/common/getting-started-variables.html. var environmentalVariable = Environment.GetEnvironmentVariable("VCAP_SERVICES"); var fileContent = File.ReadAllText(environmentalVariable); // Add in a parent object because Unity does not like to deserialize root level collection types. fileContent = Utility.AddTopLevelObjectToJson(fileContent, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(fileContent, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["tradeoff_analytics"][TestCredentialIndex].Credentials; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); } catch { Log.Debug("TestTradeoffAnalytics.RunTest()", "Failed to get credentials from VCAP_SERVICES file. Please configure credentials to run this test. For more information, see: https://github.com/watson-developer-cloud/unity-sdk/#authentication"); } // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; _tradeoffAnalytics = new TradeoffAnalytics(credentials); Problem problemToSolve = new Problem(); problemToSolve.subject = "Test Subject"; List <Column> listColumn = new List <Column>(); Column columnPrice = new Column(); columnPrice.description = "Price Column to minimize"; columnPrice.range = new ValueRange(); ((ValueRange)columnPrice.range).high = 600; ((ValueRange)columnPrice.range).low = 0; columnPrice.type = "numeric"; columnPrice.key = "price"; columnPrice.full_name = "Price"; columnPrice.goal = "min"; columnPrice.is_objective = true; columnPrice.format = "$####0.00"; Column columnWeight = new Column(); columnWeight.description = "Weight Column to minimize"; columnWeight.type = "numeric"; columnWeight.key = "weight"; columnWeight.full_name = "Weight"; columnWeight.goal = "min"; columnWeight.is_objective = true; columnWeight.format = "####0 g"; Column columnBrandName = new Column(); columnBrandName.description = "All Brand Names"; columnBrandName.type = "categorical"; columnBrandName.key = "brand"; columnBrandName.full_name = "Brand"; columnBrandName.goal = "max"; columnBrandName.is_objective = true; columnBrandName.preference = new string[] { "Samsung", "Apple", "HTC" }; columnBrandName.range = new CategoricalRange(); ((CategoricalRange)columnBrandName.range).keys = new string[] { "Samsung", "Apple", "HTC" }; listColumn.Add(columnPrice); listColumn.Add(columnWeight); // listColumn.Add(columnBrandName); problemToSolve.columns = listColumn.ToArray(); List <Option> listOption = new List <Option>(); Option option1 = new Option(); option1.key = "1"; option1.name = "Samsung Galaxy S4"; option1.values = new TestDataValue(); (option1.values as TestDataValue).weight = 130; (option1.values as TestDataValue).brand = "Samsung"; (option1.values as TestDataValue).price = 249; listOption.Add(option1); Option option2 = new Option(); option2.key = "2"; option2.name = "Apple iPhone 5"; option2.values = new TestDataValue(); (option2.values as TestDataValue).weight = 112; (option2.values as TestDataValue).brand = "Apple"; (option2.values as TestDataValue).price = 599; listOption.Add(option2); Option option3 = new Option(); option3.key = "3"; option3.name = "HTC One"; option3.values = new TestDataValue(); (option3.values as TestDataValue).weight = 143; (option3.values as TestDataValue).brand = "HTC"; (option3.values as TestDataValue).price = 299; listOption.Add(option3); problemToSolve.options = listOption.ToArray(); _tradeoffAnalytics.GetDilemma(OnGetDilemma, OnFail, problemToSolve, false); while (!_GetDillemaTested) { yield return(null); } Log.Debug("ExampleTradeoffAnalyitics.RunTest()", "Tradeoff analytics examples complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; var vcapUrl = Environment.GetEnvironmentVariable("VCAP_URL"); var vcapUsername = Environment.GetEnvironmentVariable("VCAP_USERNAME"); var vcapPassword = Environment.GetEnvironmentVariable("VCAP_PASSWORD"); using (SimpleGet simpleGet = new SimpleGet(vcapUrl, vcapUsername, vcapPassword)) { while (!simpleGet.IsComplete) { yield return(null); } result = simpleGet.Result; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["personality_insights"]; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; _personalityInsights = new PersonalityInsights(credentials); _personalityInsights.VersionDate = _personalityInsightsVersionDate; _dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; if (!_personalityInsights.GetProfile(OnGetProfileJson, OnFail, _dataPath, ContentType.TextHtml, ContentLanguage.English, ContentType.ApplicationJson, AcceptLanguage.English, true, true, true)) { Log.Debug("ExamplePersonalityInsights.GetProfile()", "Failed to get profile!"); } while (!_getProfileJsonTested) { yield return(null); } if (!_personalityInsights.GetProfile(OnGetProfileText, OnFail, _testString, ContentType.TextHtml, ContentLanguage.English, ContentType.ApplicationJson, AcceptLanguage.English, true, true, true)) { Log.Debug("ExamplePersonalityInsights.GetProfile()", "Failed to get profile!"); } while (!_getProfileTextTested) { yield return(null); } Log.Debug("ExamplePersonalityInsights.RunTest()", "Personality insights examples complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); // Test NaturalLanguageClassifier using loaded credentials NaturalLanguageClassifier autoNaturalLanguageClassifier = new NaturalLanguageClassifier(); while (!autoNaturalLanguageClassifier.Credentials.HasIamTokenData()) { yield return(null); } autoNaturalLanguageClassifier.GetClassifiers(OnAutoGetClassifiers, OnFail); while (!_autoGetClassifiersTested) { yield return(null); } VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; string credentialsFilepath = "../sdk-credentials/credentials.json"; // Load credentials file if it exists. If it doesn't exist, don't run the tests. if (File.Exists(credentialsFilepath)) { result = File.ReadAllText(credentialsFilepath); } else { yield break; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.GetCredentialByname("natural-language-classifier-sdk")[0].Credentials; // Create credential and instantiate service TokenOptions tokenOptions = new TokenOptions() { IamApiKey = credential.IamApikey, }; // Create credential and instantiate service Credentials credentials = new Credentials(tokenOptions, credential.Url); // Wait for tokendata while (!credentials.HasIamTokenData()) { yield return(null); } naturalLanguageClassifier = new NaturalLanguageClassifier(credentials); // Get classifiers if (!naturalLanguageClassifier.GetClassifiers(OnGetClassifiers, OnFail)) { Log.Debug("TestNaturalLanguageClassifier.GetClassifiers()", "Failed to get classifiers!"); } while (!_getClassifiersTested) { yield return(null); } if (_classifierIds.Count == 0) { Log.Debug("TestNaturalLanguageClassifier.Examples()", "There are no trained classifiers. Please train a classifier..."); } if (_classifierIds.Count > 0) { // Get each classifier foreach (string classifierId in _classifierIds) { if (!naturalLanguageClassifier.GetClassifier(OnGetClassifier, OnFail, classifierId)) { Log.Debug("TestNaturalLanguageClassifier.GetClassifier()", "Failed to get classifier {0}!", classifierId); } } while (!_getClassifierTested) { yield return(null); } } if (!_areAnyClassifiersAvailable && _classifierIds.Count > 0) { Log.Debug("TestNaturalLanguageClassifier.Examples()", "All classifiers are training..."); } // Train classifier #if TRAIN_CLASSIFIER string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/weather_data_train.csv"; var trainingContent = File.ReadAllText(dataPath); if (!naturalLanguageClassifier.TrainClassifier(OnTrainClassifier, OnFail, _classifierName + "/" + DateTime.Now.ToString(), "en", trainingContent)) { Log.Debug("TestNaturalLanguageClassifier.TrainClassifier()", "Failed to train clasifier!"); } while (!_trainClassifierTested) { yield return(null); } #endif #if DELETE_TRAINED_CLASSIFIER if (!string.IsNullOrEmpty(_classifierToDelete)) { if (!naturalLanguageClassifier.DeleteClassifer(OnDeleteTrainedClassifier, OnFail, _classifierToDelete)) { Log.Debug("TestNaturalLanguageClassifier.DeleteClassifer()", "Failed to delete clasifier {0}!", _classifierToDelete); } } #endif // Classify if (_areAnyClassifiersAvailable) { if (!naturalLanguageClassifier.Classify(OnClassify, OnFail, _classifierId, _inputString)) { Log.Debug("TestNaturalLanguageClassifier.Classify()", "Failed to classify!"); } while (!_classifyTested) { yield return(null); } } // Classify Collection ClassifyCollectionInput classifyCollectionInput = new ClassifyCollectionInput() { collection = new List <ClassifyInput>() { new ClassifyInput() { text = "Is it hot outside?" }, new ClassifyInput() { text = "Is it going to rain?" } } }; if (_areAnyClassifiersAvailable) { if (!naturalLanguageClassifier.ClassifyCollection(OnClassifyCollection, OnFail, _classifierId, classifyCollectionInput)) { Log.Debug("TestNaturalLanguageClassifier.ClassifyCollection()", "Failed to classify!"); } while (!_classifyCollectionTested) { yield return(null); } } Log.Debug("TestNaturalLanguageClassifier.RunTest()", "Natural language classifier examples complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); try { VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; // Get credentials from a credential file defined in environmental variables in the VCAP_SERVICES format. // See https://www.ibm.com/watson/developercloud/doc/common/getting-started-variables.html. var environmentalVariable = Environment.GetEnvironmentVariable("VCAP_SERVICES"); var fileContent = File.ReadAllText(environmentalVariable); // Add in a parent object because Unity does not like to deserialize root level collection types. fileContent = Utility.AddTopLevelObjectToJson(fileContent, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(fileContent, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["document_conversion"][TestCredentialIndex].Credentials; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); } catch { Log.Debug("TestDocumentConversion.RunTest()", "Failed to get credentials from VCAP_SERVICES file. Please configure credentials to run this test. For more information, see: https://github.com/watson-developer-cloud/unity-sdk/#authentication"); } // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; _documentConversion = new DocumentConversion(credentials); _examplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/watson_beats_jeopardy.html"; if (!_documentConversion.ConvertDocument(OnConvertDocument, OnFail, _examplePath, _conversionTarget)) { Log.Debug("TestDocumentConversion.RunTest()", "Document conversion failed!"); } while (!_convertDocumentTested) { yield return(null); } Log.Debug("TestDoucmentConversion.RunTest()", "Document conversion examples complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; string credentialsFilepath = "../sdk-credentials/credentials.json"; // Load credentials file if it exists. If it doesn't exist, don't run the tests. if (File.Exists(credentialsFilepath)) { result = File.ReadAllText(credentialsFilepath); } else { yield break; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.GetCredentialByname("assistant-sdk")[0].Credentials; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); _assistantId = credential.AssistantId.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); _service = new Assistant(credentials); _service.VersionDate = _assistantVersionDate; Log.Debug("TestAssistantV2.RunTest()", "Attempting to CreateSession"); _service.CreateSession(OnCreateSession, OnFail, _assistantId); while (!_createSessionTested) { yield return(null); } Log.Debug("TestAssistantV2.RunTest()", "Attempting to Message"); _service.Message(OnMessage, OnFail, _assistantId, _sessionId); while (!_messageTested) { yield return(null); } Log.Debug("TestAssistantV2.RunTest()", "Attempting to DeleteSession"); _service.DeleteSession(OnDeleteSession, OnFail, _assistantId, _sessionId); while (!_deleteSessionTested) { yield return(null); } }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; var vcapUrl = Environment.GetEnvironmentVariable("VCAP_URL"); var vcapUsername = Environment.GetEnvironmentVariable("VCAP_USERNAME"); var vcapPassword = Environment.GetEnvironmentVariable("VCAP_PASSWORD"); using (SimpleGet simpleGet = new SimpleGet(vcapUrl, vcapUsername, vcapPassword)) { while (!simpleGet.IsComplete) { yield return(null); } result = simpleGet.Result; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["speech_to_text"]; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; _speechToText = new SpeechToText(credentials); _customCorpusFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/theJabberwocky-utf8.txt"; _customWordsFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/test-stt-words.json"; _acousticResourceMimeType = Utility.GetMimeType(Path.GetExtension(_acousticResourceUrl)); Runnable.Run(DownloadAcousticResource()); while (!_isAudioLoaded) { yield return(null); } // Recognize Log.Debug("ExampleSpeechToText.Examples()", "Attempting to recognize"); List <string> keywords = new List <string>(); keywords.Add("speech"); _speechToText.KeywordsThreshold = 0.5f; _speechToText.InactivityTimeout = 120; _speechToText.StreamMultipart = false; _speechToText.Keywords = keywords.ToArray(); _speechToText.Recognize(HandleOnRecognize, OnFail, _acousticResourceData, _acousticResourceMimeType); while (!_recognizeTested) { yield return(null); } // Get models Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get models"); _speechToText.GetModels(HandleGetModels, OnFail); while (!_getModelsTested) { yield return(null); } // Get model Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get model {0}", _modelNameToGet); _speechToText.GetModel(HandleGetModel, OnFail, _modelNameToGet); while (!_getModelTested) { yield return(null); } // Get customizations Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get customizations"); _speechToText.GetCustomizations(HandleGetCustomizations, OnFail); while (!_getCustomizationsTested) { yield return(null); } // Create customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting create customization"); _speechToText.CreateCustomization(HandleCreateCustomization, OnFail, "unity-test-customization", "en-US_BroadbandModel", "Testing customization unity"); while (!_createCustomizationsTested) { yield return(null); } // Get customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get customization {0}", _createdCustomizationID); _speechToText.GetCustomization(HandleGetCustomization, OnFail, _createdCustomizationID); while (!_getCustomizationTested) { yield return(null); } // Get custom corpora Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom corpora for {0}", _createdCustomizationID); _speechToText.GetCustomCorpora(HandleGetCustomCorpora, OnFail, _createdCustomizationID); while (!_getCustomCorporaTested) { yield return(null); } // Add custom corpus Log.Debug("ExampleSpeechToText.Examples()", "Attempting to add custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); string corpusData = File.ReadAllText(_customCorpusFilePath); _speechToText.AddCustomCorpus(HandleAddCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName, true, corpusData); while (!_addCustomCorpusTested) { yield return(null); } // Get custom corpus Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); _speechToText.GetCustomCorpus(HandleGetCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName); while (!_getCustomCorpusTested) { yield return(null); } // Wait for customization Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Get custom words Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom words."); _speechToText.GetCustomWords(HandleGetCustomWords, OnFail, _createdCustomizationID); while (!_getCustomWordsTested) { yield return(null); } // Add custom words from path Log.Debug("ExampleSpeechToText.Examples()", "Attempting to add custom words in customization {0} using Words json path {1}", _createdCustomizationID, _customWordsFilePath); string customWords = File.ReadAllText(_customWordsFilePath); _speechToText.AddCustomWords(HandleAddCustomWordsFromPath, OnFail, _createdCustomizationID, customWords); while (!_addCustomWordsFromPathTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Add custom words from object Words words = new Words(); Word w0 = new Word(); List <Word> wordList = new List <Word>(); w0.word = "mikey"; w0.sounds_like = new string[1]; w0.sounds_like[0] = "my key"; w0.display_as = "Mikey"; wordList.Add(w0); Word w1 = new Word(); w1.word = "charlie"; w1.sounds_like = new string[1]; w1.sounds_like[0] = "char lee"; w1.display_as = "Charlie"; wordList.Add(w1); Word w2 = new Word(); w2.word = "bijou"; w2.sounds_like = new string[1]; w2.sounds_like[0] = "be joo"; w2.display_as = "Bijou"; wordList.Add(w2); words.words = wordList.ToArray(); Log.Debug("ExampleSpeechToText.Examples()", "Attempting to add custom words in customization {0} using Words object", _createdCustomizationID); _speechToText.AddCustomWords(HandleAddCustomWordsFromObject, OnFail, _createdCustomizationID, words); while (!_addCustomWordsFromObjectTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Get custom word Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom word {1} in customization {0}", _createdCustomizationID, words.words[0].word); _speechToText.GetCustomWord(HandleGetCustomWord, OnFail, _createdCustomizationID, words.words[0].word); while (!_getCustomWordTested) { yield return(null); } // Train customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to train customization {0}", _createdCustomizationID); _speechToText.TrainCustomization(HandleTrainCustomization, OnFail, _createdCustomizationID); while (!_trainCustomizationTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Upgrade customization - not currently implemented in service //Log.Debug("ExampleSpeechToText.Examples()", "Attempting to upgrade customization {0}", _createdCustomizationID); //_speechToText.UpgradeCustomization(HandleUpgradeCustomization, _createdCustomizationID); //while (!_upgradeCustomizationTested) // yield return null; // Delete custom word Log.Debug("ExampleSpeechToText.Examples()", "Attempting to delete custom word {1} in customization {0}", _createdCustomizationID, words.words[2].word); _speechToText.DeleteCustomWord(HandleDeleteCustomWord, OnFail, _createdCustomizationID, words.words[2].word); while (!_deleteCustomWordTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete custom corpus Log.Debug("ExampleSpeechToText.Examples()", "Attempting to delete custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); _speechToText.DeleteCustomCorpus(HandleDeleteCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName); while (!_deleteCustomCorpusTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } _readyToContinue = false; // Reset customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to reset customization {0}", _createdCustomizationID); _speechToText.ResetCustomization(HandleResetCustomization, OnFail, _createdCustomizationID); while (!_resetCustomizationTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to delete customization {0}", _createdCustomizationID); _speechToText.DeleteCustomization(HandleDeleteCustomization, OnFail, _createdCustomizationID); while (!_deleteCustomizationsTested) { yield return(null); } // List acoustic customizations Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get acoustic customizations"); _speechToText.GetCustomAcousticModels(HandleGetCustomAcousticModels, OnFail); while (!_getAcousticCustomizationsTested) { yield return(null); } // Create acoustic customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to create acoustic customization"); _speechToText.CreateAcousticCustomization(HandleCreateAcousticCustomization, OnFail, _createdAcousticModelName); while (!_createAcousticCustomizationsTested) { yield return(null); } // Get acoustic customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get acoustic customization {0}", _createdAcousticModelId); _speechToText.GetCustomAcousticModel(HandleGetCustomAcousticModel, OnFail, _createdAcousticModelId); while (!_getAcousticCustomizationTested) { yield return(null); } while (!_isAudioLoaded) { yield return(null); } // Create acoustic resource Log.Debug("ExampleSpeechToText.Examples()", "Attempting to create audio resource {1} on {0}", _createdAcousticModelId, _acousticResourceName); string mimeType = Utility.GetMimeType(Path.GetExtension(_acousticResourceUrl)); _speechToText.AddAcousticResource(HandleAddAcousticResource, OnFail, _createdAcousticModelId, _acousticResourceName, mimeType, mimeType, true, _acousticResourceData); while (!_addAcousticResourcesTested) { yield return(null); } // Wait for customization _isAcousticCustomizationReady = false; Runnable.Run(CheckAcousticCustomizationStatus(_createdAcousticModelId)); while (!_isAcousticCustomizationReady) { yield return(null); } // List acoustic resources Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get audio resources {0}", _createdAcousticModelId); _speechToText.GetCustomAcousticResources(HandleGetCustomAcousticResources, OnFail, _createdAcousticModelId); while (!_getAcousticResourcesTested) { yield return(null); } // Train acoustic customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to train acoustic customization {0}", _createdAcousticModelId); _speechToText.TrainAcousticCustomization(HandleTrainAcousticCustomization, OnFail, _createdAcousticModelId, null, true); while (!_trainAcousticCustomizationsTested) { yield return(null); } // Get acoustic resource Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get audio resource {1} from {0}", _createdAcousticModelId, _acousticResourceName); _speechToText.GetCustomAcousticResource(HandleGetCustomAcousticResource, OnFail, _createdAcousticModelId, _acousticResourceName); while (!_getAcousticResourceTested) { yield return(null); } // Wait for customization _isAcousticCustomizationReady = false; Runnable.Run(CheckAcousticCustomizationStatus(_createdAcousticModelId)); while (!_isAcousticCustomizationReady) { yield return(null); } // Delete acoustic resource DeleteAcousticResource(); while (!_deleteAcousticResource) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete acoustic resource for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } // Reset acoustic customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to reset acoustic customization {0}", _createdAcousticModelId); _speechToText.ResetAcousticCustomization(HandleResetAcousticCustomization, OnFail, _createdAcousticModelId); while (!_resetAcousticCustomizationsTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete acoustic customization for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } // Delete acoustic customization DeleteAcousticCustomization(); while (!_deleteAcousticCustomizationsTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying complete for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } Log.Debug("TestSpeechToText.RunTest()", "Speech to Text examples complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; var vcapUrl = Environment.GetEnvironmentVariable("VCAP_URL"); var vcapUsername = Environment.GetEnvironmentVariable("VCAP_USERNAME"); var vcapPassword = Environment.GetEnvironmentVariable("VCAP_PASSWORD"); using (SimpleGet simpleGet = new SimpleGet(vcapUrl, vcapUsername, vcapPassword)) { while (!simpleGet.IsComplete) { yield return(null); } result = simpleGet.Result; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["natural_language_understanding"]; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; _naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(credentials); Log.Debug("TestNaturalLanguageUnderstanding.RunTests()", "attempting to get models..."); if (!_naturalLanguageUnderstanding.GetModels(OnGetModels, OnFail)) { Log.Debug("TestNaturalLanguageUnderstanding.GetModels()", "Failed to get models."); } while (!_getModelsTested) { yield return(null); } Parameters parameters = new Parameters() { text = "Analyze various features of text content at scale. Provide text, raw HTML, or a public URL, and IBM Watson Natural Language Understanding will give you results for the features you request. The service cleans HTML content before analysis by default, so the results can ignore most advertisements and other unwanted content.", return_analyzed_text = true, language = "en", features = new Features() { entities = new EntitiesOptions() { limit = 50, sentiment = true, emotion = true, }, keywords = new KeywordsOptions() { limit = 50, sentiment = true, emotion = true } } }; Log.Debug("TestNaturalLanguageUnderstanding.RunTests()", "attempting to analyze..."); if (!_naturalLanguageUnderstanding.Analyze(OnAnalyze, OnFail, parameters)) { Log.Debug("TestNaturalLanguageUnderstanding.Analyze()", "Failed to get models."); } while (!_analyzeTested) { yield return(null); } Log.Debug("TestNaturalLanguageUnderstanding.RunTests()", "Natural language understanding examples complete."); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; string credentialsFilepath = "../sdk-credentials/credentials.json"; // Load credentials file if it exists. If it doesn't exist, don't run the tests. if (File.Exists(credentialsFilepath)) { result = File.ReadAllText(credentialsFilepath); } else { yield break; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.GetCredentialByname("discovery-sdk")[0].Credentials; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); _discovery = new Discovery(credentials); _discovery.VersionDate = _discoveryVersionDate; _filePathToIngest = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/Discovery/constitution.pdf"; _documentFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/Discovery/constitution.pdf"; // Get Environments Log.Debug("TestDiscovery.RunTest()", "Attempting to get environments"); if (!_discovery.GetEnvironments(OnGetEnvironments, OnFail)) { Log.Debug("TestDiscovery.GetEnvironments()", "Failed to get environments"); } while (!_getEnvironmentsTested) { yield return(null); } // Wait for environment to be ready Runnable.Run(CheckEnvironmentState(0f)); while (!_isEnvironmentReady) { yield return(null); } // GetEnvironment Log.Debug("TestDiscovery.RunTest()", "Attempting to get environment"); if (!_discovery.GetEnvironment(OnGetEnvironment, OnFail, _environmentId)) { Log.Debug("TestDiscovery.GetEnvironment()", "Failed to get environment"); } while (!_getEnvironmentTested) { yield return(null); } // Get Configurations Log.Debug("TestDiscovery.RunTest()", "Attempting to get configurations"); if (!_discovery.GetConfigurations(OnGetConfigurations, OnFail, _environmentId)) { Log.Debug("TestDiscovery.GetConfigurations()", "Failed to get configurations"); } while (!_getConfigurationsTested) { yield return(null); } // Add Configuration Log.Debug("TestDiscovery.RunTest()", "Attempting to add configuration"); if (!_discovery.AddConfiguration(OnAddConfiguration, OnFail, _environmentId, _configurationJson.Replace("{guid}", GUID.Generate().ToString()))) { Log.Debug("TestDiscovery.AddConfiguration()", "Failed to add configuration"); } while (!_addConfigurationTested) { yield return(null); } // Get Configuration Log.Debug("TestDiscovery.RunTest()", "Attempting to get configuration"); if (!_discovery.GetConfiguration(OnGetConfiguration, OnFail, _environmentId, _createdConfigurationID)) { Log.Debug("TestDiscovery.GetConfiguration()", "Failed to get configuration"); } while (!_getConfigurationTested) { yield return(null); } // Preview Configuration Log.Debug("TestDiscovery.RunTest()", "Attempting to preview configuration"); if (!_discovery.PreviewConfiguration(OnPreviewConfiguration, OnFail, _environmentId, _createdConfigurationID, null, _filePathToIngest, _metadata)) { Log.Debug("TestDiscovery.PreviewConfiguration()", "Failed to preview configuration"); } while (!_previewConfigurationTested) { yield return(null); } // Get Collections Log.Debug("TestDiscovery.RunTest()", "Attempting to get collections"); if (!_discovery.GetCollections(OnGetCollections, OnFail, _environmentId)) { Log.Debug("TestDiscovery.GetCollections()", "Failed to get collections"); } while (!_getCollectionsTested) { yield return(null); } // Add Collection Log.Debug("TestDiscovery.RunTest()", "Attempting to add collection"); if (!_discovery.AddCollection(OnAddCollection, OnFail, _environmentId, _createdCollectionName + GUID.Generate().ToString(), _createdCollectionDescription, _createdConfigurationID)) { Log.Debug("TestDiscovery.AddCollection()", "Failed to add collection"); } while (!_addCollectionTested) { yield return(null); } // Get Collection Log.Debug("TestDiscovery.RunTest()", "Attempting to get collection"); if (!_discovery.GetCollection(OnGetCollection, OnFail, _environmentId, _createdCollectionID)) { Log.Debug("TestDiscovery.GetCollection()", "Failed to get collection"); } while (!_getCollectionTested) { yield return(null); } if (!_discovery.GetFields(OnGetFields, OnFail, _environmentId, _createdCollectionID)) { Log.Debug("TestDiscovery.GetFields()", "Failed to get fields"); } while (!_getFieldsTested) { yield return(null); } // Add Document Log.Debug("TestDiscovery.RunTest()", "Attempting to add document"); if (!_discovery.AddDocument(OnAddDocument, OnFail, _environmentId, _createdCollectionID, _documentFilePath, _createdConfigurationID, null)) { Log.Debug("TestDiscovery.AddDocument()", "Failed to add document"); } while (!_addDocumentTested) { yield return(null); } // Get Document Log.Debug("TestDiscovery.RunTest()", "Attempting to get document"); if (!_discovery.GetDocument(OnGetDocument, OnFail, _environmentId, _createdCollectionID, _createdDocumentID)) { Log.Debug("TestDiscovery.GetDocument()", "Failed to get document"); } while (!_getDocumentTested) { yield return(null); } // Update Document Log.Debug("TestDiscovery.RunTest()", "Attempting to update document"); if (!_discovery.UpdateDocument(OnUpdateDocument, OnFail, _environmentId, _createdCollectionID, _createdDocumentID, _documentFilePath, _createdConfigurationID, null)) { Log.Debug("TestDiscovery.UpdateDocument()", "Failed to update document"); } while (!_updateDocumentTested) { yield return(null); } // Query Log.Debug("TestDiscovery.RunTest()", "Attempting to query"); if (!_discovery.Query(OnQuery, OnFail, _environmentId, _createdCollectionID, null, _query, null, 10, null, 0)) { Log.Debug("TestDiscovery.Query()", "Failed to query"); } while (!_queryTested) { yield return(null); } // Delete Document Log.Debug("TestDiscovery.RunTest()", "Attempting to delete document {0}", _createdDocumentID); if (!_discovery.DeleteDocument(OnDeleteDocument, OnFail, _environmentId, _createdCollectionID, _createdDocumentID)) { Log.Debug("TestDiscovery.DeleteDocument()", "Failed to delete document"); } while (!_deleteDocumentTested) { yield return(null); } // Delay Log.Debug("TestDiscovery.RunTest()", "Delaying delete collection for 10 sec"); Runnable.Run(Delay(_waitTime)); while (!_readyToContinue) { yield return(null); } _isEnvironmentReady = false; Runnable.Run(CheckEnvironmentState(_waitTime)); while (!_isEnvironmentReady) { yield return(null); } _readyToContinue = false; // Delete Collection Log.Debug("TestDiscovery.RunTest()", "Attempting to delete collection {0}", _createdCollectionID); if (!_discovery.DeleteCollection(OnDeleteCollection, OnFail, _environmentId, _createdCollectionID)) { Log.Debug("TestDiscovery.DeleteCollection()", "Failed to delete collection"); } while (!_deleteCollectionTested) { yield return(null); } // Delay Log.Debug("TestDiscovery.RunTest()", "Delaying delete configuration for 10 sec"); Runnable.Run(Delay(_waitTime)); while (!_readyToContinue) { yield return(null); } _isEnvironmentReady = false; Runnable.Run(CheckEnvironmentState(_waitTime)); while (!_isEnvironmentReady) { yield return(null); } _readyToContinue = false; // Delete Configuration Log.Debug("TestDiscovery.RunTest()", "Attempting to delete configuration {0}", _createdConfigurationID); if (!_discovery.DeleteConfiguration(OnDeleteConfiguration, OnFail, _environmentId, _createdConfigurationID)) { Log.Debug("TestDiscovery.DeleteConfiguration()", "Failed to delete configuration"); } while (!_deleteConfigurationTested) { yield return(null); } // Delete User Data Log.Debug("TestDiscovery.RunTest()", "Attempting to delete user data."); _discovery.DeleteUserData(OnDeleteUserData, OnFail, "test-unity-user-id"); while (!_deleteUserDataTested) { yield return(null); } Log.Debug("TestDiscovery.RunTest()", "Discovery unit tests complete."); yield break; }
public static void Main(string[] args) { #region Get Credentials string credentials = string.Empty; 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("personality-insights-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 PersonalityInsightsService _service = new PersonalityInsightsService(_username, _password, "2016-10-20"); _service.Endpoint = _endpoint; string contentToProfile = "The IBM Watson™ Personality Insights service provides a Representational State Transfer (REST) Application Programming Interface (API) that enables applications to derive insights from social media, enterprise data, or other digital communications. The service uses linguistic analytics to infer individuals' intrinsic personality characteristics, including Big Five, Needs, and Values, from digital communications such as email, text messages, tweets, and forum posts. The service can automatically infer, from potentially noisy social media, portraits of individuals that reflect their personality characteristics. The service can report consumption preferences based on the results of its analysis, and for JSON content that is timestamped, it can report temporal behavior."; // Test Profile Content content = new Content() { ContentItems = new List <ContentItem>() { new ContentItem() { Contenttype = ContentItem.ContenttypeEnum.TEXT_PLAIN, Language = ContentItem.LanguageEnum.EN, Content = contentToProfile } } }; var result = _service.Profile(content, "text/plain", acceptLanguage: "application/json", rawScores: true, consumptionPreferences: true, csvHeaders: true); Console.WriteLine("Profile() succeeded:\n{0}", JsonConvert.SerializeObject(result, Formatting.Indented)); Console.ReadKey(); }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; string credentialsFilepath = "../sdk-credentials/credentials.json"; // Load credentials file if it exists. If it doesn't exist, don't run the tests. if (File.Exists(credentialsFilepath)) { result = File.ReadAllText(credentialsFilepath); } else { yield break; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.GetCredentialByname("visual-recognition-sdk")[0].Credentials; _apikey = credential.ApiKey.ToString(); _url = credential.Url.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_apikey, _url); _visualRecognition = new VisualRecognition(credentials); _visualRecognition.VersionDate = _visualRecognitionVersionDate; // Get all classifiers Log.Debug("TestVisualRecognition.RunTest()", "Attempting to get all classifiers"); if (!_visualRecognition.GetClassifiersBrief(OnGetClassifiers, OnFail)) { Log.Debug("TestVisualRecognition.GetClassifiers()", "Failed to get all classifiers!"); } while (!_getClassifiersTested) { yield return(null); } #if TRAIN_CLASSIFIER _isClassifierReady = false; // Train classifier Log.Debug("TestVisualRecognition.RunTest()", "Attempting to train classifier"); string positiveExamplesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/giraffe_positive_examples.zip"; string negativeExamplesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/negative_examples.zip"; Dictionary <string, string> positiveExamples = new Dictionary <string, string>(); positiveExamples.Add("giraffe", positiveExamplesPath); if (!_visualRecognition.TrainClassifier(OnTrainClassifier, OnFail, "unity-test-classifier-ok-to-delete", positiveExamples, negativeExamplesPath)) { Log.Debug("TestVisualRecognition.TrainClassifier()", "Failed to train classifier!"); } while (!_trainClassifierTested) { yield return(null); } // Find classifier by ID Log.Debug("TestVisualRecognition.RunTest()", "Attempting to find classifier by ID"); if (!_visualRecognition.GetClassifier(OnGetClassifier, OnFail, _classifierID)) { Log.Debug("TestVisualRecognition.GetClassifier()", "Failed to get classifier!"); } while (!_getClassifierTested) { yield return(null); } //// Download Core ML Model //Log.Debug("TestVisualRecognition.RunTest()", "Attempting to get Core ML Model"); //if(!_visualRecognition.GetCoreMLModel(OnGetCoreMLModel, OnFail, _classifierID)) // Log.Debug("TestVisualRecognition.GetCoreMLModel()", "Failed to get core ml model!"); //while (!_getCoreMLModelTested) // yield return null; #endif // Classify get Log.Debug("TestVisualRecognition.RunTest()", "Attempting to get classify via URL"); if (!_visualRecognition.Classify(_imageURL, OnClassifyGet, OnFail)) { Log.Debug("TestVisualRecognition.Classify()", "Classify image failed!"); } while (!_classifyGetTested) { yield return(null); } // Classify post image Log.Debug("TestVisualRecognition.RunTest()", "Attempting to classify via image on file system"); string imagesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/giraffe_to_classify.jpg"; string[] owners = { "IBM", "me" }; string[] classifierIDs = { "default", _classifierID }; if (!_visualRecognition.Classify(OnClassifyPost, OnFail, imagesPath, owners, classifierIDs, 0.5f)) { Log.Debug("TestVisualRecognition.Classify()", "Classify image failed!"); } while (!_classifyPostTested) { yield return(null); } // Detect faces get Log.Debug("TestVisualRecognition.RunTest()", "Attempting to detect faces via URL"); if (!_visualRecognition.DetectFaces(_imageURL, OnDetectFacesGet, OnFail)) { Log.Debug("TestVisualRecognition.DetectFaces()", "Detect faces failed!"); } while (!_detectFacesGetTested) { yield return(null); } // Detect faces post image Log.Debug("TestVisualRecognition.RunTest()", "Attempting to detect faces via image"); string faceExamplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/obama.jpg"; if (!_visualRecognition.DetectFaces(OnDetectFacesPost, OnFail, faceExamplePath)) { Log.Debug("TestVisualRecognition.DetectFaces()", "Detect faces failed!"); } while (!_detectFacesPostTested) { yield return(null); } #if DELETE_TRAINED_CLASSIFIER Runnable.Run(IsClassifierReady(_classifierToDelete)); while (!_isClassifierReady) { yield return(null); } // Delete classifier by ID Log.Debug("TestVisualRecognition.RunTest()", "Attempting to delete classifier"); if (!_visualRecognition.DeleteClassifier(OnDeleteClassifier, OnFail, _classifierToDelete)) { Log.Debug("TestVisualRecognition.DeleteClassifier()", "Failed to delete classifier!"); } while (!_deleteClassifierTested) { yield return(null); } #endif Log.Debug("TestVisualRecognition.RunTest()", "Visual Recogition tests complete"); yield break; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); _testClusterConfigName = "cranfield_solr_config"; _testClusterConfigPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/cranfield_solr_config.zip"; _testRankerTrainingPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/ranker_training_data.csv"; _testAnswerDataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/ranker_answer_data.csv"; _indexDataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/cranfield_data.json"; _testQuery = "What is the basic mechanisim of the transonic aileron buzz"; _collectionNameToDelete = "TestCollectionToDelete"; _createdRankerName = "RankerToDelete"; try { VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; // Get credentials from a credential file defined in environmental variables in the VCAP_SERVICES format. // See https://www.ibm.com/watson/developercloud/doc/common/getting-started-variables.html. var environmentalVariable = Environment.GetEnvironmentVariable("VCAP_SERVICES"); var fileContent = File.ReadAllText(environmentalVariable); // Add in a parent object because Unity does not like to deserialize root level collection types. fileContent = Utility.AddTopLevelObjectToJson(fileContent, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(fileContent, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["retrieve_and_rank"][TestCredentialIndex].Credentials; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); } catch { Log.Debug("TestRetrieveAndRank.RunTest()", "Failed to get credentials from VCAP_SERVICES file. Please configure credentials to run this test. For more information, see: https://github.com/watson-developer-cloud/unity-sdk/#authentication"); } // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; _retrieveAndRank = new RetrieveAndRank(credentials); // Get clusters Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to get clusters."); if (!_retrieveAndRank.GetClusters(OnGetClusters, OnFail)) { Log.Debug("TestRetrieveAndRank.GetClusters()", "Failed to get clusters!"); } while (!_getClustersTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Create cluster Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to create cluster."); if (!_retrieveAndRank.CreateCluster(OnCreateCluster, OnFail, "unity-test-cluster", "1")) { Log.Debug("TestRetrieveAndRank.CreateCluster()", "Failed to create cluster!"); } while (!_createClusterTested || !_readyToContinue) { yield return(null); } // Wait for cluster status to be `READY`. Runnable.Run(CheckClusterStatus(10f)); while (!_isClusterReady) { yield return(null); } _readyToContinue = false; // List cluster configs Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to get cluster configs."); if (!_retrieveAndRank.GetClusterConfigs(OnGetClusterConfigs, OnFail, _clusterToDelete)) { Log.Debug("TestRetrieveAndRank.GetClusterConfigs()", "Failed to get cluster configs!"); } while (!_getClusterConfigsTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Upload cluster config Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to upload cluster config."); if (!_retrieveAndRank.UploadClusterConfig(OnUploadClusterConfig, OnFail, _clusterToDelete, _testClusterConfigName, _testClusterConfigPath)) { Log.Debug("TestRetrieveAndRank.UploadClusterConfig()", "Failed to upload cluster config {0}!", _testClusterConfigPath); } while (!_uploadClusterConfigTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Get cluster Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to get cluster."); if (!_retrieveAndRank.GetCluster(OnGetCluster, OnFail, _clusterToDelete)) { Log.Debug("TestRetrieveAndRank.GetCluster()", "Failed to get cluster!"); } while (!_getClusterTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Get cluster config Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to get cluster config."); if (!_retrieveAndRank.GetClusterConfig(OnGetClusterConfig, OnFail, _clusterToDelete, _testClusterConfigName)) { Log.Debug("TestRetrieveAndRank.GetClusterConfig()", "Failed to get cluster config {0}!", _testClusterConfigName); } while (!_getClusterConfigTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // List Collection request Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to get collections."); if (!_retrieveAndRank.ForwardCollectionRequest(OnGetCollections, OnFail, _clusterToDelete, CollectionsAction.List)) { Log.Debug("TestRetrieveAndRank.ForwardCollectionRequest()", "Failed to get collections!"); } while (!_getCollectionsTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Create Collection request Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to create collection."); if (!_retrieveAndRank.ForwardCollectionRequest(OnCreateCollection, OnFail, _clusterToDelete, CollectionsAction.Create, _collectionNameToDelete, _testClusterConfigName)) { Log.Debug("TestRetrieveAndRank.ForwardCollectionRequest()", "Failed to create collections!"); } while (!_createCollectionTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Index documents Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to index documents."); if (!_retrieveAndRank.IndexDocuments(OnIndexDocuments, OnFail, _indexDataPath, _clusterToDelete, _collectionNameToDelete)) { Log.Debug("TestRetrieveAndRank.IndexDocuments()", "Failed to index documents!"); } while (!_indexDocumentsTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Get rankers Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to get rankers."); if (!_retrieveAndRank.GetRankers(OnGetRankers, OnFail)) { Log.Debug("TestRetrieveAndRank.GetRankers()", "Failed to get rankers!"); } while (!_getRankersTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Create ranker Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to create ranker."); if (!_retrieveAndRank.CreateRanker(OnCreateRanker, OnFail, _testRankerTrainingPath, _createdRankerName)) { Log.Debug("TestRetrieveAndRank.CreateRanker()", "Failed to create ranker!"); } while (!_createRankerTested || !_readyToContinue) { yield return(null); } // Wait for ranker status to be `Available`. Log.Debug("TestRetrieveAndRank.RunTest()", "Checking ranker status in 10 seconds"); Runnable.Run(CheckRankerStatus(10f)); while (!_isRankerReady || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Standard Search string[] fl = { "title", "id", "body", "author", "bibliography" }; Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to search standard."); if (!_retrieveAndRank.Search(OnSearchStandard, OnFail, _clusterToDelete, _collectionNameToDelete, _testQuery, fl)) { Log.Debug("TestRetrieveAndRank.Search()", "Failed to search!"); } while (!_searchStandardTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Rank Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to rank."); if (!_retrieveAndRank.Rank(OnRank, OnFail, _rankerIdToDelete, _testAnswerDataPath)) { Log.Debug("TestRetrieveAndRank.Rank()", "Failed to rank!"); } while (!_rankTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Get ranker info Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to get rankers."); if (!_retrieveAndRank.GetRanker(OnGetRanker, OnFail, _rankerIdToDelete)) { Log.Debug("TestRetrieveAndRank.GetRanker()", "Failed to get ranker!"); } while (!_getRankerTested) { yield return(null); } _readyToContinue = false; // Delete rankers Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to delete ranker {0}.", _rankerIdToDelete); if (!_retrieveAndRank.DeleteRanker(OnDeleteRanker, OnFail, _rankerIdToDelete)) { Log.Debug("TestRetrieveAndRank.DeleteRanker()", "Failed to delete ranker {0}!", _rankerIdToDelete); } while (!_deleteRankerTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete Collection request Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to delete collection {0}.", "TestCollectionToDelete"); if (!_retrieveAndRank.ForwardCollectionRequest(OnDeleteCollection, OnFail, _clusterToDelete, CollectionsAction.Delete, "TestCollectionToDelete")) { Log.Debug("TestRetrieveAndRank.ForwardCollectionRequest()", "Failed to delete collections!"); } while (!_deleteCollectionTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete cluster config string clusterConfigToDelete = "test-config"; Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to delete cluster config."); if (!_retrieveAndRank.DeleteClusterConfig(OnDeleteClusterConfig, OnFail, _clusterToDelete, clusterConfigToDelete)) { Log.Debug("TestRetrieveAndRank.DeleteClusterConfig()", "Failed to delete cluster config {0}", clusterConfigToDelete); } while (!_deleteClusterConfigTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete cluster Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to delete cluster {0}.", _clusterToDelete); if (!_retrieveAndRank.DeleteCluster(OnDeleteCluster, OnFail, _clusterToDelete)) { Log.Debug("TestRetrieveAndRank.DeleteCluster()", "Failed to delete cluster!"); } while (!_deleteClusterTested || !_readyToContinue) { yield return(null); } Log.Debug("TestRetrieveAndRank.RunTest()", "Retrieve and rank examples complete!"); yield break; }