/// <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));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Delete a specific model by it's ID.
        /// </summary>
        /// <param name="model_id">The model to delete.</param>
        /// <param name="callback">The DeleteModel callback.</param>
        /// <returns></returns>
        public bool DeleteModel(DeleteModelCallback callback, string model_id)
        {
            if (string.IsNullOrEmpty(model_id))
            {
                throw new ArgumentNullException("model_id");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

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

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

            DeleteModelReq req = new DeleteModelReq();

            req.Callback   = callback;
            req.Function   = WWW.EscapeURL(model_id);
            req.OnResponse = DeleteModelResponse;
            req.Delete     = true;
            return(connector.Send(req));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Identifies a language from the given text.
        /// </summary>
        /// <param name="text">The text sample to ID.</param>
        /// <param name="callback">The callback to receive the results.</param>
        /// <returns></returns>
        public bool Identify(string text, IdentifyCallback callback)
        {
            if (string.IsNullOrEmpty(text))
            {
                throw new ArgumentNullException("text");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

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

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

            IdentifyReq req = new IdentifyReq();

            req.Callback = callback;
            req.Send     = Encoding.UTF8.GetBytes(text);
            req.Headers["Content-Type"] = "text/plain";
            req.OnResponse = OnIdentifyResponse;

            return(connector.Send(req));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Gets a classifier by classifierId.
        /// </summary>
        /// <returns><c>true</c>, if classifier was gotten, <c>false</c> otherwise.</returns>
        /// <param name="classifierId">Classifier identifier.</param>
        /// <param name="callback">Callback.</param>
        public bool GetClassifier(string classifierId, OnGetClassifier 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");
            }

            RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_CLASSIFIERS + "/" + classifierId);

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

            GetClassifierReq req = new GetClassifierReq();

            req.Callback = callback;
            req.Parameters["api_key"] = mp_ApiKey;
            req.Parameters["version"] = VisualRecognitionVersion.Version;
            req.OnResponse            = OnGetClassifierResp;

            return(connector.Send(req));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Deletes a dialog by ID.
        /// </summary>
        /// <param name="dialogId">The ID of the dialog to delete.</param>
        /// <param name="callback">The callback to invoke on success or failure.</param>
        /// <returns>Returns true if request is sent.</returns>
        public bool DeleteDialog(string dialogId, OnDialogCallback callback)
        {
            if (string.IsNullOrEmpty(dialogId))
            {
                throw new ArgumentNullException("dialogId");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

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

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

            DeleteDialogReq req = new DeleteDialogReq();

            req.Callback   = callback;
            req.OnResponse = OnDeleteDialogResp;
            req.Delete     = true;

            return(connector.Send(req));
        }
Exemplo n.º 6
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.CustomData      = customData == null ? new Dictionary <string, object>() : customData;
            req.OnResponse      = OnDeleteClassifierResp;
            req.Delete          = true;

            return(connector.Send(req));
        }
Exemplo n.º 7
0
        /// <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));
        }
        /// <summary>
        /// Classify images.
        ///
        /// Classify images with built-in or custom classifiers.
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <param name="imagesFile">An image file (.gif, .jpg, .png, .tif) or .zip file with images. Maximum image size
        /// is 10 MB. Include no more than 20 images and limit the .zip file to 100 MB. Encode the image and .zip file
        /// names in UTF-8 if they contain non-ASCII characters. The service assumes UTF-8 encoding if it encounters
        /// non-ASCII characters.
        ///
        /// You can also include an image with the **url** parameter. (optional)</param>
        /// <param name="imagesFilename">The filename for imagesFile. (optional)</param>
        /// <param name="imagesFileContentType">The content type of imagesFile. (optional)</param>
        /// <param name="url">The URL of an image (.gif, .jpg, .png, .tif) to analyze. The minimum recommended pixel
        /// density is 32X32 pixels, but the service tends to perform better with images that are at least 224 x 224
        /// pixels. The maximum image size is 10 MB.
        ///
        /// You can also include images with the **images_file** parameter. (optional)</param>
        /// <param name="threshold">The minimum score a class must have to be displayed in the response. Set the
        /// threshold to `0.0` to return all identified classes. (optional)</param>
        /// <param name="owners">The categories of classifiers to apply. The **classifier_ids** parameter overrides
        /// **owners**, so make sure that **classifier_ids** is empty.
        /// - Use `IBM` to classify against the `default` general classifier. You get the same result if both
        /// **classifier_ids** and **owners** parameters are empty.
        /// - Use `me` to classify against all your custom classifiers. However, for better performance use
        /// **classifier_ids** to specify the specific custom classifiers to apply.
        /// - Use both `IBM` and `me` to analyze the image against both classifier categories. (optional)</param>
        /// <param name="classifierIds">Which classifiers to apply. Overrides the **owners** parameter. You can specify
        /// both custom and built-in classifier IDs. The built-in `default` classifier is used if both
        /// **classifier_ids** and **owners** parameters are empty.
        ///
        /// The following built-in classifier IDs require no training:
        /// - `default`: Returns classes from thousands of general tags.
        /// - `food`: Enhances specificity and accuracy for images of food items.
        /// - `explicit`: Evaluates whether the image might be pornographic. (optional)</param>
        /// <param name="acceptLanguage">The desired language of parts of the response. See the response for details.
        /// (optional, default to en)</param>
        /// <returns><see cref="ClassifiedImages" />ClassifiedImages</returns>
        public bool Classify(Callback <ClassifiedImages> callback, System.IO.MemoryStream imagesFile = null, string imagesFilename = null, string imagesFileContentType = null, string url = null, float?threshold = null, List <string> owners = null, List <string> classifierIds = null, string acceptLanguage = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `Classify`");
            }

            RequestObject <ClassifiedImages> req = new RequestObject <ClassifiedImages>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbPOST,
                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("watson_vision_combined", "V3", "Classify"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"] = VersionDate;
            req.Forms = new Dictionary <string, RESTConnector.Form>();
            if (imagesFile != null)
            {
                req.Forms["images_file"] = new RESTConnector.Form(imagesFile, imagesFilename, imagesFileContentType);
            }
            if (!string.IsNullOrEmpty(url))
            {
                req.Forms["url"] = new RESTConnector.Form(url);
            }
            if (threshold != null)
            {
                req.Forms["threshold"] = new RESTConnector.Form(threshold.ToString());
            }
            if (owners != null && owners.Count > 0)
            {
                req.Forms["owners"] = new RESTConnector.Form(string.Join(", ", owners.ToArray()));
            }
            if (classifierIds != null && classifierIds.Count > 0)
            {
                req.Forms["classifier_ids"] = new RESTConnector.Form(string.Join(", ", classifierIds.ToArray()));
            }

            req.OnResponse = OnClassifyResponse;

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

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

            return(connector.Send(req));
        }
Exemplo n.º 9
0
        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;
            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.º 10
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>
        public bool Message(string workspaceId, string input, OnMessage callback)
        {
            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, "/v2/rest/workspaces");

            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.Function   = "/" + workspaceId + "/message";
            req.Send       = Encoding.UTF8.GetBytes(reqString);
            req.OnResponse = MessageResp;

            return(connector.Send(req));
        }
        private bool RequestToken(Callback <CloudPakForDataTokenResponse> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("successCallback");
            }

            RESTConnector connector = new RESTConnector();

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

            RequestCloudPakForDataTokenRequest req = new RequestCloudPakForDataTokenRequest();

            req.HttpMethod = UnityWebRequest.kHttpVerbGET;
            req.Callback   = callback;
            req.Headers.Add("Content-type", "application/x-www-form-urlencoded");
            req.Headers.Add("Authorization", Utility.CreateAuthorization(Username, Password));
            req.OnResponse             = OnRequestCloudPakForDataTokenResponse;
            req.DisableSslVerification = DisableSslVerification;
            return(connector.Send(req));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Deletes the specified classifier.
        /// </summary>
        /// <param name="classifierId">The ID of the classifier.</param>
        /// <param name="callback">The callback to invoke with the results.</param>
        /// <returns>Returns false if we failed to submit a request.</returns>
        public bool DeleteClassifer(string classifierId, OnDeleteClassifier callback)
        {
            if (string.IsNullOrEmpty(classifierId))
            {
                throw new ArgumentNullException("classiferId");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

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

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

            DeleteClassifierReq req = new DeleteClassifierReq();

            req.Callback   = callback;
            req.OnResponse = OnDeleteClassifierResp;
            req.Delete     = true;

            return(connector.Send(req));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Retrieve the translation models with optional filters.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</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(SuccessCallback <TranslationModels> successCallback,
                              FailCallback failCallback,
                              string sourceFilter = null,
                              string targetFilter = null,
                              TypeFilter defaults = TypeFilter.ALL,
                              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/models");

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

            GetModelsReq req = new GetModelsReq();

            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 = GetModelsResponse;
            req.Headers["X-IBMCloud-SDK-Analytics"] = "service_name=language_translator;service_version=v3;operation_id=GetModels";

            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>
        /// Deletes the specified model.
        /// </summary>
        /// <param name="callback">The 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(OnDeleteModel callback, string modelId, string customData = default(string))
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

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

            DeleteModelRequest req = new DeleteModelRequest();

            req.Callback = callback;
            req.ModelId  = modelId;
            req.Data     = customData;
            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.º 15
0
        /// <summary>
        /// Request an IAM token using an API key.
        /// </summary>
        /// <param name="callback">The request callback.</param>
        /// <param name="error"> The request error.</param>
        /// <returns></returns>
        override protected bool RequestToken(Callback <TokenData> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("successCallback");
            }

            RESTConnector connector = new RESTConnector();

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

            RequestIamTokenRequest req = new RequestIamTokenRequest();

            req.Callback   = callback;
            req.HttpMethod = UnityWebRequest.kHttpVerbGET;
            req.Headers.Add("Content-type", "application/x-www-form-urlencoded");
            req.Headers.Add("Authorization", Utility.CreateAuthorization(iamClientId, iamClientSecret));
            req.OnResponse             = OnRequestIamTokenResponse;
            req.DisableSslVerification = disableSslVerification;
            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));
        }
Exemplo n.º 16
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, "/v2/models/");

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

            DeleteModelReq req = new DeleteModelReq();

            req.SuccessCallback = successCallback;
            req.FailCallback    = failCallback;
            req.CustomData      = customData == null ? new Dictionary <string, object>() : customData;
            req.Function        = WWW.EscapeURL(model_id);
            req.OnResponse      = DeleteModelResponse;
            req.Delete          = true;
            return(connector.Send(req));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Returns an array of all classifiers to the callback function.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <returns>Returns true if the request is submitted.</returns>
        public bool GetClassifiers(SuccessCallback <Classifiers> 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, "/v1/classifiers");

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

            GetClassifiersReq req = new GetClassifiersReq();

            req.SuccessCallback = successCallback;
            req.FailCallback    = failCallback;
            req.CustomData      = customData == null ? new Dictionary <string, object>() : customData;
            req.OnResponse      = OnGetClassifiersResp;

            return(connector.Send(req));
        }
