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());
    }
Exemplo n.º 2
0
        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;
        }
Exemplo n.º 3
0
        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;
        }
Exemplo n.º 4
0
        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;

            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;
        }
Exemplo n.º 6
0
        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;

            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;
        }
Exemplo n.º 8
0
        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["visual_recognition"];

            _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
            //          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-example", 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
            #region Delay
            Runnable.Run(Delay(_delayTime));
            while (_isWaitingForDelay)
            {
                yield return(null);
            }
            #endregion

            //          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;
        }
Exemplo n.º 9
0
        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";

            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["retrieve_and_rank"];

            _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
            //};

            _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;
        }
Exemplo n.º 10
0
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            VcapCredentials vcapCredentials = new VcapCredentials();
            fsData          data            = null;

            string result = null;

            var vcapUrl      = System.Environment.GetEnvironmentVariable("VCAP_URL");
            var vcapUsername = System.Environment.GetEnvironmentVariable("VCAP_USERNAME");
            var vcapPassword = System.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["discovery"];

            _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
            //};

            _discovery             = new Discovery(credentials);
            _discovery.VersionDate = _discoveryVersionDate;
            _configurationJsonPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/Discovery/exampleConfigurationData.json";
            _filePathToIngest      = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/watson_beats_jeopardy.html";
            _documentFilePath      = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/watson_beats_jeopardy.html";

            //  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);
            }

            //  AddEnvironment
            Log.Debug("TestDiscovery.RunTest()", "Attempting to add environment");
            if (!_discovery.AddEnvironment(OnAddEnvironment, OnFail, "unity-testing-AddEnvironment-do-not-delete-until-active", "Testing addEnvironment in Unity SDK. Please do not delete this environment until the status is 'active'", 1))
            {
                Log.Debug("TestDiscovery.AddEnvironment()", "Failed to add environment");
            }
            while (!_addEnvironmentTested)
            {
                yield return(null);
            }

            //  Wait for environment to be ready
            Runnable.Run(CheckEnvironmentState(_waitTime));
            while (!_isEnvironmentReady)
            {
                yield return(null);
            }

            //  GetEnvironment
            Log.Debug("TestDiscovery.RunTest()", "Attempting to get environment");
            if (!_discovery.GetEnvironment(OnGetEnvironment, OnFail, _createdEnvironmentID))
            {
                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, _createdEnvironmentID))
            {
                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, _createdEnvironmentID, _configurationJsonPath))
            {
                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, _createdEnvironmentID, _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, _createdEnvironmentID, _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, _createdEnvironmentID))
            {
                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, _createdEnvironmentID, _createdCollectionName, _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, _createdEnvironmentID, _createdCollectionID))
            {
                Log.Debug("TestDiscovery.GetCollection()", "Failed to get collection");
            }
            while (!_getCollectionTested)
            {
                yield return(null);
            }

            if (!_discovery.GetFields(OnGetFields, OnFail, _createdEnvironmentID, _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, _createdEnvironmentID, _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, _createdEnvironmentID, _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, _createdEnvironmentID, _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, _createdEnvironmentID, _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, _createdEnvironmentID, _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, _createdEnvironmentID, _createdCollectionID))
            {
                Log.Debug("TestDiscovery.DeleteCollection()", "Failed to add 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, _createdEnvironmentID, _createdConfigurationID))
            {
                Log.Debug("TestDiscovery.DeleteConfiguration()", "Failed to delete configuration");
            }
            while (!_deleteConfigurationTested)
            {
                yield return(null);
            }

            //  Delay
            Log.Debug("TestDiscovery.RunTest()", "Delaying delete environment 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 Environment
            Log.Debug("TestDiscovery.RunTest()", "Attempting to delete environment {0}", _createdEnvironmentID);
            if (!_discovery.DeleteEnvironment(OnDeleteEnvironment, OnFail, _createdEnvironmentID))
            {
                Log.Debug("TestDiscovery.DeleteEnvironment()", "Failed to delete environment");
            }
            while (!_deleteEnvironmentTested)
            {
                yield return(null);
            }

            if (!string.IsNullOrEmpty(_createdEnvironmentID))
            {
                if (!_discovery.GetEnvironment(OnGetEnvironment, OnFail, _createdEnvironmentID))
                {
                    _discovery.DeleteEnvironment(OnDeleteEnvironment, OnFail, _createdEnvironmentID);
                }
            }

            Log.Debug("TestDiscovery.RunTest()", "Discovery 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["document_conversion"];

            _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
            //};

            _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;
        }
Exemplo n.º 12
0
        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);

            _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
            Dictionary <string, object> input = new Dictionary <string, object>();

            input.Add("text", _inputString);
            MessageRequest messageRequest = new MessageRequest()
            {
                Input            = input,
                AlternateIntents = true
            };

            _service.Message(OnMessage, OnFail, _workspaceId, messageRequest);
            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);
            }

            Log.Debug("TestAssistant.RunTest()", "Assistant examples complete.");

            yield break;
        }
Exemplo n.º 13
0
        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["tone_analyzer"];

            _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
            //};

            _toneAnalyzer             = new ToneAnalyzer(credentials);
            _toneAnalyzer.VersionDate = _toneAnalyzerVersionDate;

            //  Analyze tone
            if (!_toneAnalyzer.GetToneAnalyze(OnGetToneAnalyze, OnFail, _stringToTestTone))
            {
                Log.Debug("ExampleToneAnalyzer.GetToneAnalyze()", "Failed to analyze!");
            }

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

            Log.Debug("ExampleToneAnalyzer.RunTest()", "Tone analyzer examples complete.");

            yield break;
        }
Exemplo n.º 14
0
        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["language_translator"];

            _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;
        }