Exemplo n.º 1
0
        /// <summary>
        /// Delete a specific model by it's ID.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="model_id">The model to delete.</param>
        /// <returns></returns>
        public bool DeleteModel(SuccessCallback <DeleteModelResult> successCallback, FailCallback failCallback, string model_id, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }
            if (string.IsNullOrEmpty(model_id))
            {
                throw new ArgumentNullException("model_id");
            }

            RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/models/");

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

            DeleteModelReq req = new DeleteModelReq();

            req.Parameters["version"]  = VersionDate;
            req.SuccessCallback        = successCallback;
            req.FailCallback           = failCallback;
            req.HttpMethod             = UnityWebRequest.kHttpVerbDELETE;
            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.Function   = UnityWebRequest.EscapeURL(model_id);
            req.OnResponse = DeleteModelResponse;
            return(connector.Send(req));
        }
        private bool GetTranslation(SuccessCallback <Translations> successCallback, FailCallback failCallback, string json, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }
            if (string.IsNullOrEmpty(json))
            {
                throw new ArgumentNullException("json");
            }

            RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v2/translate");

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

            TranslateReq req = new TranslateReq();

            req.SuccessCallback = successCallback;
            req.FailCallback    = failCallback;
            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              = TranslateResponse;
            req.Send                    = Encoding.UTF8.GetBytes(json);
            req.Headers["accept"]       = "application/json";
            req.Headers["Content-Type"] = "application/json";

            return(connector.Send(req));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Converse with the dialog system.
        /// </summary>
        /// <param name="dialogId">The dialog ID of the dialog to use.</param>
        /// <param name="input">The text input.</param>
        /// <param name="callback">The callback for receiving the responses.</param>
        /// <param name="conversation_id">The conversation ID to use, if 0 then a new conversation will be started.</param>
        /// <param name="client_id">The client ID of the user.</param>
        /// <returns>Returns true if the request was submitted to the back-end.</returns>
        public bool Converse(string dialogId, string input, OnConverse callback,
                             int conversation_id = 0, int client_id = 0)
        {
            if (string.IsNullOrEmpty(dialogId))
            {
                throw new ArgumentNullException("dialogId");
            }
            if (string.IsNullOrEmpty(input))
            {
                throw new ArgumentNullException("input");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/dialogs");

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

            ConverseReq req = new ConverseReq();

            req.Function       = "/" + dialogId + "/conversation";
            req.Callback       = callback;
            req.OnResponse     = ConverseResp;
            req.Forms          = new Dictionary <string, RESTConnector.Form>();
            req.Forms["input"] = new RESTConnector.Form(input);
            if (conversation_id != 0)
            {
                req.Forms["conversation_id"] = new RESTConnector.Form(conversation_id);
            }
            if (client_id != 0)
            {
                req.Forms["client_id"] = new RESTConnector.Form(client_id);
            }

            return(connector.Send(req));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Request an IAM token using an API key.
        /// </summary>
        /// <param name="successCallback">The request callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="customData">Dictionary of custom data.</param>
        /// <returns></returns>
        public bool RequestIamToken(SuccessCallback <IamTokenData> successCallback, FailCallback failCallback, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }

            RESTConnector connector = new RESTConnector();

            connector.URL = _iamUrl;
            if (connector == null)
            {
                return(false);
            }

            RequestIamTokenRequest req = new RequestIamTokenRequest();

            req.SuccessCallback = successCallback;
            req.FailCallback    = failCallback;
            req.Headers.Add("Content-type", "application/x-www-form-urlencoded");
            req.Headers.Add("Authorization", "Basic Yng6Yng=");
            req.OnResponse = OnRequestIamTokenResponse;
            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.Forms = new Dictionary <string, RESTConnector.Form>();
            req.Forms["grant_type"]    = new RESTConnector.Form("urn:ibm:params:oauth:grant-type:apikey");
            req.Forms["apikey"]        = new RESTConnector.Form(_iamApiKey);
            req.Forms["response_type"] = new RESTConnector.Form("cloud_iam");

            return(connector.Send(req));
        }
        /// <summary>
        /// Identifies a language from the given text.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="text">The text sample to ID.</param>
        /// <returns></returns>
        public bool Identify(SuccessCallback <IdentifiedLanguages> successCallback, FailCallback failCallback, string text, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }
            if (string.IsNullOrEmpty(text))
            {
                throw new ArgumentNullException("text");
            }

            RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v2/identify");

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

            IdentifyReq req = new IdentifyReq();

            req.SuccessCallback = successCallback;
            req.FailCallback    = failCallback;
            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.Send = Encoding.UTF8.GetBytes(text);
            req.Headers["Content-Type"] = "text/plain";
            req.Headers["Accept"]       = "application/json";
            req.OnResponse = OnIdentifyResponse;

            return(connector.Send(req));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Train a new classifier.
        /// </summary>
        /// <param name="classifierName">A name to give the classifier.</param>
        /// <param name="language">Language of the classifier.</param>
        /// <param name="trainingData">CSV training data.</param>
        /// <param name="callback">Callback to invoke with the results.</param>
        /// <returns>Returns true if training data was submitted correctly.</returns>
        public bool TrainClassifier(string classifierName, string language, string trainingData, OnTrainClassifier callback)
        {
            if (string.IsNullOrEmpty(classifierName))
            {
                throw new ArgumentNullException("classifierId");
            }
            if (string.IsNullOrEmpty(language))
            {
                throw new ArgumentNullException("language");
            }
            if (string.IsNullOrEmpty(trainingData))
            {
                throw new ArgumentNullException("trainingData");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

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

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

            Dictionary <string, object> trainingMetaData = new Dictionary <string, object>();

            trainingMetaData["language"] = language;
            trainingMetaData["name"]     = classifierName;

            TrainClassifierReq req = new TrainClassifierReq();

            req.Callback   = callback;
            req.OnResponse = OnTrainClassifierResp;
            req.Forms      = new Dictionary <string, RESTConnector.Form>();
            req.Forms["training_metadata"] = new RESTConnector.Form(Encoding.UTF8.GetBytes(Json.Serialize(trainingMetaData)));
            req.Forms["training_data"]     = new RESTConnector.Form(Encoding.UTF8.GetBytes(trainingData));

            return(connector.Send(req));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Deletes the specified model.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="modelId">The model identifier.</param>
        /// <param name="customData">Optional custom data.</param>
        /// <returns>True if the call succeeds, false if the call is unsuccessful.</returns>
        public bool DeleteModel(SuccessCallback <bool> successCallback, FailCallback failCallback, string modelId, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }

            if (string.IsNullOrEmpty(modelId))
            {
                throw new ArgumentNullException("modelId");
            }

            DeleteModelRequest req = new DeleteModelRequest();

            req.SuccessCallback = successCallback;
            req.FailCallback    = failCallback;
            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.Parameters["version"] = NaturalLanguageUnderstandingVersion.Version;
            req.OnResponse            = OnDeleteModelResponse;
            req.Delete = true;

            RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format(ModelEndpoint, modelId));

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

            return(connector.Send(req));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Deletes the specified classifier.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="classifierId">The ID of the classifier.</param>
        /// <returns>Returns false if we failed to submit a request.</returns>
        public bool DeleteClassifer(SuccessCallback <bool> successCallback, FailCallback failCallback, string classifierId, 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("classiferId");
            }

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

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

            DeleteClassifierReq req = new DeleteClassifierReq();

            req.SuccessCallback        = successCallback;
            req.FailCallback           = failCallback;
            req.HttpMethod             = UnityWebRequest.kHttpVerbDELETE;
            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 = OnDeleteClassifierResp;
            req.Headers["X-IBMCloud-SDK-Analytics"] = "service_name=natural_language_classifier;service_version=v1;operation_id=DeleteClassifier";

            return(connector.Send(req));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Message the specified workspaceId, input and callback.
        /// </summary>
        /// <param name="callback">Callback.</param>
        /// <param name="workspaceID">Workspace identifier.</param>
        /// <param name="messageRequest">Message request object.</param>
        /// <param name="customData">Custom data.</param>
        /// <returns></returns>
        public bool Message(OnMessage callback, string workspaceID, MessageRequest messageRequest, string customData = default(string))
        {
            if (string.IsNullOrEmpty(workspaceID))
            {
                throw new ArgumentNullException("workspaceId");
            }
            if (string.IsNullOrEmpty(messageRequest.input.text))
            {
                throw new ArgumentNullException("messageRequest.input.text");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

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

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

            fsData data;

            sm_Serializer.TrySerialize(messageRequest.GetType(), messageRequest, out data).AssertSuccessWithoutWarnings();
            string reqString = fsJsonPrinter.CompressedJson(data);

            MessageReq req = new MessageReq();

            req.Callback                = callback;
            req.MessageRequest          = messageRequest;
            req.Headers["Content-Type"] = "application/json";
            req.Headers["Accept"]       = "application/json";
            req.Parameters["version"]   = Version.VERSION;
            req.Function                = "/" + workspaceID + "/message";
            req.Data       = customData;
            req.Send       = Encoding.UTF8.GetBytes(reqString);
            req.OnResponse = MessageResp;

            return(connector.Send(req));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Register an embodiment with the gateway.
        /// </summary>
        /// <param name="a_GroupId"></param>
        /// <param name="a_OrgId"></param>
        /// <param name="a_BearerToken"></param>
        /// <param name="a_EmbodimentName"></param>
        /// <param name="a_EmbodimentType"></param>
        /// <param name="a_Callback"></param>
        /// <returns></returns>
        public bool RegisterEmbodiment(string a_GroupId,
                                       string a_OrgId,
                                       string a_BearerToken,
                                       string a_EmbodimentName,
                                       string a_EmbodimentType,
                                       OnRegisteredEmbodiment a_Callback)
        {
            RESTConnector connection = RESTConnector.GetConnector(SERVICE_ID, "/v1/auth/registerEmbodiment");

            if (connection == null)
            {
                Log.Error("TopicClient", "RobotGatewayV1 service credentials not found.");
                return(false);
            }

            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers["Content-Type"]  = "application/json";
            headers["Authorization"] = "Bearer " + a_BearerToken;
            headers["groupId"]       = a_GroupId;
            headers["orgId"]         = a_OrgId;
            headers["macId"]         = Utility.MacAddress;

            Dictionary <string, object> json = new Dictionary <string, object>();

            json["embodimentName"]  = a_EmbodimentName;
            json["type"]            = a_EmbodimentType;
            json["groupId"]         = a_GroupId;
            json["orgId"]           = a_OrgId;
            json["macId"]           = Utility.MacAddress;
            json["embodimentToken"] = "token";

            RegisterEmbodimentReq req = new RegisterEmbodimentReq();

            req.Send     = Encoding.UTF8.GetBytes(Json.Serialize(json));
            req.Headers  = headers;
            req.Callback = a_Callback;

            req.OnResponse += OnRegisterEmbodiment;
            return(connection.Send(req));
        }
        /// <summary>
        /// Retrieve the translation models with optional filters.
        /// </summary>
        /// <param name="callback">The callback to invoke with the array of models.</param>
        /// <param name="sourceFilter">Optional source language filter.</param>
        /// <param name="targetFilter">Optional target language filter.</param>
        /// <param name="defaults">Controls if we get default, non-default, or all models.</param>
        /// <returns>Returns a true on success, false if it failed to submit the request.</returns>
        public bool GetModels(GetModelsCallback callback,
                              string sourceFilter = null,
                              string targetFilter = null,
                              TypeFilter defaults = TypeFilter.ALL)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/models");

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

            GetModelsReq req = new GetModelsReq();

            req.Callback   = callback;
            req.OnResponse = GetModelsResponse;

            if (!string.IsNullOrEmpty(sourceFilter))
            {
                req.Parameters["source"] = sourceFilter;
            }
            if (!string.IsNullOrEmpty(targetFilter))
            {
                req.Parameters["target"] = targetFilter;
            }
            if (defaults == TypeFilter.DEFAULT)
            {
                req.Parameters["default"] = "true";
            }
            else if (defaults == TypeFilter.NON_DEFAULT)
            {
                req.Parameters["default"] = "false";
            }

            return(connector.Send(req));
        }
        /// <summary>
        /// Gets the tone analyze.
        /// </summary>
        /// <returns><c>true</c>, if tone analyze was gotten, <c>false</c> otherwise.</returns>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="text">Text.</param>
        /// <param name="data">Data.</param>
        public bool GetToneAnalyze(SuccessCallback <ToneAnalyzerResponse> successCallback, FailCallback failCallback, string text, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }

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

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

            GetToneAnalyzerRequest req = new GetToneAnalyzerRequest();

            req.SuccessCallback = successCallback;
            req.FailCallback    = failCallback;
            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 = GetToneAnalyzerResponse;

            Dictionary <string, string> upload = new Dictionary <string, string>();

            upload["text"] = "\"" + text + "\"";
            req.Send       = Encoding.UTF8.GetBytes(Json.Serialize(upload));
            req.Headers["Content-Type"] = "application/json";
            req.Parameters["version"]   = VersionDate;
            req.Parameters["sentences"] = "true";
            return(connector.Send(req));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Grabs a list of all available dialogs from the service.
        /// </summary>
        /// <param name="callback">The callback to receive the list of dialogs.</param>
        /// <returns>Returns true if request has been sent.</returns>
        public bool GetDialogs(OnGetDialogs callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/dialogs");

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

            GetDialogsReq req = new GetDialogsReq();

            req.Callback   = callback;
            req.OnResponse = OnGetDialogsResp;

            return(connector.Send(req));
        }
Exemplo n.º 14
0
        /// <summary>
        /// This function returns a list to the callback of all identifiable languages.
        /// </summary>
        /// <param name="callback">The callback to invoke with a Language array, null on error.</param>
        /// <returns>Returns true if the request was submitted.</returns>
        public bool GetLanguages(GetLanguagesCallback callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/identifiable_languages");

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

            GetLanguagesReq req = new GetLanguagesReq();

            req.Callback   = callback;
            req.OnResponse = GetLanguagesResponse;

            return(connector.Send(req));
        }
        /// <summary>
        /// Returns an array of all classifiers to the callback function.
        /// </summary>
        /// <param name="callback">The callback to invoke with the Classifiers object.</param>
        /// <returns>Returns true if the request is submitted.</returns>
        public bool GetClassifiers(OnGetClassifiers callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

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

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

            GetClassifiersReq req = new GetClassifiersReq();

            req.Callback   = callback;
            req.OnResponse = OnGetClassifiersResp;

            return(connector.Send(req));
        }
Exemplo n.º 16
0
        /// <summary>
        /// Returns a specific classifer.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="classifierId">The ID of the classifier to get.</param>
        /// <returns>Returns true if the request is submitted.</returns>
        public bool GetClassifier(SuccessCallback <Classifier> successCallback, FailCallback failCallback, string classifierId, 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");
            }

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

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

            GetClassifierReq req = new GetClassifierReq();

            req.SuccessCallback        = successCallback;
            req.FailCallback           = failCallback;
            req.HttpMethod             = UnityWebRequest.kHttpVerbGET;
            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 = OnGetClassifierResp;

            return(connector.Send(req));
        }
        /// <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));
        }
        /// <summary>
        /// Get a specific model by it's ID.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="model_id"></param>
        /// <returns></returns>
        public bool GetModel(SuccessCallback <TranslationModel> successCallback, FailCallback failCallback, string model_id, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }
            if (string.IsNullOrEmpty(model_id))
            {
                throw new ArgumentNullException("model_id");
            }

            RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v2/models/");

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

            GetModelReq req = new GetModelReq();

            req.SuccessCallback = successCallback;
            req.FailCallback    = failCallback;
            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.Function   = WWW.EscapeURL(model_id);
            req.OnResponse = GetModelResponse;

            return(connector.Send(req));
        }
