public bool GetDilemma(OnDilemma callback, Problem problem, Boolean generateVisualization)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, FUNCTION_DILEMMA);

            if (connector == null)
            {
                return(false);
            }

            GetDilemmaRequest req = new GetDilemmaRequest();

            req.Callback   = callback;
            req.OnResponse = GetDilemmaResponse;
            req.Parameters["generate_visualization"] = generateVisualization.ToString();

            fsData tempData = null;

            sm_Serializer.TrySerialize <Problem>(problem, out tempData);

            Log.Status("GetDilemma", "JSON: {0}", tempData.ToString());

            req.Send = Encoding.UTF8.GetBytes(tempData.ToString());
            req.Headers["Content-Type"] = "application/json";

            return(connector.Send(req));
        }
Esempio n. 2
0
    private static void OnGetModels(ListModelsResults resp, string customData)
    {
        fsData data = null;

        sm_Serializer.TrySerialize(resp, out data).AssertSuccess();
        Log.Debug("ExampleNaturalLanguageUnderstandingV1", "ListModelsResult: {0}", data.ToString());
    }
        /// <summary>
        /// Returns a dilemma that contains the problem and a resolution. The problem contains a set of options and objectives. The resolution
        /// contains a set of optimal options, their analytical characteristics, and by default their representation on a two-dimensional space.
        /// You can optionally request that the service also return a refined set of preferable options that are most likely to appeal to the
        /// greatest number of users
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="problem">The decision problem.</param>
        /// <param name="generateVisualization">Indicates whether to calculate the map visualization. If true, the visualization is returned if
        /// the is_objective field is true for at least three columns and at least three options have a status of FRONT in the problem resolution.</param>
        /// <param name="customData">Optional custom data.</param>
        /// <returns></returns>
        public bool GetDilemma(SuccessCallback <DilemmasResponse> successCallback, FailCallback failCallback, Problem problem, Boolean generateVisualization, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }

            RESTConnector connector = RESTConnector.GetConnector(Credentials, DillemaEndpoint);

            if (connector == null)
            {
                return(false);
            }

            GetDilemmaRequest req = new GetDilemmaRequest();

            req.SuccessCallback = successCallback;
            req.FailCallback    = failCallback;
            req.CustomData      = customData == null ? new Dictionary <string, object>() : customData;
            req.OnResponse      = GetDilemmaResponse;
            req.Parameters["generate_visualization"] = generateVisualization.ToString();

            fsData tempData = null;

            _serializer.TrySerialize <Problem>(problem, out tempData);

            req.Send = Encoding.UTF8.GetBytes(tempData.ToString());
            req.Headers["Content-Type"] = "application/json";

            return(connector.Send(req));
        }
Esempio n. 4
0
        ///Deserialize from json
        public static object Deserialize(Type type, string serializedState, List <UnityEngine.Object> objectReferences = null, object deserialized = null)
        {
            lock (serializerLock)
            {
                if (!init)
                {
                    serializer.AddConverter(new fsUnityObjectConverter());
                    init = true;
                }

                //set the objectReferences context
                if (objectReferences != null)
                {
                    serializer.Context.Set <List <UnityEngine.Object> >(objectReferences);
                }

                fsData data = null;
                cache.TryGetValue(serializedState, out data);
                if (data == null)
                {
                    data = fsJsonParser.Parse(serializedState);
                    var str = data.ToString();
                    cache[serializedState] = data;
                }

                //deserialize the data
                //We override the UnityObject converter if we deserialize a UnityObject directly.
                //UnityObject converter will still be used for every serialized property found within the object though.
                var overrideConverterType = typeof(UnityEngine.Object).RTIsAssignableFrom(type)? typeof(fsReflectedConverter) : null;
                serializer.TryDeserialize(data, type, overrideConverterType, ref deserialized).AssertSuccess();

                return(deserialized);
            }
        }
        /// <summary>
        /// Creates a new environment. You can only create one environment per service instance.An attempt to create another environment
        /// will result in an error. The size of the new environment can be controlled by specifying the size parameter.
        /// </summary>
        /// <param name="callback">The OnAnalyze callback.</param>
        /// <param name="parameters">The analyze parameters.</param>
        /// <param name="customData">Optional custom data.</param>
        /// <returns>True if the call succeeds, false if the call is unsuccessful.</returns>
        public bool Analyze(OnAnalyze callback, Parameters parameters, string customData = default(string))
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            AnalyzeRequest req = new AnalyzeRequest();

            req.Callback                = callback;
            req._Parameters             = parameters;
            req.Data                    = customData;
            req.OnResponse              = OnAnalyzeResponse;
            req.Headers["Content-Type"] = "application/json";
            req.Headers["Accept"]       = "application/json";
            req.Parameters["version"]   = NaturalLanguageUnderstandingVersion.Version;

            fsData   data     = null;
            fsResult r        = sm_Serializer.TrySerialize(parameters, out data);
            string   sendjson = data.ToString();

            req.Send = Encoding.UTF8.GetBytes(sendjson);
            RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_ANALYZE);

            if (connector == null)
            {
                return(false);
            }

            return(connector.Send(req));
        }
Esempio n. 6
0
    private void OnAnalyze(AnalysisResults resp, string customData)
    {
        fsData data = null;

        sm_Serializer.TrySerialize(resp, out data).AssertSuccess();
        Log.Debug("ExampleNaturalLanguageUnderstandingV1", "AnalysisResults: {0}", data.ToString());
    }
