Ejemplo n.º 1
0
        private static void FindSimilarFacesInAllLargeFaceListsAsync()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            var processed = 0;

            using (var operation = telemetryClient.StartOperation <RequestTelemetry>("Find similar faces in all large face lists"))
            {
                try
                {
                    var filePath   = Path.Combine(Settings.FindSimilarFolderPath, "input.jpg");
                    var imageBytes = File.ReadAllBytes(filePath);
                    var stream     = new System.IO.MemoryStream(imageBytes);
                    var imageUri   = StorageHelper.UploadFileAsync(stream, $"input.jpg", "uploads", Settings.AzureWebJobsStorage, "image/jpeg").Result;

                    List <FaceClientSDK.Domain.Face.DetectResult> list = APIReference.Instance.Face.DetectAsync(imageUri, "age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise", true, true).Result;
                    bool isValid = true;

                    if (list.Count == 0)
                    {
                        isValid = false;

                        //delete file from storage
                        var res = StorageHelper.DeleteFileAsync($"input.jpg", "uploads", Settings.AzureWebJobsStorage).Result;

                        Console.WriteLine($"no face detected!");
                        telemetryClient.TrackTrace($"no face detected!");
                    }

                    if (list.Count > 1)
                    {
                        isValid = false;

                        //delete file from storage
                        var res = StorageHelper.DeleteFileAsync($"input.jpg", "uploads", Settings.AzureWebJobsStorage).Result;

                        Console.WriteLine($"multiple faces detected!");
                        telemetryClient.TrackTrace($"multiple faces detected!");
                    }

                    if (isValid)
                    {
                        var detectedFaceId = list.First().faceId.ToString();

                        List <FaceClientSDK.Domain.Face.FindSimilarResult> facesFoundInAllFaceLists = new List <FaceClientSDK.Domain.Face.FindSimilarResult>();
                        List <ListResult> faceList = APIReference.Instance.LargeFaceList.ListAsync("0", "1000").Result;

                        if (Parallel.ForEach(faceList, (s) => {
                            try
                            {
                                Settings.LargeFaceListId = s.largeFaceListId;
                                Console.WriteLine($"Find similar faces in LargeFaceListId: {s.largeFaceListId}");
                                telemetryClient.TrackTrace($"Find similar faces in LargeFaceListId: {s.largeFaceListId}");

                                List <FaceClientSDK.Domain.Face.FindSimilarResult> similarFaces = APIReference.Instance.Face.FindSimilarAsync(detectedFaceId, string.Empty, Settings.LargeFaceListId, new string[] { }, 10, "matchPerson").Result;

                                foreach (FaceClientSDK.Domain.Face.FindSimilarResult fs in similarFaces)
                                {
                                    facesFoundInAllFaceLists.Add(fs);
                                }

                                processed++;
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                                telemetryClient.TrackException(ex);
                                return;
                            }
                        }).IsCompleted)
                        {
                            if (Parallel.ForEach(facesFoundInAllFaceLists, (fs) => {
                                try
                                {
                                    GetFaceResult face = APIReference.Instance.LargeFaceList.GetFaceAsync(Settings.LargeFaceListId, fs.persistedFaceId).Result;

                                    Console.WriteLine($"PersistedFaceId: {fs.persistedFaceId}, UserData: {face.userData}, Confidence: {fs.confidence}");
                                    telemetryClient.TrackTrace($"PersistedFaceId: {fs.persistedFaceId}, UserData: {face.userData}, Confidence: {fs.confidence}");
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.Message);
                                    telemetryClient.TrackException(ex);
                                    return;
                                }
                            }).IsCompleted)
                            {
                                Console.WriteLine($"Processed lists: {processed}");
                                operation.Telemetry.Properties["ProcessedLists"] = processed.ToString();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    telemetryClient.TrackException(ex);
                }

                stopwatch.Stop();
                telemetryClient.TrackEvent($"Find similar faces in all large face lists - completed at {stopwatch.ElapsedMilliseconds} ms.");

                telemetryClient.StopOperation(operation);
            }
        }
Ejemplo n.º 2
0
        private static async void AddFaceToLargeFaceListAsync()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            var processed           = 0;
            var IterationsToRetry   = Settings.AddFaceRetries;
            var TimeToSleepForRetry = Settings.AddFaceTimeToSleepInMs;

            using (var operation = telemetryClient.StartOperation <RequestTelemetry>("Add face to large face list"))
            {
                try
                {
                    if (!Directory.Exists(Settings.ImageFolderPath))
                    {
                        throw new Exception("There was a problem validating the images folder");
                    }

                    List <string> imageList = Directory.GetFiles(Settings.ImageFolderPath, "*.jpg").ToList();

                    telemetryClient.TrackTrace($"ImageFolderPath: {Settings.ImageFolderPath}");

                    foreach (string s in imageList)
                    {
                        for (int i = 0; i <= IterationsToRetry; i++)
                        {
                            FileInfo imageFile = null;

                            try
                            {
                                imageFile = new FileInfo(s);

                                var noExtension = imageFile.Name.Replace(imageFile.Extension, "");

                                Metadata metadata = new Metadata()
                                {
                                    id = noExtension
                                };

                                var imageBytes = File.ReadAllBytes(imageFile.FullName);
                                var stream     = new MemoryStream(imageBytes);
                                var imageUri   = await StorageHelper.UploadFileAsync(stream, $"{imageFile.Name}", "images", Settings.AzureWebJobsStorage, "image/jpeg");

                                AddFaceResult resultFaceToList = await APIReference.Instance.LargeFaceList.AddFaceAsync(Settings.LargeFaceListId, imageUri, metadata.id, string.Empty);

                                if (resultFaceToList == null)
                                {
                                    return;
                                }

                                processed++;

                                Console.WriteLine($"Processed: {processed}, PersistedFaceId: {resultFaceToList.persistedFaceId}");
                                telemetryClient.TrackTrace($"Processed: {processed}, PersistedFaceId: {resultFaceToList.persistedFaceId}");

                                break;
                            }
                            catch (Exception ex)
                            {
                                var message = string.Empty;
                                if (i > 0)
                                {
                                    message = $"Retry #{i} in image: {imageFile.Name}, Exception: {ex.Message}";
                                }
                                else
                                {
                                    message = $"There was an error in image: {imageFile.Name}, Exception: {ex.Message}";
                                }

                                Console.WriteLine(message);

                                List <Exception> exs = new List <Exception>();
                                exs.Add(ex);
                                AggregateException aex = new AggregateException(message, exs);
                                telemetryClient.TrackException(aex);
                                Task.Delay(TimeToSleepForRetry).Wait();
                            }
                        }
                    }

                    Console.WriteLine($"Processed: {processed}");
                    operation.Telemetry.Properties["ProcessedFaces"] = processed.ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    telemetryClient.TrackException(ex);
                }

                stopwatch.Stop();
                telemetryClient.TrackEvent($"Add face to large face list - completed at {stopwatch.ElapsedMilliseconds} ms.");

                telemetryClient.StopOperation(operation);
            }
        }