Esempio n. 1
0
        public void DetectWhenMultipleQsTest()
        {
            var request = new DetectRequest
            {
                Key = this.ApiKey,
                Qs  = new[] { "Hello World", "Der var engang" }
            };

            var result = GoogleTranslate.Detect.Query(request);

            Assert.IsNotNull(result);
            Assert.AreEqual(Status.Ok, result.Status);

            var detections = result.Data.Detections?.ToArray();

            Assert.IsNotNull(detections);
            Assert.IsNotEmpty(detections);
            Assert.AreEqual(2, detections.Length);

            var detection1 = detections[0];

            Assert.IsNotNull(detection1);
            Assert.AreEqual(Language.English, detection1[0].Language);

            var detection2 = detections[1];

            Assert.IsNotNull(detection2);
            Assert.AreEqual(Language.Danish, detection2[0].Language);
        }
Esempio n. 2
0
        public void ConstructorDefaultTest()
        {
            var request = new DetectRequest();

            Assert.IsTrue(request.IsSsl);
            Assert.IsNull(request.Qs);
        }
Esempio n. 3
0
        public async Task DetectLastPointAnomaly()
        {
            //read endpoint and apiKey
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            var endpointUri = new Uri(endpoint);
            var credential  = new AzureKeyCredential(apiKey);

            //create client
            AnomalyDetectorClient client = new AnomalyDetectorClient(endpointUri, credential);

            //read data
            string datapath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "samples", "data", "request-data.csv");

            List <TimeSeriesPoint> list = File.ReadAllLines(datapath, Encoding.UTF8)
                                          .Where(e => e.Trim().Length != 0)
                                          .Select(e => e.Split(','))
                                          .Where(e => e.Length == 2)
                                          .Select(e => new TimeSeriesPoint(float.Parse(e[1]))
            {
                Timestamp = DateTime.Parse(e[0])
            }).ToList();

            //create request
            DetectRequest request = new DetectRequest(list)
            {
                Granularity = TimeGranularity.Daily
            };

            #region Snippet:DetectLastPointAnomaly

            //detect
            Console.WriteLine("Detecting the anomaly status of the latest point in the series.");

            try
            {
                LastDetectResponse result = await client.DetectLastPointAsync(request).ConfigureAwait(false);

                if (result.IsAnomaly)
                {
                    Console.WriteLine("The latest point was detected as an anomaly.");
                }
                else
                {
                    Console.WriteLine("The latest point was not detected as an anomaly.");
                }
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine(String.Format("Last detection failed: {0}", ex.Message));
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Detection error. {0}", ex.Message));
                throw;
            }
            #endregion
        }
        public IHttpActionResult CreateRequest(DetectRequest request)
        {
            // set up process start info
            var startInfo = new ProcessStartInfo();

            startInfo.WorkingDirectory = System.Web.Hosting.HostingEnvironment.MapPath("~/Python");
            startInfo.FileName         = "C:/Python27/python.exe";
            string cmd  = "read_video.py";
            string args = "\"" + request.VidUrl + "\" ";

            foreach (string path in request.TemplateUrls)
            {
                string pathFormat = "\"" + path + "\" ";
                args += pathFormat;
            }
            startInfo.Arguments = string.Format("{0} {1}", cmd, args);

            // launch process
            Process process = Process.Start(startInfo);

            // wait for process exit
            process?.WaitForExit();

            return(Ok());
        }
Esempio n. 5
0
        public void GetQueryStringParametersTest()
        {
            var request = new DetectRequest
            {
                Key = "key",
                Qs  = new[]
                {
                    "qs"
                }
            };

            var queryStringParameters = request.GetQueryStringParameters();

            Assert.IsNotNull(queryStringParameters);

            var key         = queryStringParameters.FirstOrDefault(x => x.Key == "key");
            var keyExpected = request.Key;

            Assert.IsNotNull(key);
            Assert.AreEqual(keyExpected, key.Value);

            var qs         = queryStringParameters.FirstOrDefault(x => x.Key == "q");
            var qsExpected = request.Qs.First();

            Assert.IsNotNull(qs);
            Assert.AreEqual(qsExpected, qs.Value);
        }