Esempio n. 7
0
        public override void OnBeforeDeserialize(Type storageType, ref fsData data)
        {
            if (data.IsNull)
            {
                return;
            }

            var json = data.AsDictionary;

            fsData typeData;

            if (json.TryGetValue("$type", out typeData))
            {
                var serializedType = ReflectionTools.GetType(typeData.AsString);

                //Handle missing serialized Node type
                if (serializedType == null)
                {
                    //First try get an automatic replacement
                    serializedType = TryGetReplacement(typeData.AsString);
                    if (serializedType != null)
                    {
                        json["$type"] = new fsData(serializedType.FullName);
                        return;
                    }

                    //Otherwise replace with a Missing Node
                    //inject the 'MissingNode' type and store recovery serialization state.
                    //recoveryState and missingType are serializable members of MissingNode.
                    json["recoveryState"] = new fsData(data.ToString());
                    json["missingType"]   = new fsData(typeData.AsString);
                    json["$type"]         = new fsData(typeof(MissingNode).FullName);
                }

                //Recover possibly found serialized type
                if (serializedType == typeof(MissingNode))
                {
                    //Does the missing type now exists?
                    var missingType = ReflectionTools.GetType(json["missingType"].AsString);

                    //If still not try auto replacement
                    if (missingType == null)
                    {
                        missingType = TryGetReplacement(json["missingType"].AsString);
                    }

                    //Finaly recover if we have a type
                    if (missingType != null)
                    {
                        var recoveryState = json["recoveryState"].AsString;
                        var recoverJson   = fsJsonParser.Parse(recoveryState).AsDictionary;

                        //merge the recover state *ON TOP* of the current state, thus merging only Declared recovered members
                        json          = json.Concat(recoverJson.Where(kvp => !json.ContainsKey(kvp.Key))).ToDictionary(c => c.Key, c => c.Value);
                        json["$type"] = new fsData(missingType.FullName);
                        data          = new fsData(json);
                    }
                }
            }
        }
Esempio n. 8
0
        public bool GetDilemma(OnDilemma callback, Problem problem, Boolean generateVisualization, string customData = default(string))
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            RESTConnector connector = RESTConnector.GetConnector(Credentials, DillemaEndpoint);

            if (connector == null)
            {
                return(false);
            }

            GetDilemmaRequest req = new GetDilemmaRequest();

            req.Callback   = callback;
            req.OnResponse = GetDilemmaResponse;
            req.Data       = customData;
            req.Parameters["generate_visualization"] = generateVisualization.ToString();

            fsData tempData = null;

            _serializer.TrySerialize <Problem>(problem, out tempData);

            req.Send = Encoding.UTF8.GetBytes(tempData.ToString());
            req.Headers["Content-Type"] = "application/json";

            return(connector.Send(req));
        }