Exemplo n.º 19
0
        /// <summary>
        /// List documents.
        ///
        /// Lists documents that have been submitted for translation.
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <returns><see cref="DocumentList" />DocumentList</returns>
        public bool ListDocuments(Callback <DocumentList> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `ListDocuments`");
            }

            RequestObject <DocumentList> req = new RequestObject <DocumentList>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbGET,
                DisableSslVerification = DisableSslVerification
            };

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

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "ListDocuments"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"] = VersionDate;

            req.OnResponse = OnListDocumentsResponse;

            RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/documents");

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

            return(connector.Send(req));
        }
Exemplo n.º 20
0
        /// <summary>
        /// List models.
        ///
        /// Lists Watson Knowledge Studio [custom entities and relations
        /// models](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing)
        /// that are deployed to your Natural Language Understanding service.
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <returns><see cref="ListModelsResults" />ListModelsResults</returns>
        public bool ListModels(Callback <ListModelsResults> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `ListModels`");
            }

            RequestObject <ListModelsResults> req = new RequestObject <ListModelsResults>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbGET,
                DisableSslVerification = DisableSslVerification
            };

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

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("natural-language-understanding", "V1", "ListModels"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"] = VersionDate;

            req.OnResponse = OnListModelsResponse;

            RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/models", GetServiceUrl());

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

            return(connector.Send(req));
        }