Exemplo n.º 18
0
        /// <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;
            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.º 19
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.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));
        }
Exemplo n.º 20
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));
        }
Exemplo n.º 21
0
        private bool Classify(string imagePath, byte[] imageData, OnClassify callback, string[] owners = default(string[]), string[] classifierIDs = default(string[]), float threshold = default(float), string acceptLanguage = "en")
        {
            RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_CLASSIFY);

            if (connector == null)
            {
                return(false);
            }
            ClassifyReq req = new ClassifyReq();

            req.Callback                   = callback;
            req.Timeout                    = REQUEST_TIMEOUT;
            req.OnResponse                 = OnClassifyResp;
            req.AcceptLanguage             = acceptLanguage;
            req.Parameters["api_key"]      = mp_ApiKey;
            req.Parameters["version"]      = VisualRecognitionVersion.Version;
            req.Headers["Content-Type"]    = "application/x-www-form-urlencoded";
            req.Headers["Accept-Language"] = acceptLanguage;

            if (imageData != null)
            {
                req.Send = imageData;
            }

            return(connector.Send(req));
        }
Exemplo n.º 22
0
        /// <summary>
        /// Refresh an IAM token using a refresh token.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="customData">Dictionary of custom data.</param>
        /// <returns></returns>
        public bool RefreshIamToken(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;

            RefreshIamTokenRequest req = new RefreshIamTokenRequest();
            req.SuccessCallback = successCallback;
            req.FailCallback = failCallback;
            req.Headers.Add("Content-type", "application/x-www-form-urlencoded");
            req.Headers.Add("Authorization", "Basic Yng6Yng=");
            req.OnResponse = OnRefreshIamTokenResponse;
            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("refresh_token");
            req.Forms["refresh_token"] = new RESTConnector.Form(_iamTokenData.RefreshToken);

            return connector.Send(req);
        }