Esempio n. 9
0
        public override void OnBeforeDeserialize(Type storageType, ref fsData data)
        {
            if (data.IsNull)
            {
                return;
            }

            var json = data.AsDictionary;

            fsData typeData;

            if (json.TryGetValue("$type", out typeData))
            {
                var serializedType = ReflectionTools.GetType(typeData.AsString);

                if (serializedType == null || serializedType == typeof(MissingConnection))
                {
                    //TargetType is either the one missing or the one previously stored as missing in the MissingConnection.
                    var targetFullTypeName = serializedType == null? typeData.AsString : json["missingType"].AsString;
                    //Try find type with same name in some other namespace that is subclass of Connection
                    var typeNameWithoutNS = targetFullTypeName.Split('.').LastOrDefault();
                    foreach (var type in ReflectionTools.GetAllTypes())
                    {
                        if (type.Name == typeNameWithoutNS && type.IsSubclassOf(typeof(NodeCanvas.Framework.Connection)))
                        {
                            json["$type"] = new fsData(type.FullName);
                            return;
                        }
                    }
                }

                //Handle missing serialized Connection type
                if (serializedType == null)
                {
                    //inject the 'MissingConnection' type and store recovery serialization state.
                    //recoveryState and missingType are serializable members of MissingConnection.
                    json["recoveryState"] = new fsData(data.ToString());
                    json["missingType"]   = new fsData(typeData.AsString);
                    json["$type"]         = new fsData(typeof(MissingConnection).FullName);
                }

                //Recover possible found serialized type
                if (serializedType == typeof(MissingConnection))
                {
                    //Does the missing type now exists? If so recover
                    var missingType = ReflectionTools.GetType(json["missingType"].AsString);
                    if (missingType != null)
                    {
                        var recoveryState = json["recoveryState"].AsString;
                        var recoverJson   = fsJsonParser.Parse(recoveryState).AsDictionary;

                        //merge the recover state *ON TOP* of the current state, thus merging only Declared recovered members
                        json          = json.Concat(recoverJson.Where(kvp => !json.ContainsKey(kvp.Key))).ToDictionary(c => c.Key, c => c.Value);
                        json["$type"] = new fsData(missingType.FullName);
                        data          = new fsData(json);
                    }
                }
            }
        }
        public override void OnBeforeDeserialize(Type storageType, ref fsData data)
        {
            if (data.IsNull)
            {
                return;
            }

            var json = data.AsDictionary;

            if (json.ContainsKey("$type"))
            {
                var serializedType = ReflectionTools.GetType(json["$type"].AsString);

                //Handle missing serialized Node type
                if (serializedType == null)
                {
                    //inject the 'MissingTask' type and store recovery serialization state
                    json["recoveryState"] = new fsData(data.ToString());
                    json["missingType"]   = new fsData(json["$type"].AsString);

                    Type missingNodeType = null;
                    if (storageType == typeof(ActionTask))
                    {
                        missingNodeType = typeof(MissingAction);
                    }
                    if (storageType == typeof(ConditionTask))
                    {
                        missingNodeType = typeof(MissingCondition);
                    }
                    if (missingNodeType == null)
                    {
                        Debug.LogError("Can't resolve missing Task type");
                        return;
                    }

                    json["$type"] = new fsData(missingNodeType.FullName);

                    //There is no way to know DecalredOnly properties to save just them instead of the whole object since we dont have an actual type
                }

                //Recover possible found serialized type
                if (serializedType == typeof(MissingAction) || serializedType == typeof(MissingCondition))
                {
                    //Does the missing type now exists? If so recover
                    var missingType = ReflectionTools.GetType(json["missingType"].AsString);
                    if (missingType != null)
                    {
                        var recoveryState = json["recoveryState"].AsString;
                        var recoverJson   = fsJsonParser.Parse(recoveryState).AsDictionary;

                        //merge the recover state *ON TOP* of the current state, thus merging only Declared recovered members
                        json          = json.Concat(recoverJson.Where(kvp => !json.ContainsKey(kvp.Key))).ToDictionary(c => c.Key, c => c.Value);
                        json["$type"] = new fsData(missingType.FullName);
                        data          = new fsData(json);
                    }
                }
            }
        }
        /// <summary>
        /// Send user input to assistant.
        ///
        /// Send user input to an assistant and receive a response.
        ///
        /// There is no rate limit for this operation.
        /// </summary>
        /// <param name="successCallback">The function that is called when the operation is successful.</param>
        /// <param name="failCallback">The function that is called when the operation fails.</param>
        /// <param name="assistantId">Unique identifier of the assistant. You can find the assistant ID of an assistant
        /// on the **Assistants** tab of the Watson Assistant tool. For information about creating assistants, see the
        /// [documentation](https://cloud.ibm.com/docs/services/assistant/create-assistant.html#creating-assistants).
        ///
        /// **Note:** Currently, the v2 API does not support creating assistants.</param>
        /// <param name="sessionId">Unique identifier of the session.</param>
        /// <param name="request">The message to be sent. This includes the user's input, along with optional intents,
        /// entities, and context from the last response. (optional)</param>
        /// <returns><see cref="MessageResponse" />MessageResponse</returns>
        /// <param name="customData">A Dictionary<string, object> of data that will be passed to the callback. The raw
        /// json output from the REST call will be passed in this object as the value of the 'json'
        /// key.</string></param>
        public bool Message(SuccessCallback <MessageResponse> successCallback, FailCallback failCallback, String assistantId, String sessionId, MessageRequest request = null, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback is required for Message");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback is required for Message");
            }
            if (string.IsNullOrEmpty(assistantId))
            {
                throw new ArgumentException("assistantId is required for Message");
            }
            if (string.IsNullOrEmpty(sessionId))
            {
                throw new ArgumentException("sessionId is required for Message");
            }

            MessageRequestObj req = new MessageRequestObj();

            req.SuccessCallback        = successCallback;
            req.FailCallback           = failCallback;
            req.HttpMethod             = UnityWebRequest.kHttpVerbPOST;
            req.DisableSslVerification = DisableSslVerification;
            req.CustomData             = customData == null ? new Dictionary <string, object>() : customData;
            if (req.CustomData.ContainsKey(Constants.String.CUSTOM_REQUEST_HEADERS))
            {
                foreach (KeyValuePair <string, string> kvp in req.CustomData[Constants.String.CUSTOM_REQUEST_HEADERS] as Dictionary <string, string> )
                {
                    req.Headers.Add(kvp.Key, kvp.Value);
                }
            }

            if (request != null)
            {
                fsData data = null;
                _serializer.TrySerialize(request, out data);
                string json = data.ToString().Replace('\"', '"');
                req.Send = Encoding.UTF8.GetBytes(json);
            }

            req.Headers["Content-Type"] = "application/json";
            req.Parameters["version"]   = VersionDate;
            req.OnResponse = OnMessageResponse;
            req.Headers["X-IBMCloud-SDK-Analytics"] = "service_name=conversation;service_version=v2;operation_id=Message";

            RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v2/assistants/{0}/sessions/{1}/message", assistantId, sessionId));

            if (connector == null)
            {
                return(false);
            }

            return(connector.Send(req));
        }