Exemplo n.º 21
0
        /// <summary>
        /// This function POSTs the given audio clip the recognize function and convert speech into text. This function should be used
        /// only on AudioClips under 4MB once they have been converted into WAV format. Use the StartListening() for continuous
        /// recognition of text.
        /// </summary>
        /// <param name="clip">The AudioClip object.</param>
        /// <param name="callback">A callback to invoke with the results.</param>
        /// <returns></returns>
        public bool Recognize(AudioClip clip, OnRecognize callback)
        {
            if (clip == null)
            {
                throw new ArgumentNullException("clip");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/recognize");

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

            RecognizeRequest req = new RecognizeRequest();

            req.Clip     = clip;
            req.Callback = callback;

            req.Headers["Content-Type"] = "audio/wav";
            req.Send = WaveFile.CreateWAV(clip);
            if (req.Send.Length > MAX_RECOGNIZE_CLIP_SIZE)
            {
                Log.Error("SpeechToText", "AudioClip is too large for Recognize().");
                return(false);
            }
            req.Parameters["model"]            = m_RecognizeModel;
            req.Parameters["continuous"]       = "false";
            req.Parameters["max_alternatives"] = m_MaxAlternatives.ToString();
            req.Parameters["timestamps"]       = m_Timestamps ? "true" : "false";
            req.Parameters["word_confidence"]  = m_WordConfidence ? "true" : "false";
            req.OnResponse = OnRecognizeResponse;

            return(connector.Send(req));
        }
Exemplo n.º 22
0
        /// <summary>
        /// This function returns a list to the callback of all identifiable languages.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <returns>Returns true if the request was submitted.</returns>
        public bool GetLanguages(SuccessCallback <Languages> successCallback, FailCallback failCallback, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }

            RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/identifiable_languages");

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

            GetLanguagesReq req = new GetLanguagesReq();

            req.Parameters["version"]  = VersionDate;
            req.SuccessCallback        = successCallback;
            req.FailCallback           = failCallback;
            req.HttpMethod             = UnityWebRequest.kHttpVerbGET;
            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 = GetLanguagesResponse;
            req.Headers["X-IBMCloud-SDK-Analytics"] = "service_name=language_translator;service_version=v3;operation_id=GetLanguages";

            return(connector.Send(req));
        }