Esempio n. 6
0
        public async Task DetectEntireSeriesAnomaly()
        {
            #region Snippet:CreateAnomalyDetectorClient

            //read endpoint and apiKey
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            var endpointUri = new Uri(endpoint);
            var credential  = new AzureKeyCredential(apiKey);

            //create client
            AnomalyDetectorClient client = new AnomalyDetectorClient(endpointUri, credential);

            //read data
            string datapath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "samples", "data", "request-data.csv");

            #endregion

            #region Snippet:ReadSeriesData

            List <TimeSeriesPoint> list = File.ReadAllLines(datapath, Encoding.UTF8)
                                          .Where(e => e.Trim().Length != 0)
                                          .Select(e => e.Split(','))
                                          .Where(e => e.Length == 2)
                                          .Select(e => new TimeSeriesPoint(DateTime.Parse(e[0]), float.Parse(e[1]))).ToList();

            //create request
            DetectRequest request = new DetectRequest(list, TimeGranularity.Daily);

            #endregion

            #region Snippet:DetectEntireSeriesAnomaly

            //detect
            Console.WriteLine("Detecting anomalies in the entire time series.");

            EntireDetectResponse result = await client.DetectEntireSeriesAsync(request).ConfigureAwait(false);

            if (result.IsAnomaly.Contains(true))
            {
                Console.WriteLine("An anomaly was detected at index:");
                for (int i = 0; i < request.Series.Count; ++i)
                {
                    if (result.IsAnomaly[i])
                    {
                        Console.Write(i);
                        Console.Write(" ");
                    }
                }
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine(" No anomalies detected in the series.");
            }

            #endregion
        }
Esempio n. 7
0
 private void AddKey(string key, string value)
 {
     key = key.ToLower();
     if (DetectRequest.ContainsKey(key))
     {
         DetectRequest.Remove(key);
     }
     DetectRequest.Add(key, value);
 }
        private static void Main(string[] args)
        {
            var apiBasePath = Environment.GetEnvironmentVariable(API_BASE_PATH) ?? "https://test-faceapi.regulaforensics.com";

            var face1 = File.ReadAllBytes("resources/face_1.jpg");
            var face2 = File.ReadAllBytes("resources/face_2.jpg");

            var sdk = new FaceSdk(apiBasePath);

            var matchImage1 = new MatchImage(data: face1, type: ImageSource.LIVE);
            var matchImage2 = new MatchImage(data: face1, type: ImageSource.DOCUMENT_RFID);
            var matchImage3 = new MatchImage(data: face2, type: ImageSource.LIVE);

            var matchingRequest = new MatchRequest(
                false, new List <MatchImage> {
                matchImage1, matchImage2, matchImage3
            }
                );

            var matchingResponse = sdk.MatchingApi.Match(matchingRequest);

            Console.WriteLine("-----------------------------------------------------------------");
            Console.WriteLine("                         Matching Results                         ");
            Console.WriteLine("-----------------------------------------------------------------");

            foreach (var comparison in matchingResponse.Results)
            {
                Console.WriteLine("pair({0}, {1}) similarity: {2}",
                                  comparison.FirstIndex, comparison.SecondIndex, comparison.Similarity);
            }

            var detectRequest  = new DetectRequest(face2);
            var detectResponse = sdk.MatchingApi.Detect(detectRequest);
            var detectResults  = detectResponse.Results;

            Console.WriteLine("-----------------------------------------------------------------");
            Console.WriteLine("                         Detect Results                          ");
            Console.WriteLine("-----------------------------------------------------------------");

            Console.WriteLine("detectorType: {0}", detectResults.DetectorType);
            Console.WriteLine("landmarkType: {0}", detectResults.LandmarksType);
            foreach (var detection in detectResults.Detections)
            {
                Console.WriteLine("landmarks: [{0}]",
                                  string.Join(", ", detection.Landmarks.Select(landmark =>
                                                                               $"[{string.Join(", ", landmark)}]").ToList()));

                Console.WriteLine("roi: [{0}]", string.Join(", ", detection.Roi.ToArray()));
                Console.WriteLine("attributes: {0}",
                                  string.IsNullOrEmpty(detection.Attributes?.ToString()) ? "null" : detection.Attributes.ToString());
            }

            Console.WriteLine("-----------------------------------------------------------------");
        }
