示例#1
0
        public override IEnumerator RunTest()
        {
            if (Config.Instance.FindCredentials(m_NLC.GetServiceID()) == null)
            {
                yield break;
            }

            m_NLC.FindClassifier("TestNLC/", OnFindClassifier);
            while (!m_FindClassifierTested)
            {
                yield return(null);
            }

            if (m_TrainClassifier)
            {
                string trainingData = File.ReadAllText(Application.dataPath + "/Watson/Editor/TestData/weather_data_train.csv");

                Test(m_NLC.TrainClassifier("TestNLC/" + DateTime.Now.ToString(), "en", trainingData, OnTrainClassifier));
                while (!m_TrainClasifierTested)
                {
                    yield return(null);
                }
            }
            else if (!string.IsNullOrEmpty(m_ClassifierId))
            {
                Test(m_NLC.Classify(m_ClassifierId, "Is it hot outside", OnClassify));
                while (!m_ClassifyTested)
                {
                    yield return(null);
                }
            }

#if TEST_DELETE
            if (!string.IsNullOrEmpty(m_ClassifierId))
            {
                Test(m_NLC.DeleteClassifer(m_ClassifierId, OnDeleteClassifier));
                while (!m_DeleteTested)
                {
                    yield return(null);
                }
            }
#endif

            yield break;
        }