Exemplo n.º 23
0
        /// <summary>
        /// Deletes the classifier by classifierID.
        /// </summary>
        /// <returns><c>true</c>, if classifier was deleted, <c>false</c> otherwise.</returns>
        /// <param name="classifierId">Classifier identifier.</param>
        /// <param name="callback">Callback.</param>
        public bool DeleteClassifier(string classifierId, OnDeleteClassifier callback)
        {
            if (string.IsNullOrEmpty(classifierId))
            {
                throw new ArgumentNullException("classifierId");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }
            if (string.IsNullOrEmpty(mp_ApiKey))
            {
                mp_ApiKey = Config.Instance.GetAPIKey(SERVICE_ID);
            }
            if (string.IsNullOrEmpty(mp_ApiKey))
            {
                throw new WatsonException("GetClassifier - VISUAL_RECOGNITION_API_KEY needs to be defined in config.json");
            }

            Log.Debug("VisualRecognition", "Attempting to delete classifier {0}", classifierId);
            RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_CLASSIFIERS + "/" + classifierId);

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

            DeleteClassifierReq req = new DeleteClassifierReq();

            req.Callback = callback;
            req.Timeout  = REQUEST_TIMEOUT;
            req.Parameters["api_key"] = mp_ApiKey;
            req.Parameters["version"] = VisualRecognitionVersion.Version;
            req.OnResponse            = OnDeleteClassifierResp;
            req.Delete = true;

            return(connector.Send(req));
        }