Esempio n. 9
0
        public void DetectWhenQsIsEmptyTest()
        {
            var request = new DetectRequest
            {
                Key = this.ApiKey,
                Qs  = new string[0]
            };

            var exception = Assert.Throws <ArgumentException>(() => GoogleTranslate.Detect.Query(request));

            Assert.AreEqual(exception.Message, "Qs is required");
        }
Esempio n. 10
0
        public void DetectWhenKeyIsStringEmptyTest()
        {
            var request = new DetectRequest
            {
                Key = string.Empty,
                Qs  = new[] { "Hej Verden" }
            };

            var exception = Assert.Throws <ArgumentException>(() => GoogleTranslate.Detect.Query(request));

            Assert.AreEqual(exception.Message, "Key is required");
        }
Esempio n. 11
0
        public void GetQueryStringParametersTest()
        {
            var request = new DetectRequest
            {
                Key = "abc",
                Qs  = new[]
                {
                    "abc"
                }
            };

            Assert.DoesNotThrow(() => request.GetQueryStringParameters());
        }
Esempio n. 12
0
        public void DetectWhenAsyncTest()
        {
            var request = new DetectRequest
            {
                Key = this.ApiKey,
                Qs  = new[] { "Hello World" }
            };

            var result = GoogleTranslate.Detect.QueryAsync(request).Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(Status.Ok, result.Status);
        }
 public virtual Response <LastDetectResponse> DetectLastPoint(DetectRequest body, CancellationToken cancellationToken = default)
 {
     using var scope = _clientDiagnostics.CreateScope("AnomalyDetectorClient.DetectLastPoint");
     scope.Start();
     try
     {
         return(RestClient.DetectLastPoint(body, cancellationToken));
     }
     catch (Exception e)
     {
         scope.Failed(e);
         throw;
     }
 }
Esempio n. 14
0
        public void GetQueryStringParametersWhenKeyIsStringEmptyTest()
        {
            var request = new DetectRequest
            {
                Key = string.Empty
            };

            var exception = Assert.Throws <ArgumentException>(() =>
            {
                var parameters = request.GetQueryStringParameters();
                Assert.IsNull(parameters);
            });

            Assert.AreEqual(exception.Message, "'Key' is required");
        }
Esempio n. 15
0
        public void GetQueryStringParametersWhenQsIsNullTest()
        {
            var request = new DetectRequest
            {
                Key = "abc",
                Qs  = null
            };

            var exception = Assert.Throws <ArgumentException>(() =>
            {
                var parameters = request.GetQueryStringParameters();
                Assert.IsNull(parameters);
            });

            Assert.AreEqual(exception.Message, "'Qs' is required");
        }
Esempio n. 16
0
        public void GetQueryStringParametersWhenKeyIsNullTest()
        {
            var request = new DetectRequest
            {
                Key = null,
                Qs  = new[] { "Hej Verden" }
            };

            var exception = Assert.Throws <ArgumentException>(() =>
            {
                var parameters = request.GetQueryStringParameters();
                Assert.IsNull(parameters);
            });

            Assert.AreEqual(exception.Message, "Key is required");
        }
Esempio n. 17
0
        public void GetQueryStringParametersWhenQsIsEmptyTest()
        {
            var request = new DetectRequest
            {
                Key = this.ApiKey,
                Qs  = new string[0]
            };

            var exception = Assert.Throws <ArgumentException>(() =>
            {
                var parameters = request.GetQueryStringParameters();
                Assert.IsNull(parameters);
            });

            Assert.AreEqual(exception.Message, "Qs is required");
        }
Esempio n. 18
0
        public void GetUriTest()
        {
            var request = new DetectRequest
            {
                Key = "abc",
                Qs  = new[]
                {
                    "abc",
                    "def"
                }
            };

            var uri = request.GetUri();

            Assert.IsNotNull(uri);
            Assert.AreEqual($"/language/translate/v2/detect?key={request.Key}&q={request.Qs.First()}&q={request.Qs.Last()}", uri.PathAndQuery);
        }