Esempio n. 12
0
        public override void OnBeforeDeserialize(Type storageType, ref fsData data)
        {
            if (data.IsNull){
                return;
            }

            var json = data.AsDictionary;

            fsData typeData;
            if (json.TryGetValue("$type", out typeData)){

                var serializedType = ReflectionTools.GetType( typeData.AsString );

                if (serializedType == null || serializedType == typeof(MissingConnection)){
                    //TargetType is either the one missing or the one previously stored as missing in the MissingConnection.
                    var targetFullTypeName = serializedType == null? typeData.AsString : json["missingType"].AsString;
                    //Try find type with same name in some other namespace that is subclass of Connection
                    var typeNameWithoutNS = targetFullTypeName.Split('.').LastOrDefault();
                    foreach(var type in ReflectionTools.GetAllTypes()){
                        if (type.Name == typeNameWithoutNS && type.IsSubclassOf(typeof(NodeCanvas.Framework.Connection))){
                            json["$type"] = new fsData(type.FullName);
                            return;
                        }
                    }
                }

                //Handle missing serialized Connection type
                if (serializedType == null){
                    //inject the 'MissingConnection' type and store recovery serialization state.
                    //recoveryState and missingType are serializable members of MissingConnection.
                    json["recoveryState"] = new fsData( data.ToString() );
                    json["missingType"] = new fsData( typeData.AsString );
                    json["$type"] = new fsData( typeof(MissingConnection).FullName );
                }

                //Recover possible found serialized type
                if (serializedType == typeof(MissingConnection)){

                    //Does the missing type now exists? If so recover
                    var missingType = ReflectionTools.GetType( json["missingType"].AsString );
                    if (missingType != null){

                        var recoveryState = json["recoveryState"].AsString;
                        var recoverJson = fsJsonParser.Parse(recoveryState).AsDictionary;

                        //merge the recover state *ON TOP* of the current state, thus merging only Declared recovered members
                        json = json.Concat( recoverJson.Where( kvp => !json.ContainsKey(kvp.Key) ) ).ToDictionary( c => c.Key, c => c.Value );
                        json["$type"] = new fsData( missingType.FullName );
                        data = new fsData( json );
                    }
                }
            }
        }
        public override void OnBeforeDeserialize(Type storageType, ref fsData data)
        {
            if (!data.IsDictionary)
            {
                return;
            }

            if (JSONSerializer.applicationPlaying)
            {
                return;
            }

            var json = data.AsDictionary;

            fsData typeData;

            if (json.TryGetValue(fsSerializer.KEY_INSTANCE_TYPE, out typeData))
            {
                //check if serialized can actually resolve the type
                var serializedType = ReflectionTools.GetType(typeData.AsString, storageType);

                //If not, handle missing serialized type
                if (serializedType == null)
                {
                    //Replace with a Missing Type
                    //inject the Missing Type and store recovery serialization state.
                    //recoveryState and missingType are serializable members of Missing Type.
                    json[FIELD_NAME_TYPE]  = new fsData(typeData.AsString);
                    json[FIELD_NAME_STATE] = new fsData(data.ToString());
                    json[fsSerializer.KEY_INSTANCE_TYPE] = new fsData(typeof(TMissing).FullName);
                }

                //Recover possibly found serialized type
                if (serializedType == typeof(TMissing))
                {
                    //Does the missing type now exists?
                    var missingType = ReflectionTools.GetType(json[FIELD_NAME_TYPE].AsString, storageType);

                    //Finaly recover if we have a type
                    if (missingType != null)
                    {
                        var recoveryState = json[FIELD_NAME_STATE].AsString;
                        var recoverJson   = fsJsonParser.Parse(recoveryState).AsDictionary;

                        //merge the recover state *ON TOP* of the current state, thus merging only Declared recovered members
                        json = json.Concat(recoverJson.Where(kvp => !json.ContainsKey(kvp.Key))).ToDictionary(c => c.Key, c => c.Value);
                        json[fsSerializer.KEY_INSTANCE_TYPE] = new fsData(missingType.FullName);
                        data = new fsData(json);
                    }
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Returns label information for multiple phrases. The status must be Available before you can use the classifier to classify text. Note that classifying Japanese texts is a beta feature.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="classifierId">The ID of the classifier to use.</param>
        /// <param name="body">The collection of text to classify.</param>
        /// <returns>Returns false if we failed to submit the request.</returns>
        public bool ClassifyCollection(SuccessCallback <ClassificationCollection> successCallback, FailCallback failCallback, string classifierId, ClassifyCollectionInput body, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }
            if (string.IsNullOrEmpty(classifierId))
            {
                throw new ArgumentNullException("classifierId");
            }
            if (body == null)
            {
                throw new ArgumentNullException("body");
            }

            RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/classifiers");

            if (connector == null)
            {
                return(false);
            }

            ClassifyCollectionReq req = new ClassifyCollectionReq();

            req.SuccessCallback        = successCallback;
            req.FailCallback           = failCallback;
            req.HttpMethod             = UnityWebRequest.kHttpVerbPOST;
            req.DisableSslVerification = DisableSslVerification;
            req.CustomData             = customData == null ? new Dictionary <string, object>() : customData;
            if (req.CustomData.ContainsKey(Constants.String.CUSTOM_REQUEST_HEADERS))
            {
                foreach (KeyValuePair <string, string> kvp in req.CustomData[Constants.String.CUSTOM_REQUEST_HEADERS] as Dictionary <string, string> )
                {
                    req.Headers.Add(kvp.Key, kvp.Value);
                }
            }
            req.OnResponse = OnClassifyCollectionResp;
            req.Headers["X-IBMCloud-SDK-Analytics"] = "service_name=natural_language_classifier;service_version=v1;operation_id=ClassifyCollection";
            req.Function = "/" + classifierId + "/classify_collection";
            req.Headers["Content-Type"] = "application/json";

            fsData data = null;

            _serializer.TrySerialize(body, out data);
            req.Send = Encoding.UTF8.GetBytes(data.ToString());

            return(connector.Send(req));
        }
        public override void OnBeforeDeserialize(Type storageType, ref fsData data)
        {
            if (data.IsNull)
                return;

            var json = data.AsDictionary;

            if (json.ContainsKey("$type")){

                var serializedType = ReflectionTools.GetType( json["$type"].AsString );

                //Handle missing serialized Node type
                if (serializedType == null){

                    //inject the 'MissingTask' type and store recovery serialization state
                    json["recoveryState"] = new fsData( data.ToString() );
                    json["missingType"] = new fsData( json["$type"].AsString );

                    Type missingNodeType = null;
                    if (storageType == typeof(ActionTask))
                        missingNodeType = typeof(MissingAction);
                    if (storageType == typeof(ConditionTask))
                        missingNodeType = typeof(MissingCondition);
                    if (missingNodeType == null){
                        Debug.LogError("Can't resolve missing Task type");
                        return;
                    }

                    json["$type"] = new fsData( missingNodeType.FullName );

                    //There is no way to know DecalredOnly properties to save just them instead of the whole object since we dont have an actual type
                }

                //Recover possible found serialized type
                if (serializedType == typeof(MissingAction) || serializedType == typeof(MissingCondition)){

                    //Does the missing type now exists? If so recover
                    var missingType = ReflectionTools.GetType( json["missingType"].AsString );
                    if (missingType != null){

                        var recoveryState = json["recoveryState"].AsString;
                        var recoverJson = fsJsonParser.Parse(recoveryState).AsDictionary;

                        //merge the recover state *ON TOP* of the current state, thus merging only Declared recovered members
                        json = json.Concat( recoverJson.Where( kvp => !json.ContainsKey(kvp.Key) ) ).ToDictionary( c => c.Key, c => c.Value );
                        json["$type"] = new fsData( missingType.FullName );
                        data = new fsData( json );
                    }
                }
            }
        }
Esempio n. 16
0
    private static void OnAnalyze(AnalysisResults resp, string customData)
    {
        //Log.Debug ("NLU", "Nicole: " + resp.entities[0]);
        //Log.Debug ("NLU", "NicoleFuck: " + resp.keywords [0]);
        fsData data = null;

        sm_Serializer.TrySerialize(resp, out data).AssertSuccess();
        Log.Debug("ExampleNaturalLanguageUnderstandingV1", "AnalysisResults: {0}", data.ToString());
        JsonData obj = JsonMapper.ToObject(data.ToString());

        Debug.Log(obj["concepts"]);
        string allText = "Topics: " + "\n";

        if (RecordSpeech.JsonContainsKey(obj, "concepts"))
        {
            for (int j = 0; j < obj ["concepts"].Count; j++)
            {
                //Debug.Log (obj ["concepts"] [j] ["text"]);
                if (RecordSpeech.JsonContainsKey(obj ["concepts"] [j], "text"))
                {
                    allText += (string)(obj ["concepts"] [j] ["text"] + "\n");
                }
            }
        }
        allText += "Keywords: " + "\n";
        if (RecordSpeech.JsonContainsKey(obj, "keywords"))
        {
            for (int j = 0; j < obj ["keywords"].Count; j++)
            {
                //Debug.Log (obj ["concepts"] [j] ["text"]);
                if (RecordSpeech.JsonContainsKey(obj ["keywords"] [j], "text"))
                {
                    allText += (string)(obj ["keywords"] [j] ["text"] + "\n");
                }
            }
        }
        GameObject.Find("TopicsText").GetComponent <Text>().text = allText;
    }
        /// <summary>
        /// Creates a new environment. You can only create one environment per service instance.An attempt to create another environment
        /// will result in an error. The size of the new environment can be controlled by specifying the size parameter.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="parameters">The analyze parameters.</param>
        /// <param name="customData">Optional custom data.</param>
        /// <returns>True if the call succeeds, false if the call is unsuccessful.</returns>
        public bool Analyze(SuccessCallback <AnalysisResults> successCallback, FailCallback failCallback, Parameters parameters, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            AnalyzeRequest req = new AnalyzeRequest();

            req.SuccessCallback        = successCallback;
            req.FailCallback           = failCallback;
            req.HttpMethod             = UnityWebRequest.kHttpVerbPOST;
            req.DisableSslVerification = DisableSslVerification;
            req.CustomData             = customData == null ? new Dictionary <string, object>() : customData;
            if (req.CustomData.ContainsKey(Constants.String.CUSTOM_REQUEST_HEADERS))
            {
                foreach (KeyValuePair <string, string> kvp in req.CustomData[Constants.String.CUSTOM_REQUEST_HEADERS] as Dictionary <string, string> )
                {
                    req.Headers.Add(kvp.Key, kvp.Value);
                }
            }
            req.OnResponse = OnAnalyzeResponse;
            req.Headers["X-IBMCloud-SDK-Analytics"] = "service_name=natural_language_understanding;service_version=v1;operation_id=Analyze";
            req.Headers["Content-Type"]             = "application/json";
            req.Headers["Accept"]     = "application/json";
            req.Parameters["version"] = NaturalLanguageUnderstandingVersion.Version;

            fsData data = null;

            _serializer.TrySerialize(parameters, out data);
            string sendjson = data.ToString();

            req.Send = Encoding.UTF8.GetBytes(sendjson);
            RESTConnector connector = RESTConnector.GetConnector(Credentials, AnalyzeEndpoint);

            if (connector == null)
            {
                return(false);
            }

            return(connector.Send(req));
        }
Esempio n. 18
0
        private void OnRefreshIamTokenResponse(RESTConnector.Request req, RESTConnector.Response resp)
        {
            DetailedResponse <IamTokenData> response = new DetailedResponse <IamTokenData>();

            response.Result = new IamTokenData();
            fsData data = null;

            foreach (KeyValuePair <string, string> kvp in resp.Headers)
            {
                response.Headers.Add(kvp.Key, kvp.Value);
            }

            if (resp.Success)
            {
                try
                {
                    fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data);
                    if (!r.Succeeded)
                    {
                        throw new IBMException(r.FormattedMessages);
                    }

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

                    response.Response = data.ToString();
                }
                catch (Exception e)
                {
                    Log.Error("TokenManager.OnRefreshTokenResponse()", "Exception: {0}", e.ToString());
                    resp.Success = false;
                }
            }

            if (((RefreshIamTokenRequest)req).Callback != null)
            {
                ((RefreshIamTokenRequest)req).Callback(response, resp.Error);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Returns label information for multiple phrases. The status must be Available before you can use the classifier to classify text. Note that classifying Japanese texts is a beta feature.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="classifierId">The ID of the classifier to use.</param>
        /// <param name="body">The collection of text to classify.</param>
        /// <returns>Returns false if we failed to submit the request.</returns>
        public bool ClassifyCollection(SuccessCallback <ClassificationCollection> successCallback, FailCallback failCallback, string classifierId, ClassifyCollectionInput body, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }
            if (string.IsNullOrEmpty(classifierId))
            {
                throw new ArgumentNullException("classifierId");
            }
            if (body == null)
            {
                throw new ArgumentNullException("body");
            }

            RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/classifiers");

            if (connector == null)
            {
                return(false);
            }

            ClassifyCollectionReq req = new ClassifyCollectionReq();

            req.SuccessCallback         = successCallback;
            req.FailCallback            = failCallback;
            req.CustomData              = customData == null ? new Dictionary <string, object>() : customData;
            req.OnResponse              = OnClassifyCollectionResp;
            req.Function                = "/" + classifierId + "/classify_collection";
            req.Headers["Content-Type"] = "application/json";

            fsData data = null;

            _serializer.TrySerialize(body, out data);
            req.Send = Encoding.UTF8.GetBytes(data.ToString());

            return(connector.Send(req));
        }
        public override void OnBeforeDeserialize(Type storageType, ref fsData data)
        {
            if (data.IsNull)
            {
                return;
            }

            var json = data.AsDictionary;

            if (json.ContainsKey("$type"))
            {
                var serializedType = ReflectionTools.GetType(json["$type"].AsString);

                //Handle missing serialized Node type
                if (serializedType == null)
                {
                    //inject the 'MissingNode' type and store recovery serialization state
                    json["recoveryState"] = new fsData(data.ToString());
                    json["missingType"]   = new fsData(json["$type"].AsString);
                    json["$type"]         = new fsData(typeof(MissingNode).FullName);
                }

                //Recover possible found serialized type
                if (serializedType == typeof(MissingNode))
                {
                    //Does the missing type now exists? If so recover
                    var missingType = ReflectionTools.GetType(json["missingType"].AsString);
                    if (missingType != null)
                    {
                        var recoveryState = json["recoveryState"].AsString;
                        var recoverJson   = fsJsonParser.Parse(recoveryState).AsDictionary;

                        //merge the recover state *ON TOP* of the current state, thus merging only Declared recovered members
                        json          = json.Concat(recoverJson.Where(kvp => !json.ContainsKey(kvp.Key))).ToDictionary(c => c.Key, c => c.Value);
                        json["$type"] = new fsData(missingType.FullName);
                        data          = new fsData(json);
                    }
                }
            }
        }
        /// <summary>
        /// Creates a new environment. You can only create one environment per service instance.An attempt to create another environment
        /// will result in an error. The size of the new environment can be controlled by specifying the size parameter.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="parameters">The analyze parameters.</param>
        /// <param name="customData">Optional custom data.</param>
        /// <returns>True if the call succeeds, false if the call is unsuccessful.</returns>
        public bool Analyze(SuccessCallback <AnalysisResults> successCallback, FailCallback failCallback, Parameters parameters, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            AnalyzeRequest req = new AnalyzeRequest();

            req.SuccessCallback         = successCallback;
            req.FailCallback            = failCallback;
            req.CustomData              = customData == null ? new Dictionary <string, object>() : customData;
            req.OnResponse              = OnAnalyzeResponse;
            req.Headers["Content-Type"] = "application/json";
            req.Headers["Accept"]       = "application/json";
            req.Parameters["version"]   = NaturalLanguageUnderstandingVersion.Version;

            fsData data = null;

            _serializer.TrySerialize(parameters, out data);
            string sendjson = data.ToString();

            req.Send = Encoding.UTF8.GetBytes(sendjson);
            RESTConnector connector = RESTConnector.GetConnector(Credentials, AnalyzeEndpoint);

            if (connector == null)
            {
                return(false);
            }

            return(connector.Send(req));
        }
		public override void OnBeforeDeserialize(Type storageType, ref fsData data){
			
			if (data.IsNull)
				return;

			var json = data.AsDictionary;

			if (json.ContainsKey("$type")){

				var serializedType = ReflectionTools.GetType( json["$type"].AsString );

				//Handle missing serialized Node type
				if (serializedType == null){

					//inject the 'MissingNode' type and store recovery serialization state
					json["recoveryState"] = new fsData( data.ToString() );
					json["missingType"] = new fsData( json["$type"].AsString );
					json["$type"] = new fsData( typeof(MissingNode).FullName );
				}

				//Recover possible found serialized type
				if (serializedType == typeof(MissingNode)){

					//Does the missing type now exists? If so recover
					var missingType = ReflectionTools.GetType( json["missingType"].AsString );
					if (missingType != null){

						var recoveryState = json["recoveryState"].AsString;
						var recoverJson = fsJsonParser.Parse(recoveryState).AsDictionary;

						//merge the recover state *ON TOP* of the current state, thus merging only Declared recovered members
						json = json.Concat( recoverJson.Where( kvp => !json.ContainsKey(kvp.Key) ) ).ToDictionary( c => c.Key, c => c.Value );
						json["$type"] = new fsData( missingType.FullName );
						data = new fsData( json );
					}
				}
			}
		}
Esempio n. 23
0
        private void GetLanguagesResponse(RESTConnector.Request req, RESTConnector.Response resp)
        {
            Languages langs = new Languages();
            fsData    data  = null;

            if (resp.Success)
            {
                try
                {
                    fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data);
                    if (!r.Succeeded)
                    {
                        throw new WatsonException(r.FormattedMessages);
                    }

                    object obj = langs;
                    r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
                    if (!r.Succeeded)
                    {
                        throw new WatsonException(r.FormattedMessages);
                    }
                }
                catch (Exception e)
                {
                    Log.Error("Natural Language Classifier", "GetLanguages Exception: {0}", e.ToString());
                    resp.Success = false;
                }
            }

            string customData = ((GetLanguagesReq)req).Data;

            if (((GetLanguagesReq)req).Callback != null)
            {
                ((GetLanguagesReq)req).Callback(resp.Success ? langs : null, (!string.IsNullOrEmpty(customData) ? customData : data.ToString()));
            }
        }
Esempio n. 24
0
        private void OnCreateModelResponse(RESTConnector.Request req, RESTConnector.Response resp)
        {
            TranslationModel result = new TranslationModel();
            fsData           data   = null;

            if (resp.Success)
            {
                try
                {
                    fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data);

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

                    object obj = result;
                    r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
                    if (!r.Succeeded)
                    {
                        throw new WatsonException(r.FormattedMessages);
                    }
                }
                catch (Exception e)
                {
                    Log.Error("Discovery", "Create model Exception: {0}", e.ToString());
                    resp.Success = false;
                }
            }

            string customData = ((CreateModelRequest)req).Data;

            if (((CreateModelRequest)req).Callback != null)
            {
                ((CreateModelRequest)req).Callback(resp.Success ? result : null, !string.IsNullOrEmpty(customData) ? customData : data.ToString());
            }
        }