Exemplo n.º 24
0
        /// <summary>
        /// Message the specified workspaceId, input and callback.
        /// </summary>
        /// <param name="workspaceID">Workspace identifier.</param>
        /// <param name="input">Input.</param>
        /// <param name="callback">Callback.</param>
        /// <param name="customData">Custom data.</param>
        public bool Message(OnMessage callback, string workspaceID, string input, string customData = default(string))
        {
            if (string.IsNullOrEmpty(workspaceID))
            {
                throw new ArgumentNullException("workspaceId");
            }
            if (string.IsNullOrEmpty(input))
            {
                throw new ArgumentNullException("input");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

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

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

            string reqJson   = "{{\"input\": {{\"text\": \"{0}\"}}}}";
            string reqString = string.Format(reqJson, input);

            MessageReq req = new MessageReq();

            req.Callback = callback;
            req.Headers["Content-Type"] = "application/json";
            req.Headers["Accept"]       = "application/json";
            req.Parameters["version"]   = Version.VERSION;
            req.Function   = "/" + workspaceID + "/message";
            req.Data       = customData;
            req.Send       = Encoding.UTF8.GetBytes(reqString);
            req.OnResponse = MessageResp;

            return(connector.Send(req));
        }
        /// <summary>
        /// List classifiers.
        ///
        /// Returns an empty array if no classifiers are available.
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <returns><see cref="ClassifierList" />ClassifierList</returns>
        public bool ListClassifiers(Callback <ClassifierList> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `ListClassifiers`");
            }

            RequestObject <ClassifierList> req = new RequestObject <ClassifierList>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbGET,
                DisableSslVerification = DisableSslVerification
            };

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

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("natural_language_classifier", "V1", "ListClassifiers"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }


            req.OnResponse = OnListClassifiersResponse;

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

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

            return(connector.Send(req));
        }
        /// <summary>
        /// Lists available models for Relations and Entities features, including Watson Knowledge Studio
        /// custom models that you have created and linked to your Natural Language Understanding service.
        /// </summary>
        /// <param name="callback">The OnGetModels callback.</param>
        /// <param name="customData">Optional custom data.</param>
        /// <returns>True if the call succeeds, false if the call is unsuccessful.</returns>
        public bool GetModels(OnGetModels callback, string customData = default(string))
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            GetModelsRequest req = new GetModelsRequest();

            req.Callback = callback;
            req.Data     = customData;
            req.Parameters["version"] = NaturalLanguageUnderstandingVersion.Version;
            req.OnResponse            = OnGetModelsResponse;

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

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

            return(connector.Send(req));
        }
