Exemplo n.º 1
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.º 2
0
        /// <summary>
        /// Classifies image specified by URL.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="callback">Callback.</param>
        /// <param name="owners">Owners.</param>
        /// <param name="classifierIDs">Classifier IDs to be classified against.</param>
        /// <param name="threshold">Threshold.</param>
        /// <param name="acceptLanguage">Accept language.</param>
        public bool Classify(string url, OnClassify callback, string[] owners = default(string[]), string[] classifierIDs = default(string[]), float threshold = default(float), string acceptLanguage = "en")
        {
            if (string.IsNullOrEmpty(mp_ApiKey))
            {
                mp_ApiKey = Config.Instance.GetAPIKey(SERVICE_ID);
            }
            if (string.IsNullOrEmpty(mp_ApiKey))
            {
                throw new WatsonException("FindClassifier - VISUAL_RECOGNITION_API_KEY needs to be defined in config.json");
            }
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

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

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

            ClassifyReq req = new ClassifyReq();

            req.Callback       = callback;
            req.OnResponse     = OnClassifyResp;
            req.AcceptLanguage = acceptLanguage;
            req.Headers["Accepted-Language"] = acceptLanguage;
            req.Parameters["api_key"]        = mp_ApiKey;
            req.Parameters["url"]            = url;
            req.Parameters["version"]        = VisualRecognitionVersion.Version;
            if (owners != default(string[]))
            {
                req.Parameters["owners"] = string.Join(",", owners);
            }
            if (classifierIDs != default(string[]))
            {
                req.Parameters["classifier_ids"] = string.Join(",", classifierIDs);
            }
            if (threshold != default(float))
            {
                req.Parameters["threshold"] = threshold;
            }

            return(connector.Send(req));
        }