Esempio n. 25
0
        public override void OnBeforeDeserialize(Type storageType, ref fsData data)
        {
            if (data.IsNull){
                return;
            }

            var json = data.AsDictionary;

            fsData typeData;
            if (json.TryGetValue("$type", out typeData)){

                var serializedType = ReflectionTools.GetType( typeData.AsString );

                if (serializedType == null || serializedType == typeof(MissingAction) || serializedType == typeof(MissingCondition)){
                    //TargetType is either the one missing or the one previously stored as missing in the MissingTask.
                    var targetFullTypeName = serializedType == null? typeData.AsString : json["missingType"].AsString;
                    //try find defined [DeserializeFrom] attribute
                    foreach(var type in ReflectionTools.GetAllTypes()){
                        var att = type.RTGetAttribute<DeserializeFromAttribute>(false);
                        if (att != null && att.previousTypeNames.Any(n => n == targetFullTypeName) ){
                            json["$type"] = new fsData( type.FullName );
                            return;
                        }
                    }

                    //Try find type with same name in some other namespace that is subclass of Task
                    var typeNameWithoutNS = targetFullTypeName.Split('.').LastOrDefault();
                    foreach(var type in ReflectionTools.GetAllTypes()){
                        if (type.Name == typeNameWithoutNS && type.IsSubclassOf(typeof(NodeCanvas.Framework.Task))){
                            json["$type"] = new fsData(type.FullName);
                            return;
                        }
                    }
                }

                //Handle missing serialized Task type
                if (serializedType == null){
                    //Otherwise replace with a missing task.
                    Type missingNodeType = null;
                    if (storageType == typeof(ActionTask)){ missingNodeType = typeof(MissingAction); }
                    if (storageType == typeof(ConditionTask)){ missingNodeType = typeof(MissingCondition); }
                    if (missingNodeType == null){ return; }

                    //inject the 'MissingTask' type and store recovery serialization state.
                    //recoveryState and missingType are serializable members of MissingTask.
                    json["$type"] = new fsData( missingNodeType.FullName );
                    json["recoveryState"] = new fsData( data.ToString() );
                    json["missingType"] = new fsData( typeData.AsString );

                    //There is no way to know DecalredOnly properties to save just them instead of the whole object since we dont have an actual type
                }

                //Recover possible found serialized type
                if (serializedType == typeof(MissingAction) || serializedType == typeof(MissingCondition)){

                    //Does the missing type now exists? If so recover
                    var missingType = ReflectionTools.GetType( json["missingType"].AsString );
                    if (missingType != null){

                        var recoveryState = json["recoveryState"].AsString;
                        var recoverJson = fsJsonParser.Parse(recoveryState).AsDictionary;

                        //merge the recover state *ON TOP* of the current state, thus merging only Declared recovered members
                        json = json.Concat( recoverJson.Where( kvp => !json.ContainsKey(kvp.Key) ) ).ToDictionary( c => c.Key, c => c.Value );
                        json["$type"] = new fsData( missingType.FullName );
                        data = new fsData( json );
                    }
                }
            }
        }