Esempio n. 19
0
        public void DetectWhenKeyIsStringEmptyTest()
        {
            var request = new DetectRequest
            {
                Key = string.Empty,
                Qs  = new[] { "Hej Verden" }
            };

            var exception = Assert.Throws <AggregateException>(() => GoogleTranslate.Detect.QueryAsync(request).Wait());

            Assert.IsNotNull(exception);

            var innerException = exception.InnerException;

            Assert.IsNotNull(innerException);
            Assert.AreEqual(typeof(GoogleApiException), innerException.GetType());
            Assert.AreEqual(innerException.Message, "Key is required");
        }
Esempio n. 20
0
        public void DetectWhenQsIsEmptyTest()
        {
            var request = new DetectRequest
            {
                Key = this.ApiKey,
                Qs  = new string[0]
            };

            var exception = Assert.Throws <AggregateException>(() => GoogleTranslate.Detect.QueryAsync(request).Wait());

            Assert.IsNotNull(exception);

            var innerException = exception.InnerException;

            Assert.IsNotNull(innerException);
            Assert.AreEqual(typeof(GoogleApiException), innerException.GetType());
            Assert.AreEqual(innerException.Message, "Qs is required");
        }
Esempio n. 21
0
        public void DetectWhenAsyncAndCancelledTest()
        {
            var request = new DetectRequest
            {
                Key = this.ApiKey,
                Qs  = new[] { "Hello World" }
            };

            var cancellationTokenSource = new CancellationTokenSource();
            var task = GoogleTranslate.Detect.QueryAsync(request, cancellationTokenSource.Token);

            cancellationTokenSource.Cancel();

            var exception = Assert.Throws <OperationCanceledException>(() => task.Wait(cancellationTokenSource.Token));

            Assert.IsNotNull(exception);
            Assert.AreEqual(exception.Message, "The operation was canceled.");
        }
Esempio n. 22
0
        public void DetectWhenQsIsNullTest()
        {
            var request = new DetectRequest
            {
                Key = this.ApiKey,
                Qs  = null
            };

            var exception = Assert.Throws <AggregateException>(() => GoogleTranslate.Detect.Query(request));

            Assert.IsNotNull(exception);
            Assert.AreEqual("One or more errors occurred.", exception.Message);

            var innerException = exception.InnerException;

            Assert.IsNotNull(innerException);
            Assert.AreEqual(typeof(GoogleApiException), innerException.GetType());
            Assert.AreEqual(innerException.Message, "Qs is required");
        }
Esempio n. 23
0
        public bool Detect(int times)
        {
            if (null == client)
            {
                return(false);
            }


            DetectRequest msg = new DetectRequest()
            {
                DetectMsg = new Detect {
                    SN = 0xffffffff
                },
            };

            for (int i = 0; i < times; i++)
            {
                detectAck = false;
                detectWaitHandle.Reset();
                if (client.Send(msg) > 0)
                {
                    if (detectWaitHandle.WaitOne(2000))
                    {
                        if (detectAck)
                        {
                            return(true);
                        }
                        else
                        {
                            Thread.Sleep(1000);
                            continue;
                        }
                    }
                    else
                    {
                        Thread.Sleep(1000);
                        continue;
                    }
                }
                return(false);
            }
            return(false);
        }
Esempio n. 24
0
        public void DetectWhenInvalidKeyTest()
        {
            var request = new DetectRequest
            {
                Key = "test",
                Qs  = new[] { "Hello World" }
            };

            var exception = Assert.Throws <AggregateException>(() => GoogleTranslate.Detect.Query(request));

            Assert.IsNotNull(exception);
            Assert.AreEqual("One or more errors occurred.", exception.Message);

            var innerException = exception.InnerExceptions.FirstOrDefault();

            Assert.IsNotNull(innerException);
            Assert.AreEqual(typeof(GoogleApiException).ToString(), innerException.GetType().ToString());
            Assert.AreEqual("Response status code does not indicate success: 400 (Bad Request).", innerException.Message);
        }
        public async Task <Response <EntireDetectResponse> > DetectEntireSeriesAsync(DetectRequest body, CancellationToken cancellationToken = default)
        {
            if (body == null)
            {
                throw new ArgumentNullException(nameof(body));
            }

            using var message = CreateDetectEntireSeriesRequest(body);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);

            switch (message.Response.Status)
            {
            case 200:
            {
                EntireDetectResponse value = default;
                using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);

                value = EntireDetectResponse.DeserializeEntireDetectResponse(document.RootElement);
                return(Response.FromValue(value, message.Response));
            }
        internal HttpMessage CreateDetectEntireSeriesRequest(DetectRequest body)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;

            request.Method = RequestMethod.Post;
            var uri = new RawRequestUriBuilder();

            uri.AppendRaw(endpoint, false);
            uri.AppendRaw("/anomalydetector/v1.0", false);
            uri.AppendPath("/timeseries/entire/detect", false);
            request.Uri = uri;
            request.Headers.Add("Content-Type", "application/json");
            request.Headers.Add("Accept", "application/json");
            var content = new Utf8JsonRequestContent();

            content.JsonWriter.WriteObjectValue(body);
            request.Content = content;
            return(message);
        }