Exemplo n.º 23
0
        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));
        }
Exemplo n.º 24
0
        /// <summary>
        /// Gets the tone analyze.
        /// </summary>
        /// <returns><c>true</c>, if tone analyze was gotten, <c>false</c> otherwise.</returns>
        /// <param name="callback">Callback.</param>
        /// <param name="text">Text.</param>
        /// <param name="data">Data.</param>
        public bool GetToneAnalyze(OnGetToneAnalyzed callback, string text, string data = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

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

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

            GetToneAnalyzerRequest req = new GetToneAnalyzerRequest();

            req.Callback   = callback;
            req.OnResponse = GetToneAnalyzerResponse;

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

            upload["text"] = "\"" + text + "\"";
            req.Send       = Encoding.UTF8.GetBytes(Json.Serialize(upload));
            req.Data       = data;
            req.Headers["Content-Type"] = "application/json";
            req.Parameters["version"]   = VersionDate;
            req.Parameters["sentences"] = "true";
            return(connector.Send(req));
        }
Exemplo n.º 25
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 = new RESTConnector();

            connector.URL = "http://aiaas.pandorabots.com/talk/1409612821373/rosie?user_key=ce95ff63dbe2ece138f3ffec7695db2b";
            if (connector == null)
            {
                return(false);
            }

            ConverseReq req = new ConverseReq();

            req.Callback       = callback;
            req.OnResponse     = ConverseResp;
            req.Forms          = new Dictionary <string, RESTConnector.Form>();
            req.Forms["input"] = new RESTConnector.Form(input);
            return(connector.Send(req));
        }
        /// <summary>
        /// Returns an array of all classifiers to the callback function.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <returns>Returns true if the request is submitted.</returns>
        public bool GetClassifiers(SuccessCallback <Classifiers> 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, "/v1/classifiers");

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

            GetClassifiersReq req = new GetClassifiersReq();

            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 = OnGetClassifiersResp;

            return(connector.Send(req));
        }