Esempio n. 26
0
        private void GetProfileResponse(RESTConnector.Request req, RESTConnector.Response resp)
        {
            Profile response = new Profile();
            fsData  data     = null;

            if (resp.Success)
            {
                try
                {
                    fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data);
                    if (!r.Succeeded)
                    {
                        throw new WatsonException(r.FormattedMessages);
                    }

                    object obj = response;
                    r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
                    if (!r.Succeeded)
                    {
                        throw new WatsonException(r.FormattedMessages);
                    }
                }
                catch (Exception e)
                {
                    Log.Error("PersonalityInsights", "GetProfileResponse Exception: {0}", e.ToString());
                    resp.Success = false;
                }
            }

            string customData = ((GetProfileRequest)req).Data;

            if (((GetProfileRequest)req).Callback != null)
            {
                ((GetProfileRequest)req).Callback(resp.Success ? response : null, !string.IsNullOrEmpty(customData) ? customData : data.ToString());
            }
        }
Esempio n. 27
0
        public override void OnBeforeDeserialize(Type storageType, ref fsData data)
        {
            if (data.IsNull)
            {
                return;
            }

            var json = data.AsDictionary;

            fsData typeData;

            if (json.TryGetValue("$type", out typeData))
            {
                var serializedType = ReflectionTools.GetType(typeData.AsString);

                if (serializedType == null || serializedType == typeof(MissingAction) || serializedType == typeof(MissingCondition))
                {
                    //TargetType is either the one missing or the one previously stored as missing in the MissingTask.
                    var targetFullTypeName = serializedType == null? typeData.AsString : json["missingType"].AsString;
                    //try find defined [DeserializeFrom] attribute
                    foreach (var type in ReflectionTools.GetAllTypes())
                    {
                        var att = type.RTGetAttribute <DeserializeFromAttribute>(false);
                        if (att != null && att.previousTypeNames.Any(n => n == targetFullTypeName))
                        {
                            json["$type"] = new fsData(type.FullName);
                            return;
                        }
                    }

                    //Try find type with same name in some other namespace that is subclass of Task
                    var typeNameWithoutNS = targetFullTypeName.Split('.').LastOrDefault();
                    foreach (var type in ReflectionTools.GetAllTypes())
                    {
                        if (type.Name == typeNameWithoutNS && type.IsSubclassOf(typeof(NodeCanvas.Framework.Task)))
                        {
                            json["$type"] = new fsData(type.FullName);
                            return;
                        }
                    }
                }

                //Handle missing serialized Task type
                if (serializedType == null)
                {
                    //Otherwise replace with a missing task.
                    Type missingNodeType = null;
                    if (storageType == typeof(ActionTask))
                    {
                        missingNodeType = typeof(MissingAction);
                    }
                    if (storageType == typeof(ConditionTask))
                    {
                        missingNodeType = typeof(MissingCondition);
                    }
                    if (missingNodeType == null)
                    {
                        return;
                    }

                    //inject the 'MissingTask' type and store recovery serialization state.
                    //recoveryState and missingType are serializable members of MissingTask.
                    json["$type"]         = new fsData(missingNodeType.FullName);
                    json["recoveryState"] = new fsData(data.ToString());
                    json["missingType"]   = new fsData(typeData.AsString);

                    //There is no way to know DecalredOnly properties to save just them instead of the whole object since we dont have an actual type
                }

                //Recover possible found serialized type
                if (serializedType == typeof(MissingAction) || serializedType == typeof(MissingCondition))
                {
                    //Does the missing type now exists? If so recover
                    var missingType = ReflectionTools.GetType(json["missingType"].AsString);
                    if (missingType != null)
                    {
                        var recoveryState = json["recoveryState"].AsString;
                        var recoverJson   = fsJsonParser.Parse(recoveryState).AsDictionary;

                        //merge the recover state *ON TOP* of the current state, thus merging only Declared recovered members
                        json          = json.Concat(recoverJson.Where(kvp => !json.ContainsKey(kvp.Key))).ToDictionary(c => c.Key, c => c.Value);
                        json["$type"] = new fsData(missingType.FullName);
                        data          = new fsData(json);
                    }
                }
            }
        }