Esempio n. 27
0
        public void DetectTest()
        {
            var request = new DetectRequest
            {
                Key = this.ApiKey,
                Qs  = new[] { "Hello World" }
            };

            var result = GoogleTranslate.Detect.Query(request);

            Assert.IsNotNull(result);
            Assert.AreEqual(Status.Ok, result.Status);

            var detections = result.Data.Detections?.ToArray();

            Assert.IsNotNull(detections);
            Assert.IsNotEmpty(detections);

            var detection = detections.FirstOrDefault();

            Assert.IsNotNull(detection);
            Assert.AreEqual(Language.English, detection[0].Language);
        }
Esempio n. 28
0
        public void DetectWhenAsyncAndTimeoutTest()
        {
            var request = new DetectRequest
            {
                Key = this.ApiKey,
                Qs  = new[] { "Hello World" }
            };

            var exception = Assert.Throws <AggregateException>(() =>
            {
                var result = GoogleTranslate.Detect.QueryAsync(request, TimeSpan.FromMilliseconds(1)).Result;
                Assert.IsNull(result);
            });

            Assert.IsNotNull(exception);
            Assert.AreEqual(exception.Message, "One or more errors occurred.");

            var innerException = exception.InnerException;

            Assert.IsNotNull(innerException);
            Assert.AreEqual(innerException.GetType(), typeof(TaskCanceledException));
            Assert.AreEqual(innerException.Message, "A task was canceled.");
        }
        /// <summary>
        /// Detect facial coordinates
        /// </summary>
        /// <exception cref="Regula.FaceSDK.WebClient.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="detectRequest"></param>
        /// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
        /// <returns>Task of ApiResponse (DetectResponse)</returns>
        public async System.Threading.Tasks.Task <ApiResponse <DetectResponse> > DetectWithHttpInfoAsync(DetectRequest detectRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            // verify the required parameter 'detectRequest' is set
            if (detectRequest == null)
            {
                throw new ApiException(400, "Missing required parameter 'detectRequest' when calling MatchingApi->Detect");
            }

            var    localVarPath         = "/api/detect";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new List <KeyValuePair <String, String> >();
            var    localVarHeaderParams = new Dictionary <String, String>(this.Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (detectRequest != null && detectRequest.GetType() != typeof(byte[]))
            {
                localVarPostBody = this.Configuration.ApiClient.Serialize(detectRequest); // http body (model) parameter
            }
            else
            {
                localVarPostBody = detectRequest; // byte array
            }


            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await this.Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                            Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                            localVarPathParams, localVarHttpContentType, cancellationToken);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("Detect", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <DetectResponse>(localVarStatusCode,
                                                    localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)),
                                                    (DetectResponse)this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(DetectResponse))));
        }
 public virtual async Task <Response <EntireDetectResponse> > DetectEntireSeriesAsync(DetectRequest body, CancellationToken cancellationToken = default)
 {
     using var scope = _clientDiagnostics.CreateScope("AnomalyDetectorClient.DetectEntireSeries");
     scope.Start();
     try
     {
         return(await RestClient.DetectEntireSeriesAsync(body, cancellationToken).ConfigureAwait(false));
     }
     catch (Exception e)
     {
         scope.Failed(e);
         throw;
     }
 }