Exemplo n.º 27
0
        /// <summary>
        /// Get a specific model by it's ID.
        /// </summary>
        /// <param name="model_id"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public bool GetModel(string model_id, GetModelCallback callback)
        {
            if (string.IsNullOrEmpty(model_id))
            {
                throw new ArgumentNullException("model_id");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

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

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

            GetModelReq req = new GetModelReq();

            req.Callback   = callback;
            req.Function   = WWW.EscapeURL(model_id);
            req.OnResponse = GetModelResponse;

            return(connector.Send(req));
        }
Exemplo n.º 28
0
        /// <summary>
        /// Refresh an IAM token using a refresh token.
        /// </summary>
        /// <param name="callback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <returns></returns>
        public bool RefreshIamToken(Callback <IamTokenData> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            RESTConnector connector = new RESTConnector();

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

            RefreshIamTokenRequest req = new RefreshIamTokenRequest();

            req.Callback   = callback;
            req.HttpMethod = UnityWebRequest.kHttpVerbGET;
            req.Headers.Add("Content-type", "application/x-www-form-urlencoded");
            req.Headers.Add("Authorization", "Basic Yng6Yng=");
            req.OnResponse             = OnRefreshIamTokenResponse;
            req.DisableSslVerification = DisableSslVerification;
            req.Forms = new Dictionary <string, RESTConnector.Form>();
            req.Forms["grant_type"]    = new RESTConnector.Form("refresh_token");
            req.Forms["refresh_token"] = new RESTConnector.Form(_iamTokenData.RefreshToken);

            return(connector.Send(req));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Create model.
        ///
        /// Uploads Translation Memory eXchange (TMX) files to customize a translation model.
        ///
        /// You can either customize a model with a forced glossary or with a corpus that contains parallel sentences.
        /// To create a model that is customized with a parallel corpus <b>and</b> a forced glossary, proceed in two
        /// steps: customize with a parallel corpus first and then customize the resulting model with a glossary.
        /// Depending on the type of customization and the size of the uploaded corpora, training can range from minutes
        /// for a glossary to several hours for a large parallel corpus. You can upload a single forced glossary file
        /// and this file must be less than <b>10 MB</b>. You can upload multiple parallel corpora tmx files. The
        /// cumulative file size of all uploaded files is limited to <b>250 MB</b>. To successfully train with a
        /// parallel corpus you must have at least <b>5,000 parallel sentences</b> in your corpus.
        ///
        /// You can have a <b>maximum of 10 custom models per language pair</b>.
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <param name="baseModelId">The model ID of the model to use as the base for customization. To see available
        /// models, use the `List models` method. Usually all IBM provided models are customizable. In addition, all
        /// your models that have been created via parallel corpus customization, can be further customized with a
        /// forced glossary.</param>
        /// <param name="forcedGlossary">A TMX file with your customizations. The customizations in the file completely
        /// overwrite the domain translaton data, including high frequency or high confidence phrase translations. You
        /// can upload only one glossary with a file size less than 10 MB per call. A forced glossary should contain
        /// single words or short phrases. (optional)</param>
        /// <param name="parallelCorpus">A TMX file with parallel sentences for source and target language. You can
        /// upload multiple parallel_corpus files in one request. All uploaded parallel_corpus files combined, your
        /// parallel corpus must contain at least 5,000 parallel sentences to train successfully. (optional)</param>
        /// <param name="name">An optional model name that you can use to identify the model. Valid characters are
        /// letters, numbers, dashes, underscores, spaces and apostrophes. The maximum length is 32 characters.
        /// (optional)</param>
        /// <returns><see cref="TranslationModel" />TranslationModel</returns>
        public bool CreateModel(Callback <TranslationModel> callback, string baseModelId, System.IO.MemoryStream forcedGlossary = null, System.IO.MemoryStream parallelCorpus = null, string name = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `CreateModel`");
            }
            if (string.IsNullOrEmpty(baseModelId))
            {
                throw new ArgumentNullException("`baseModelId` is required for `CreateModel`");
            }

            RequestObject <TranslationModel> req = new RequestObject <TranslationModel>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbPOST,
                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", "CreateModel"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"] = VersionDate;
            req.Forms = new Dictionary <string, RESTConnector.Form>();
            if (forcedGlossary != null)
            {
                req.Forms["forced_glossary"] = new RESTConnector.Form(forcedGlossary, "filename", "application/octet-stream");
            }
            if (parallelCorpus != null)
            {
                req.Forms["parallel_corpus"] = new RESTConnector.Form(parallelCorpus, "filename", "application/octet-stream");
            }
            if (!string.IsNullOrEmpty(baseModelId))
            {
                req.Parameters["base_model_id"] = baseModelId;
            }
            if (!string.IsNullOrEmpty(name))
            {
                req.Parameters["name"] = name;
            }

            req.OnResponse = OnCreateModelResponse;

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

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

            return(connector.Send(req));
        }
        /// <summary>
        /// Returns a specific classifer.
        /// </summary>
        /// <param name="classifierId">The ID of the classifier to get.</param>
        /// <param name="callback">The callback to invoke with the Classifier object.</param>
        /// <returns>Returns true if the request is submitted.</returns>
        public bool GetClassifier(string classifierId, OnGetClassifier callback)
        {
            if (string.IsNullOrEmpty(classifierId))
            {
                throw new ArgumentNullException("classifierId");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

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

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

            GetClassifierReq req = new GetClassifierReq();

            req.Callback   = callback;
            req.OnResponse = OnGetClassifierResp;

            return(connector.Send(req));
        }