示例#2
0
    private IEnumerator Examples()
    {
        //  Get classifiers
        if (!_service.GetClassifiers(OnGetClassifiers, OnFail))
        {
            Log.Debug("ExampleNaturalLanguageClassifier.GetClassifiers()", "Failed to get classifiers!");
        }

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

        if (_classifierIds.Count == 0)
        {
            Log.Debug("ExampleNaturalLanguageClassifier.Examples()", "There are no trained classifiers. Please train a classifier...");
        }

        if (_classifierIds.Count > 0)
        {
            //  Get each classifier
            foreach (string classifierId in _classifierIds)
            {
                if (!_service.GetClassifier(OnGetClassifier, OnFail, classifierId))
                {
                    Log.Debug("ExampleNaturalLanguageClassifier.GetClassifier()", "Failed to get classifier {0}!", classifierId);
                }
            }

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

        if (!_areAnyClassifiersAvailable && _classifierIds.Count > 0)
        {
            Log.Debug("ExampleNaturalLanguageClassifier.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 (!_service.TrainClassifier(OnTrainClassifier, OnFail, _classifierName + "/" + DateTime.Now.ToString(), "en", trainingContent))
        {
            Log.Debug("ExampleNaturalLanguageClassifier.TrainClassifier()", "Failed to train clasifier!");
        }

        while (!_trainClassifierTested)
        {
            yield return(null);
        }
#endif

#if DELETE_TRAINED_CLASSIFIER
        if (!string.IsNullOrEmpty(_classifierToDelete))
        {
            if (!_service.DeleteClassifer(OnDeleteTrainedClassifier, OnFail, _classifierToDelete))
            {
                Log.Debug("ExampleNaturalLanguageClassifier.DeleteClassifer()", "Failed to delete clasifier {0}!", _classifierToDelete);
            }
        }
#endif

        //  Classify
        if (_areAnyClassifiersAvailable)
        {
            if (!_service.Classify(OnClassify, OnFail, _classifierId, _inputString))
            {
                Log.Debug("ExampleNaturalLanguageClassifier.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 (!_service.ClassifyCollection(OnClassifyCollection, OnFail, _classifierId, classifyCollectionInput))
            {
                Log.Debug("ExampleNaturalLanguageClassifier.ClassifyCollection()", "Failed to classify!");
            }

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

        Log.Debug("ExampleNaturalLanguageClassifier.Examples()", "Natural language classifier examples complete.");
    }
示例#3
0
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            //  Test NaturalLanguageClassifier using loaded credentials
            NaturalLanguageClassifier autoNaturalLanguageClassifier = new NaturalLanguageClassifier();

            while (!autoNaturalLanguageClassifier.Credentials.HasIamTokenData())
            {
                yield return(null);
            }
            autoNaturalLanguageClassifier.GetClassifiers(OnAutoGetClassifiers, OnFail);
            while (!_autoGetClassifiersTested)
            {
                yield return(null);
            }

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

            string result = null;
            string credentialsFilepath = "../sdk-credentials/credentials.json";

            //  Load credentials file if it exists. If it doesn't exist, don't run the tests.
            if (File.Exists(credentialsFilepath))
            {
                result = File.ReadAllText(credentialsFilepath);
            }
            else
            {
                yield break;
            }

            //  Add in a parent object because Unity does not like to deserialize root level collection types.
            result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES");

            //  Convert json to fsResult
            fsResult r = fsJsonParser.Parse(result, out data);

            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Convert fsResult to VcapCredentials
            object obj = vcapCredentials;

            r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Set credentials from imported credntials
            Credential credential = vcapCredentials.GetCredentialByname("natural-language-classifier-sdk")[0].Credentials;
            //  Create credential and instantiate service
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = credential.IamApikey,
            };

            //  Create credential and instantiate service
            Credentials credentials = new Credentials(tokenOptions, credential.Url);

            //  Wait for tokendata
            while (!credentials.HasIamTokenData())
            {
                yield return(null);
            }

            naturalLanguageClassifier = new NaturalLanguageClassifier(credentials);

            //  Get classifiers
            if (!naturalLanguageClassifier.GetClassifiers(OnGetClassifiers, OnFail))
            {
                Log.Debug("TestNaturalLanguageClassifier.GetClassifiers()", "Failed to get classifiers!");
            }

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

            if (_classifierIds.Count == 0)
            {
                Log.Debug("TestNaturalLanguageClassifier.Examples()", "There are no trained classifiers. Please train a classifier...");
            }

            if (_classifierIds.Count > 0)
            {
                //  Get each classifier
                foreach (string classifierId in _classifierIds)
                {
                    if (!naturalLanguageClassifier.GetClassifier(OnGetClassifier, OnFail, classifierId))
                    {
                        Log.Debug("TestNaturalLanguageClassifier.GetClassifier()", "Failed to get classifier {0}!", classifierId);
                    }
                }

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

            if (!_areAnyClassifiersAvailable && _classifierIds.Count > 0)
            {
                Log.Debug("TestNaturalLanguageClassifier.Examples()", "All classifiers are training...");
            }

            //  Train classifier
#if TRAIN_CLASSIFIER
            string dataPath        = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/weather_data_train.csv";
            var    trainingContent = File.ReadAllText(dataPath);
            if (!naturalLanguageClassifier.TrainClassifier(OnTrainClassifier, OnFail, _classifierName + "/" + DateTime.Now.ToString(), "en", trainingContent))
            {
                Log.Debug("TestNaturalLanguageClassifier.TrainClassifier()", "Failed to train clasifier!");
            }

            while (!_trainClassifierTested)
            {
                yield return(null);
            }
#endif

#if DELETE_TRAINED_CLASSIFIER
            if (!string.IsNullOrEmpty(_classifierToDelete))
            {
                if (!naturalLanguageClassifier.DeleteClassifer(OnDeleteTrainedClassifier, OnFail, _classifierToDelete))
                {
                    Log.Debug("TestNaturalLanguageClassifier.DeleteClassifer()", "Failed to delete clasifier {0}!", _classifierToDelete);
                }
            }
#endif

            //  Classify
            if (_areAnyClassifiersAvailable)
            {
                if (!naturalLanguageClassifier.Classify(OnClassify, OnFail, _classifierId, _inputString))
                {
                    Log.Debug("TestNaturalLanguageClassifier.Classify()", "Failed to classify!");
                }

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

            //  Classify Collection
            ClassifyCollectionInput classifyCollectionInput = new ClassifyCollectionInput()
            {
                collection = new List <ClassifyInput>()
                {
                    new ClassifyInput()
                    {
                        text = "Is it hot outside?"
                    },
                    new ClassifyInput()
                    {
                        text = "Is it going to rain?"
                    }
                }
            };

            if (_areAnyClassifiersAvailable)
            {
                if (!naturalLanguageClassifier.ClassifyCollection(OnClassifyCollection, OnFail, _classifierId, classifyCollectionInput))
                {
                    Log.Debug("TestNaturalLanguageClassifier.ClassifyCollection()", "Failed to classify!");
                }

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

            Log.Debug("TestNaturalLanguageClassifier.RunTest()", "Natural language classifier examples complete.");

            yield break;
        }
示例#4
0
        private void OnGUI()
        {
            if (Event.current.type == EventType.repaint && !m_handleRepaintError)
            {
                m_handleRepaintError = true;
                return;
            }

            GUILayout.Label(m_WatsonIcon);

            m_ScrollPos = EditorGUILayout.BeginScrollView(m_ScrollPos);
            EditorGUILayout.BeginVertical();

            if (m_Refreshing)
            {
                EditorGUI.BeginDisabledGroup(true);
                GUILayout.Button("Refreshing...");
                EditorGUI.EndDisabledGroup();
            }
            else if (m_ClassifierData == null || GUILayout.Button("Refresh"))
            {
                OnRefresh();
            }

            EditorGUILayout.LabelField("Classifiers:");
            //EditorGUI.indentLevel += 1;

            if (m_ClassifierData != null)
            {
                ClassifierData deleteClassifier = null;
                foreach (var data in m_ClassifierData)
                {
                    EditorGUILayout.BeginHorizontal();

                    bool expanded = data.Expanded;
                    data.Expanded = EditorGUILayout.Foldout(expanded, data.Name + " [Language: " + data.Language + "]");
                    if (data.Expanded != expanded)
                    {
                        data.Save();
                    }

                    if (GUILayout.Button("Import", GUILayout.Width(100)))
                    {
                        var path = EditorUtility.OpenFilePanel("Select Training File", "", "csv");
                        if (!string.IsNullOrEmpty(path))
                        {
                            try {
                                data.Import(path);
                            }
                            catch
                            {
                                EditorUtility.DisplayDialog("Error", "Failed to load training data: " + path, "OK");
                            }
                        }
                    }
                    if (GUILayout.Button("Export", GUILayout.Width(100)))
                    {
                        var path = EditorUtility.SaveFilePanel("Export Training file", Application.dataPath, "", "csv");
                        if (!string.IsNullOrEmpty(path))
                        {
                            File.WriteAllText(path, data.Export());
                        }
                    }
                    if (GUILayout.Button("Save", GUILayout.Width(100)))
                    {
                        data.Save();
                    }
                    if (GUILayout.Button("Delete", GUILayout.Width(100)))
                    {
                        if (EditorUtility.DisplayDialog("Confirm", "Please confirm you want to delete classifier: " + data.Name, "Yes", "No"))
                        {
                            deleteClassifier = data;
                        }
                    }
                    if (GUILayout.Button("Train", GUILayout.Width(100)))
                    {
                        string classifierName = data.Name + "/" + DateTime.Now.ToString();

                        if (EditorUtility.DisplayDialog("Confirm", "Please confirm you want to train a new instance: " + classifierName, "Yes", "No"))
                        {
                            if (!m_NLC.TrainClassifier(classifierName, data.Language, data.Export(), OnClassiferTrained))
                            {
                                EditorUtility.DisplayDialog("Error", "Failed to train classifier.", "OK");
                            }
                        }
                    }
                    EditorGUILayout.EndHorizontal();

                    if (expanded)
                    {
                        EditorGUI.indentLevel += 1;

                        bool instancesExpanded = data.InstancesExpanded;
                        data.InstancesExpanded = EditorGUILayout.Foldout(instancesExpanded, "Instances");
                        if (instancesExpanded != data.InstancesExpanded)
                        {
                            data.Save();
                        }

                        if (instancesExpanded)
                        {
                            EditorGUI.indentLevel += 1;
                            if (m_Classifiers != null)
                            {
                                for (int i = 0; i < m_Classifiers.classifiers.Length; ++i)
                                {
                                    Classifier cl = m_Classifiers.classifiers[i];
                                    if (!cl.name.StartsWith(data.Name + "/"))
                                    {
                                        continue;
                                    }

                                    EditorGUILayout.BeginHorizontal();
                                    EditorGUILayout.LabelField("Name: " + cl.name);
                                    if (GUILayout.Button("Delete", GUILayout.Width(100)))
                                    {
                                        if (EditorUtility.DisplayDialog("Confirm", string.Format("Confirm delete of classifier {0}", cl.classifier_id), "YES", "NO") &&
                                            !m_NLC.DeleteClassifer(cl.classifier_id, OnDeleteClassifier))
                                        {
                                            EditorUtility.DisplayDialog("Error", "Failed to delete classifier.", "OK");
                                        }
                                    }
                                    EditorGUILayout.EndHorizontal();

                                    EditorGUI.indentLevel += 1;
                                    EditorGUILayout.LabelField("ID: " + cl.classifier_id);
                                    EditorGUILayout.LabelField("Created: " + cl.created.ToString());
                                    EditorGUILayout.LabelField("Status: " + cl.status);

                                    EditorGUI.indentLevel -= 1;
                                }
                            }
                            EditorGUI.indentLevel -= 1;
                        }

                        if (data.Data == null)
                        {
                            data.Data = new Dictionary <string, List <string> >();
                        }
                        if (data.DataExpanded == null)
                        {
                            data.DataExpanded = new Dictionary <string, bool>();
                        }

                        bool classesExpanded = data.ClassesExpanded;
                        data.ClassesExpanded = EditorGUILayout.Foldout(classesExpanded, "Classes");
                        if (classesExpanded != data.ClassesExpanded)
                        {
                            data.Save();
                        }

                        if (classesExpanded)
                        {
                            EditorGUI.indentLevel += 1;

                            EditorGUILayout.BeginHorizontal();
                            m_NewClassName = EditorGUILayout.TextField(m_NewClassName);
                            EditorGUI.BeginDisabledGroup(string.IsNullOrEmpty(m_NewClassName));

                            GUI.SetNextControlName("AddClass");
                            if (GUILayout.Button("Add Class", GUILayout.Width(100)))
                            {
                                data.Data[m_NewClassName] = new List <string>();
                                data.Save();

                                m_NewClassName = string.Empty;
                                GUI.FocusControl("AddClass");
                            }
                            EditorGUI.EndDisabledGroup();
                            EditorGUILayout.EndHorizontal();

                            string deleteClass = string.Empty;
                            foreach (var kp in data.Data)
                            {
                                bool classExpanded = true;
                                data.DataExpanded.TryGetValue(kp.Key, out classExpanded);

                                EditorGUILayout.BeginHorizontal();
                                data.DataExpanded[kp.Key] = EditorGUILayout.Foldout(classExpanded, "Class: " + kp.Key);
                                if (classExpanded != data.DataExpanded[kp.Key])
                                {
                                    data.Save();
                                }

                                if (GUILayout.Button("Delete", GUILayout.Width(100)))
                                {
                                    if (EditorUtility.DisplayDialog("Confirm", "Please confirm you want to delete class: " + kp.Key, "Yes", "No"))
                                    {
                                        deleteClass = kp.Key;
                                    }
                                }
                                EditorGUILayout.EndHorizontal();

                                if (classExpanded)
                                {
                                    EditorGUI.indentLevel += 1;

                                    EditorGUILayout.BeginHorizontal();
                                    m_NewPhrase = EditorGUILayout.TextField(m_NewPhrase);
                                    EditorGUI.BeginDisabledGroup(string.IsNullOrEmpty(m_NewPhrase));

                                    GUI.SetNextControlName("AddPhrase");
                                    if (GUILayout.Button("Add Phrase", GUILayout.Width(100)))
                                    {
                                        kp.Value.Add(m_NewPhrase);
                                        data.Save();

                                        m_NewPhrase = string.Empty;
                                        GUI.FocusControl("AddPhrase");
                                    }
                                    EditorGUI.EndDisabledGroup();
                                    EditorGUILayout.EndHorizontal();

                                    for (int i = 0; i < kp.Value.Count; ++i)
                                    {
                                        EditorGUILayout.BeginHorizontal();
                                        kp.Value[i] = EditorGUILayout.TextField(kp.Value[i]);

                                        if (GUILayout.Button("Delete", GUILayout.Width(100)))
                                        {
                                            kp.Value.RemoveAt(i--);
                                        }

                                        EditorGUILayout.EndHorizontal();
                                    }

                                    EditorGUI.indentLevel -= 1;
                                }
                            }

                            if (!string.IsNullOrEmpty(deleteClass))
                            {
                                data.Data.Remove(deleteClass);
                                data.DataExpanded.Remove(deleteClass);
                                data.Save();
                            }

                            EditorGUI.indentLevel -= 1;
                        }

                        EditorGUI.indentLevel -= 1;
                    }
                }

                if (deleteClassifier != null)
                {
                    File.Delete(deleteClassifier.FileName);
                    m_ClassifierData.Remove(deleteClassifier);

                    AssetDatabase.Refresh();
                }
            }
            //EditorGUI.indentLevel -= 1;

            EditorGUILayout.LabelField("Create Classifier:");
            EditorGUI.indentLevel += 1;

            m_NewClassifierName = EditorGUILayout.TextField("Name", m_NewClassifierName);
            m_NewClassifierLang = EditorGUILayout.TextField("Language", m_NewClassifierLang);

            EditorGUI.BeginDisabledGroup(string.IsNullOrEmpty(m_NewClassifierLang) || string.IsNullOrEmpty(m_NewClassifierName));
            if (GUILayout.Button("Create"))
            {
                m_NewClassifierName = m_NewClassifierName.Replace("/", "_");

                string classifierFile = m_ClassifiersFolder + "/" + m_NewClassifierName + ".json";
                if (!File.Exists(classifierFile) ||
                    EditorUtility.DisplayDialog("Confirm", string.Format("Classifier file {0} already exists, are you sure you wish to overwrite?", classifierFile), "YES", "NO"))
                {
                    ClassifierData newClassifier = new ClassifierData();
                    newClassifier.Name     = m_NewClassifierName;
                    newClassifier.Language = m_NewClassifierLang;
                    newClassifier.Save(classifierFile);
                    m_NewClassifierName = string.Empty;

                    OnRefresh();
                }
            }
            EditorGUI.EndDisabledGroup();
            EditorGUI.indentLevel -= 1;


            bool showAllClassifiers = m_DisplayClassifiers;

            m_DisplayClassifiers = EditorGUILayout.Foldout(showAllClassifiers, "All Classifier Instances");

            if (showAllClassifiers)
            {
                EditorGUI.indentLevel += 1;

                if (m_Classifiers != null)
                {
                    for (int i = 0; i < m_Classifiers.classifiers.Length; ++i)
                    {
                        Classifier cl = m_Classifiers.classifiers[i];

                        EditorGUILayout.BeginHorizontal();
                        EditorGUILayout.LabelField("Name: " + cl.name);
                        if (GUILayout.Button("Delete", GUILayout.Width(100)))
                        {
                            if (EditorUtility.DisplayDialog("Confirm", string.Format("Confirm delete of classifier {0}", cl.classifier_id), "YES", "NO") &&
                                !m_NLC.DeleteClassifer(cl.classifier_id, OnDeleteClassifier))
                            {
                                EditorUtility.DisplayDialog("Error", "Failed to delete classifier.", "OK");
                            }
                        }
                        EditorGUILayout.EndHorizontal();

                        EditorGUI.indentLevel += 1;
                        EditorGUILayout.LabelField("ID: " + cl.classifier_id);
                        EditorGUILayout.LabelField("Created: " + cl.created.ToString());
                        EditorGUILayout.LabelField("Status: " + cl.status);

                        EditorGUI.indentLevel -= 1;
                    }
                }
                EditorGUI.indentLevel -= 1;
            }

            //EditorGUILayout.LabelField("Create Classifier:" );
            //EditorGUI.indentLevel += 1;

            //m_NewClassifierName = EditorGUILayout.TextField("Name", m_NewClassifierName );
            //m_NewClassifierLang = EditorGUILayout.TextField("Language", m_NewClassifierLang );

            //EditorGUI.BeginDisabledGroup( string.IsNullOrEmpty(m_NewClassifierLang) || string.IsNullOrEmpty(m_NewClassifierName) );
            //if ( GUILayout.Button( "Create" ) )
            //{
            //    var path = EditorUtility.OpenFilePanel( "Select Training File", "", "csv" );
            //    if (! string.IsNullOrEmpty( path ) )
            //    {
            //        string trainingData = File.ReadAllText( path );
            //        if (! string.IsNullOrEmpty( trainingData ) )
            //        {
            //            string name = m_NewClassifierName;
            //            if ( string.IsNullOrEmpty( name ) )
            //                name = DateTime.Now.ToString();

            //            if (! m_NLC.TrainClassifier( name, m_NewClassifierLang, trainingData, OnClassiferTrained ) )
            //                EditorUtility.DisplayDialog( "Error", "Failed to train classifier.", "OK" );
            //        }
            //        else
            //            EditorUtility.DisplayDialog( "Error", "Failed to load training data: " + path, "OK" );
            //    }

            //    m_NewClassifierName = null;
            //}
            //EditorGUI.EndDisabledGroup();
            //EditorGUI.indentLevel -= 1;

            EditorGUILayout.EndVertical();
            EditorGUILayout.EndScrollView();
        }
示例#5
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();

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

                //  Get credentials from a credential file defined in environmental variables in the VCAP_SERVICES format.
                //  See https://www.ibm.com/watson/developercloud/doc/common/getting-started-variables.html.
                var environmentalVariable = Environment.GetEnvironmentVariable("VCAP_SERVICES");
                var fileContent           = File.ReadAllText(environmentalVariable);

                //  Add in a parent object because Unity does not like to deserialize root level collection types.
                fileContent = Utility.AddTopLevelObjectToJson(fileContent, "VCAP_SERVICES");

                //  Convert json to fsResult
                fsResult r = fsJsonParser.Parse(fileContent, out data);
                if (!r.Succeeded)
                {
                    throw new WatsonException(r.FormattedMessages);
                }

                //  Convert fsResult to VcapCredentials
                object obj = vcapCredentials;
                r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
                if (!r.Succeeded)
                {
                    throw new WatsonException(r.FormattedMessages);
                }

                //  Set credentials from imported credntials
                Credential credential = vcapCredentials.VCAP_SERVICES["natural_language_classifier"][TestCredentialIndex].Credentials;
                _username = credential.Username.ToString();
                _password = credential.Password.ToString();
                _url      = credential.Url.ToString();
            }
            catch
            {
                Log.Debug("TestNaturalLanguageClassifier", "Failed to get credentials from VCAP_SERVICES file. Please configure credentials to run this test. For more information, see: https://github.com/watson-developer-cloud/unity-sdk/#authentication");
            }

            //  Create credential and instantiate service
            Credentials credentials = new Credentials(_username, _password, _url);

            //  Or authenticate using token
            //Credentials credentials = new Credentials(_url)
            //{
            //    AuthenticationToken = _token
            //};

            naturalLanguageClassifier = new NaturalLanguageClassifier(credentials);

            //  Get classifiers
            if (!naturalLanguageClassifier.GetClassifiers(OnGetClassifiers))
            {
                Log.Debug("ExampleNaturalLanguageClassifier", "Failed to get classifiers!");
            }

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

            if (_classifierIds.Count == 0)
            {
                Log.Debug("ExampleNaturalLanguageClassifier", "There are no trained classifiers. Please train a classifier...");
            }

            if (_classifierIds.Count > 0)
            {
                //  Get each classifier
                foreach (string classifierId in _classifierIds)
                {
                    if (!naturalLanguageClassifier.GetClassifier(classifierId, OnGetClassifier))
                    {
                        Log.Debug("ExampleNaturalLanguageClassifier", "Failed to get classifier {0}!", classifierId);
                    }
                }

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

            if (!_areAnyClassifiersAvailable && _classifierIds.Count > 0)
            {
                Log.Debug("ExampleNaturalLanguageClassifier", "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(_classifierName + "/" + DateTime.Now.ToString(), "en", trainingContent, OnTrainClassifier))
            {
                Log.Debug("ExampleNaturalLanguageClassifier", "Failed to train clasifier!");
            }

            while (!_trainClassifierTested)
            {
                yield return(null);
            }
#endif

#if DELETE_TRAINED_CLASSIFIER
            if (!string.IsNullOrEmpty(_classifierToDelete))
            {
                if (!naturalLanguageClassifier.DeleteClassifer(_classifierToDelete, OnDeleteTrainedClassifier))
                {
                    Log.Debug("ExampleNaturalLanguageClassifier", "Failed to delete clasifier {0}!", _classifierToDelete);
                }
            }
#endif

            //  Classify
            if (_areAnyClassifiersAvailable)
            {
                if (!naturalLanguageClassifier.Classify(_classifierId, _inputString, OnClassify))
                {
                    Log.Debug("ExampleNaturalLanguageClassifier", "Failed to classify!");
                }

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

            Log.Debug("ExampleNaturalLanguageClassifier", "Natural language classifier examples complete.");

            yield break;
        }
    private IEnumerator Examples()
    {
        //  Get classifiers
        if (!naturalLanguageClassifier.GetClassifiers(OnGetClassifiers))
        {
            Log.Debug("ExampleNaturalLanguageClassifier", "Failed to get classifiers!");
        }

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

        if (_classifierIds.Count == 0)
        {
            Log.Debug("ExampleNaturalLanguageClassifier", "There are no trained classifiers. Please train a classifier...");
        }

        if (_classifierIds.Count > 0)
        {
            //  Get each classifier
            foreach (string classifierId in _classifierIds)
            {
                if (!naturalLanguageClassifier.GetClassifier(classifierId, OnGetClassifier))
                {
                    Log.Debug("ExampleNaturalLanguageClassifier", "Failed to get classifier {0}!", classifierId);
                }
            }

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

        if (!_areAnyClassifiersAvailable && _classifierIds.Count > 0)
        {
            Log.Debug("ExampleNaturalLanguageClassifier", "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(_classifierName + "/" + DateTime.Now.ToString(), "en", trainingContent, OnTrainClassifier))
        {
            Log.Debug("ExampleNaturalLanguageClassifier", "Failed to train clasifier!");
        }

        while (!_trainClassifierTested)
        {
            yield return(null);
        }
#endif

#if DELETE_TRAINED_CLASSIFIER
        if (!string.IsNullOrEmpty(_classifierToDelete))
        {
            if (!naturalLanguageClassifier.DeleteClassifer(_classifierToDelete, OnDeleteTrainedClassifier))
            {
                Log.Debug("ExampleNaturalLanguageClassifier", "Failed to delete clasifier {0}!", _classifierToDelete);
            }
        }
#endif

        //  Classify
        if (_areAnyClassifiersAvailable)
        {
            if (!naturalLanguageClassifier.Classify(_classifierId, _inputString, OnClassify))
            {
                Log.Debug("ExampleNaturalLanguageClassifier", "Failed to classify!");
            }

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

        Log.Debug("ExampleNaturalLanguageClassifier", "Natural language classifier examples complete.");
    }