Exemplo n.º 27
0
        /// <summary>
        /// This uploads a new dialog to the service.
        /// </summary>
        /// <param name="dialogName">The name of the dialog.</param>
        /// <param name="callback">The callback to receive the dialog ID.</param>
        /// <param name="dialogData">The raw byte data of the dialog.</param>
        /// <param name="dataFileName">This must be the filename including the extension so the dialog service knows how to parse the data.</param>
        /// <returns>Returns true if the upload was submitted.</returns>
        public bool UploadDialog(string dialogName, OnUploadDialog callback, byte[] dialogData, string dataFileName)
        {
            if (string.IsNullOrEmpty(dialogName))
            {
                throw new ArgumentNullException("dialogName");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }
            if (dialogData == null)
            {
                throw new ArgumentNullException("dialogData");
            }
            if (string.IsNullOrEmpty(dataFileName))
            {
                throw new ArgumentNullException("dataFileName");
            }

            RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/dialogs");

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

            UploadDialogReq req = new UploadDialogReq();

            req.Callback      = callback;
            req.OnResponse    = OnCreateDialogResp;
            req.Forms         = new Dictionary <string, RESTConnector.Form>();
            req.Forms["name"] = new RESTConnector.Form(dialogName);
            req.Forms["file"] = new RESTConnector.Form(dialogData, dataFileName);
            req.Timeout       = 10 * 60.0f; // increase timeout to 10 minutes

            return(connector.Send(req));
        }