Exemplo n.º 3
0
        public string Classify(T NewNods)
        {
            List <KeyValuePair <T, float> > TrainedResultDistancePair = new List <KeyValuePair <T, float> >();

            foreach (T Center in TrainedResult)
            {
                float DistanceGet = Center.GetEuclideanDistance(NewNods);
                TrainedResultDistancePair.Add(new KeyValuePair <T, float>(Center, DistanceGet));
            }

            var ShortestGroup    = TrainedResultDistancePair.OrderBy(x => x.Value).Select(x => x.Key);
            var ShortestGroupTag = ShortestGroup.First().Tag;

            OnClassify?.Invoke(NewNods, ShortestGroup, ShortestGroupTag);
            NewNods.Tag = ShortestGroupTag;

            return(ShortestGroupTag);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Classifies a posted image.
        /// </summary>
        /// <param name="callback">Callback.</param>
        /// <param name="imagePath">Image path.</param>
        /// <param name="owners">Owners.</param>
        /// <param name="classifierIDs">Classifier I ds.</param>
        /// <param name="threshold">Threshold.</param>
        /// <param name="acceptLanguage">Accept language.</param>
        public bool Classify(OnClassify callback, string imagePath, string[] owners = default(string[]), string[] classifierIDs = default(string[]), float threshold = default(float), string acceptLanguage = "en")
        {
            if (string.IsNullOrEmpty(mp_ApiKey))
            {
                mp_ApiKey = Config.Instance.GetAPIKey(SERVICE_ID);
            }
            if (string.IsNullOrEmpty(mp_ApiKey))
            {
                throw new WatsonException("FindClassifier - VISUAL_RECOGNITION_API_KEY needs to be defined in config.json");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }
            if (string.IsNullOrEmpty(imagePath))
            {
                throw new ArgumentNullException("Define an image path to classify!");
            }

            byte[] imageData = null;
            if (!string.IsNullOrEmpty(imagePath))
            {
                if (LoadFile != null)
                {
                    imageData = LoadFile(imagePath);
                }
                else
                {
                    #if !UNITY_WEBPLAYER
                    imageData = File.ReadAllBytes(imagePath);
                    #endif
                }

                if (imageData == null)
                {
                    Log.Error("VisualRecognition", "Failed to upload {0}!", imagePath);
                }
            }

            return(Classify(imagePath, imageData, callback, owners, classifierIDs, threshold, acceptLanguage));
        }
Exemplo n.º 5
0
        public KnnClassifyResult Classify(int k, T NewNode)
        {
            List <KeyValuePair <T, float> > NodeDistance = new List <KeyValuePair <T, float> >();

            foreach (var ClassifiedNode in ClassifiedNodes)
            {
                var distance = ClassifiedNode.GetEuclideanDistance(NewNode);

                if (Threshold != null && distance < Threshold)
                {
                    NodeDistance.Add(new KeyValuePair <T, float>(ClassifiedNode, distance));
                }
                else
                {
                    NodeDistance.Add(new KeyValuePair <T, float>(ClassifiedNode, distance));
                }
            }

            var ClosestKPoints = NodeDistance.OrderBy(x => x.Value).Take(k);

            var MostElementsGroup = ClosestKPoints
                                    .GroupBy(node => node.Key.Tag)
                                    .OrderByDescending(group => group.Count())
                                    .First();

            float  confidence = ((float)MostElementsGroup.Count()) / ((float)k);
            string MostTag    = MostElementsGroup.Key;

            NewNode.Tag = MostTag;

            OnClassify?.Invoke(NewNode, ClosestKPoints.Select(x => x.Key), MostTag, ClassifiedNodes);

            return(new KnnClassifyResult()
            {
                Tag = MostTag, Confidence = confidence
            });
        }
        /// <summary>
        /// Classifies the given text, invokes the callback with the results.
        /// </summary>
        /// <param name="classifierId">The ID of the classifier to use.</param>
        /// <param name="text">The text to classify.</param>
        /// <param name="callback">The callback to invoke with the results.</param>
        /// <returns>Returns false if we failed to submit the request.</returns>
        public bool Classify(string classifierId, string text, OnClassify callback)
        {
            if (string.IsNullOrEmpty(classifierId))
            {
                throw new ArgumentNullException("classifierId");
            }
            if (string.IsNullOrEmpty(text))
            {
                throw new ArgumentNullException("text");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

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

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

            ClassifyReq req = new ClassifyReq();

            req.ClassiferId             = classifierId;
            req.Callback                = callback;
            req.OnResponse              = OnClassifyResp;
            req.Function                = "/" + classifierId + "/classify";
            req.Headers["Content-Type"] = "application/json";

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

            body["text"] = text;
            req.Send     = Encoding.UTF8.GetBytes(Json.Serialize(body));

            return(connector.Send(req));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Classifies the given text, invokes the callback with the results.
        /// </summary>
        /// <param name="classifierId">The ID of the classifier to use.</param>
        /// <param name="text">The text to classify.</param>
        /// <param name="callback">The callback to invoke with the results.</param>
        /// <returns>Returns false if we failed to submit the request.</returns>
        public bool Classify(string classifierId, string text, OnClassify callback)
        {
            if (string.IsNullOrEmpty(classifierId))
            {
                throw new ArgumentNullException("classifierId");
            }
            if (string.IsNullOrEmpty(text))
            {
                throw new ArgumentNullException("text");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            string textId = Utility.GetMD5(text);

            if (!DisableCache)
            {
                DataCache cache = null;
                if (!m_ClassifyCache.TryGetValue(classifierId, out cache))
                {
                    cache = new DataCache("NaturalLanguageClassifier_" + classifierId);
                    m_ClassifyCache[classifierId] = cache;
                }

                byte[] cached = cache.Find(textId);
                if (cached != null)
                {
                    ClassifyResult res = ProcessClassifyResult(cached);
                    if (res != null)
                    {
                        callback(res);
                        return(true);
                    }
                }
            }

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

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

            ClassifyReq req = new ClassifyReq();

            req.TextId                  = textId;
            req.ClassiferId             = classifierId;
            req.Callback                = callback;
            req.OnResponse              = OnClassifyResp;
            req.Function                = "/" + classifierId + "/classify";
            req.Headers["Content-Type"] = "application/json";

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

            body["text"] = text;
            req.Send     = Encoding.UTF8.GetBytes(Json.Serialize(body));

            return(connector.Send(req));
        }