Exemplo n.º 28
0
        /// <summary>
        /// Create a session.
        ///
        /// Create a new session. A session is used to send user input to a skill and receive responses. It also
        /// maintains the state of the conversation.
        /// </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://console.bluemix.net/docs/services/assistant/create-assistant.html#creating-assistants).
        ///
        /// **Note:** Currently, the v2 API does not support creating assistants.</param>
        /// <returns><see cref="SessionResponse" />SessionResponse</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 CreateSession(SuccessCallback <SessionResponse> successCallback, FailCallback failCallback, String assistantId, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }

            CreateSessionRequestObj req = new CreateSessionRequestObj();

            req.SuccessCallback = successCallback;
            req.FailCallback    = failCallback;
            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.Headers["Content-Type"] = "application/json";
            req.Parameters["version"]   = VersionDate;
            req.OnResponse = OnCreateSessionResponse;
            req.Post       = true;

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

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

            return(connector.Send(req));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Message the specified workspaceId, input and callback.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="workspaceID">Workspace identifier.</param>
        /// <param name="input">Input.</param>
        /// <param name="customData">Custom data.</param>
        public bool Message(SuccessCallback <object> successCallback, FailCallback failCallback, string workspaceID, string input, Dictionary <string, object> customData = null)
        {
            //if (string.IsNullOrEmpty(workspaceID))
            //    throw new ArgumentNullException("workspaceId");
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }

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

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

            string reqJson   = "{{\"input\": {{\"text\": \"{0}\"}}}}";
            string reqString = string.Format(reqJson, input);

            MessageReq req = new MessageReq();

            req.SuccessCallback         = successCallback;
            req.FailCallback            = failCallback;
            req.Headers["Content-Type"] = "application/json";
            req.Headers["Accept"]       = "application/json";
            req.Parameters["version"]   = VersionDate;
            req.Function   = "/" + workspaceID + "/message";
            req.Send       = Encoding.UTF8.GetBytes(reqString);
            req.OnResponse = MessageResp;
            req.CustomData = customData == null ? new Dictionary <string, object>() : customData;

            return(connector.Send(req));
        }
Exemplo n.º 30
0
        /// <summary>
        /// Lists available models for Relations and Entities features, including Watson Knowledge Studio
        /// custom models that you have created and linked to your Natural Language Understanding service.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="customData">Optional custom data.</param>
        /// <returns>True if the call succeeds, false if the call is unsuccessful.</returns>
        public bool GetModels(SuccessCallback <ListModelsResults> successCallback, FailCallback failCallback, Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }

            GetModelsRequest req = new GetModelsRequest();

            req.SuccessCallback        = successCallback;
            req.FailCallback           = failCallback;
            req.HttpMethod             = UnityWebRequest.kHttpVerbGET;
            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.Parameters["version"] = NaturalLanguageUnderstandingVersion.Version;
            req.OnResponse            = OnGetModelsResponse;

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

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

            return(connector.Send(req));
        }