Пример #1
0
        private async Task <List <FaceAnalyzeItem> > FaceProcessByStreamAsync(Stream imageStream, FaceDetectionModel detectionModel, bool enableIdentification, FaceRecognitionModel recognitionModel, FaceIdentificationGroupType identificationGroupType, string identificationGroupId)
        {
            var returnFaceId           = false;
            var returnFaceLandmarks    = true;
            var returnFaceAttributes   = FaceAttributes;
            var targetRecognitionModel = FaceRecognitionModel.recognition_01;

            if (FaceDetectionModel.detection_02.Equals(detectionModel))
            {
                returnFaceLandmarks  = false;
                returnFaceAttributes = new List <FaceAttributeType?>();
            }

            if (enableIdentification)
            {
                returnFaceId           = true;
                targetRecognitionModel = recognitionModel;
            }

            var detectedFaces = await _faceClient.Face.DetectWithStreamAsync(
                imageStream,
                returnFaceId : returnFaceId,
                returnFaceLandmarks : returnFaceLandmarks,
                returnFaceAttributes : returnFaceAttributes,
                recognitionModel : targetRecognitionModel.ToString(),
                returnRecognitionModel : true,
                detectionModel : detectionModel.ToString()
                );

            // Process detected faces
            return(await DetectedFacesProcessAsync(detectedFaces, detectionModel, enableIdentification, recognitionModel, identificationGroupType, identificationGroupId));
        }
        public async Task <IActionResult> UploadFile(IFormFile file)
        {
            var filename = Path.GetFileName(file.FileName);
            var filePath = Path.Combine(
                Directory.GetCurrentDirectory(), "wwwroot", "images",
                filename);

            if (file.Length > 0)
            {
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
            }

            var ImageData = new FaceRecognitionModel();

            FaceRecognitionProcess oProcess = new FaceRecognitionProcess();

            ImageData = await oProcess.DetectFace(filePath);

            TempData["FaceList"] = JsonConvert.SerializeObject(ImageData.oFaceList.m_faceListmodel);


            return(View("Index", ImageData.oImageDetail));
        }
Пример #3
0
        public static IForm <EnqueueForm> BuildForm()
        {
            OnCompletionAsyncDelegate <EnqueueForm> processOrder = async(context, state) =>
            {
                //Get the actual state of the FaceRecognitionModel , for then get the object id, photoId, name and file name
                FaceRecognitionModel faceRecognitionState = new FaceRecognitionModel();
                AppoinmentService    appointmentService   = new AppoinmentService();
                try
                {
                    if (!context.UserData.TryGetValue <FaceRecognitionModel>("FaceRecognitionModel", out faceRecognitionState))
                    {
                        faceRecognitionState = new FaceRecognitionModel();
                    }

                    FRService frService = new FRService();
                    int       caseId    = await frService.enqueueCustomer(faceRecognitionState.ObjectId, faceRecognitionState.PhotoId, faceRecognitionState.Name, faceRecognitionState.FileName);

                    //Get the actual user state of the customer
                    ACFCustomer customerState = new ACFCustomer();
                    try
                    {
                        if (!context.UserData.TryGetValue <ACFCustomer>("customerState", out customerState))
                        {
                            customerState = new ACFCustomer();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Not exists a user session");
                    }
                    //In this case I have the case, that has been enqueue, but the middleware don´thave a method for get by case id,
                    //but have yes a method for get a list of cases of customer id
                    if (caseId > 0)
                    {
                        Case _case = AppoinmentService.GetCaseById(customerState.CustomerId);
                        await context.PostAsync($"Your ticket was created, your number is: " + _case.QCode + _case.QNumber);
                    }
                    else
                    {
                        throw new Exception("Error: The case Id = 0");
                    }
                }
                catch (Exception ex)
                {
                    await context.PostAsync($"Failed with message: {ex.Message}");
                }
            };
            CultureInfo ci = new CultureInfo("en");

            Thread.CurrentThread.CurrentCulture   = ci;
            Thread.CurrentThread.CurrentUICulture = ci;
            FormBuilder <EnqueueForm> form = new FormBuilder <EnqueueForm>();

            return(form   //Message("Wait a moment please")
                   .Field(new FieldReflector <EnqueueForm>(nameof(UserId)).SetActive(InactiveField))
                   .AddRemainingFields()
                   .OnCompletion(processOrder)
                   .Build());
        }
Пример #4
0
        public async Task <FaceAnalyzeResponse> AnalyzeAsync(string imageUrl, IFormFile file,
                                                             FaceDetectionModel detectionModel, bool enableIdentification, FaceRecognitionModel recognitionModel,
                                                             FaceIdentificationGroupType identificationGroupType, string identificationGroupId)
        {
            // Face
            if (!string.IsNullOrWhiteSpace(imageUrl))
            {
                var face      = FaceProcessByUrlAsync(imageUrl, detectionModel, enableIdentification, recognitionModel, identificationGroupType, identificationGroupId);
                var imageInfo = ImageInfoProcessor.GetImageInfoFromImageUrlAsync(imageUrl, _httpClientFactory);

                // Combine
                var task = Task.WhenAll(face, imageInfo);
                try
                {
                    await task;
                    return(new FaceAnalyzeResponse
                    {
                        ImageInfo = imageInfo.Result,
                        FaceResult = face.Result
                    });
                }
                catch (APIErrorException ex)
                {
                    var exceptionMessage = ex.Response.Content;
                    var parsedJson       = JToken.Parse(exceptionMessage);

                    if (ex.Response.StatusCode == System.Net.HttpStatusCode.BadRequest)
                    {
                        return(new FaceAnalyzeResponse
                        {
                            ApiRequestErrorMessage = $"Bad request thrown by the underlying API from Microsoft:",
                            ApiRequestErrorContent = parsedJson.ToString(Formatting.Indented)
                        });
                    }
                    else
                    {
                        return(new FaceAnalyzeResponse
                        {
                            OtherErrorMessage = $"Error thrown by the underlying API from Microsoft:",
                            OtherErrorContent = parsedJson.ToString(Formatting.Indented)
                        });
                    }
                }
            }
            else
            {
                using (var analyzeStream = new MemoryStream())
                    using (var outputStream = new MemoryStream())
                    {
                        // Get initial value
                        await file.CopyToAsync(analyzeStream);

                        analyzeStream.Seek(0, SeekOrigin.Begin);
                        await analyzeStream.CopyToAsync(outputStream);

                        // Reset the stream for consumption
                        analyzeStream.Seek(0, SeekOrigin.Begin);
                        outputStream.Seek(0, SeekOrigin.Begin);

                        try
                        {
                            var face = await FaceProcessByStreamAsync(analyzeStream, detectionModel, enableIdentification, recognitionModel, identificationGroupType, identificationGroupId);

                            var imageInfo = ImageInfoProcessor.GetImageInfoFromStream(outputStream, file.ContentType);

                            return(new FaceAnalyzeResponse
                            {
                                ImageInfo = imageInfo,
                                FaceResult = face
                            });
                        }
                        catch (APIErrorException ex)
                        {
                            var exceptionMessage = ex.Response.Content;
                            var parsedJson       = JToken.Parse(exceptionMessage);

                            if (ex.Response.StatusCode == System.Net.HttpStatusCode.BadRequest)
                            {
                                return(new FaceAnalyzeResponse
                                {
                                    ApiRequestErrorMessage = $"Bad request thrown by the underlying API from Microsoft:",
                                    ApiRequestErrorContent = parsedJson.ToString(Formatting.Indented)
                                });
                            }
                            else
                            {
                                return(new FaceAnalyzeResponse
                                {
                                    OtherErrorMessage = $"Error thrown by the underlying API from Microsoft:",
                                    OtherErrorContent = parsedJson.ToString(Formatting.Indented)
                                });
                            }
                        }
                    }
            }
        }
Пример #5
0
        private async Task <List <FaceAnalyzeItem> > DetectedFacesProcessAsync(IList <DetectedFace> detectedFaces, FaceDetectionModel detectionModel, bool enableIdentification, FaceRecognitionModel recognitionModel, FaceIdentificationGroupType identificationGroupType, string identificationGroupId)
        {
            var unidentifiedResults = detectedFaces.Select(f => new FaceAnalyzeItem {
                DetectedFace = f
            }).ToList();

            if (!enableIdentification || detectedFaces.Count == 0)
            {
                return(unidentifiedResults);
            }

            // Check identification group training status and getting person list for name consolidation
            TrainingStatus identificationGroupTrainingStatus;
            IList <Person> identificationGroupPersons;

            if (FaceIdentificationGroupType.PersonGroup.Equals(identificationGroupType))
            {
                try
                {
                    identificationGroupTrainingStatus = await _faceClient.PersonGroup.GetTrainingStatusAsync(identificationGroupId);
                }
                catch (APIErrorException ex)
                {
                    // If group has never been trained, a 404 is thrown by the API
                    if ("PersonGroupNotTrained".Equals(ex.Body.Error.Code))
                    {
                        // TO DO - Add error info in reply
                        return(unidentifiedResults);
                    }
                    else
                    {
                        throw;
                    }
                }

                identificationGroupPersons = await _faceClient.PersonGroupPerson.ListAsync(identificationGroupId);
            }
            else
            {
                try
                {
                    identificationGroupTrainingStatus = await _faceClient.LargePersonGroup.GetTrainingStatusAsync(identificationGroupId);
                }
                catch (APIErrorException ex)
                {
                    // If group has never been trained, a 404 is thrown by the API
                    if ("PersonGroupNotTrained".Equals(ex.Body.Error.Code))
                    {
                        // TO DO - Add error info in reply
                        return(unidentifiedResults);
                    }
                    else
                    {
                        throw;
                    }
                }

                identificationGroupPersons = await _faceClient.LargePersonGroupPerson.ListAsync(identificationGroupId);
            }

            if (!TrainingStatusType.Succeeded.Equals(identificationGroupTrainingStatus.Status) ||
                identificationGroupPersons == null || identificationGroupPersons.Count == 0)
            {
                // TO DO - Add error info in reply
                return(unidentifiedResults);
            }

            // Identification request: max 10 faces / request (API limitation)
            var batchSize           = 10;
            var batchCount          = (int)Math.Ceiling((double)detectedFaces.Count / batchSize);
            var identificationTasks = new Task <IEnumerable <FaceAnalyzeItem> > [batchCount];

            for (var i = 0; i < batchCount; i++)
            {
                identificationTasks[i] = FaceIdentifyAsync(
                    detectedFaces.Skip(i * batchSize).Take(batchSize),
                    identificationGroupType,
                    identificationGroupId,
                    identificationGroupPersons
                    );
            }

            var identificationResults = await Task.WhenAll(identificationTasks.ToArray());

            var identifiedFaces = identificationResults.SelectMany(i => i).ToList();

            return(identifiedFaces);
        }
Пример #6
0
        /// <summary>
        /// This method create IForm for save the customer information
        /// </summary>
        /// <returns></returns>
        public static IForm <SaveCustomerForm> BuildForm()
        {
            OnCompletionAsyncDelegate <SaveCustomerForm> processOrder = async(context, state) =>
            {
                ACFCustomer customer = new ACFCustomer();
                try
                {
                    customer.CustomerId  = 0;//It is setted to 0, beacuse we will create new user, in other hand we can pass the id for update the record
                    customer.FirstName   = state.FirstName;
                    customer.LastName    = state.LastName;
                    customer.Email       = state.Email;
                    customer.PhoneNumber = state.PhoneNumber;
                    customer.Sex         = GetIntSex(state.Sex.ToString());
                    int customerId = AppoinmentService.SaveCustomer(customer.PhoneNumber, customer.Email, customer.FirstName,
                                                                    customer.LastName, customer.Sex, customer.PhoneNumber, customer.CustomerId);
                    state.customerId = customerId.ToString();
                    if (customerId > 0)
                    {
                        FRService frService = new FRService();
                        //Get the idImage Saved
                        int idImageSaved = 0;
                        if (!context.UserData.TryGetValue <int>("idImageSaveId", out idImageSaved))
                        {
                            idImageSaved = 0;
                        }

                        //Set the FaceRecognition Model,
                        FaceRecognitionModel faceRecognitionModel = new FaceRecognitionModel();
                        faceRecognitionModel.ObjectId = Utilities.Util.generateObjectId(customer.FirstName, customer.LastName, customer.PhoneNumber);
                        faceRecognitionModel.PhotoId  = savedImageId.ToString();
                        faceRecognitionModel.Name     = imageName;
                        faceRecognitionModel.FileName = imageName;
                        context.UserData.SetValue <FaceRecognitionModel>("FaceRecognitionModel", faceRecognitionModel);

                        bool uploadImage = await frService.uploadImage(customer.FirstName, customer.LastName, customer.PhoneNumber
                                                                       , imageName, savedImageId);

                        await context.PostAsync("Your user has been saved succesfully with the id: " + customerId);

                        /* Create the userstate */
                        //Instance of the object ACFCustomer for keept the customer
                        ACFCustomer customerState = new ACFCustomer();
                        customerState.CustomerId  = customerId;
                        customerState.FirstName   = customer.FirstName;
                        customerState.PhoneNumber = customer.PhoneNumber;
                        customerState.Sex         = Convert.ToInt32(customer.Sex);
                        customerState.PersonaId   = customer.PhoneNumber;
                        context.UserData.SetValue <ACFCustomer>("customerState", customerState);
                        context.UserData.SetValue <bool>("SignIn", true);
                    }
                }
                catch (Exception ex)
                {
                    await context.PostAsync("We have an error: " + ex.Message);
                }
            };
            CultureInfo ci = new CultureInfo("en");

            Thread.CurrentThread.CurrentCulture   = ci;
            Thread.CurrentThread.CurrentUICulture = ci;
            var culture  = Thread.CurrentThread.CurrentUICulture;
            var form     = new FormBuilder <SaveCustomerForm>();
            var yesTerms = form.Configuration.Yes.ToList();
            var noTerms  = form.Configuration.No.ToList();

            yesTerms.Add("Yes");
            noTerms.Add("No");
            form.Configuration.Yes = yesTerms.ToArray();
            return(form.Message("Fill the next information, please")
                   .Field(nameof(FirstName))
                   .Field(nameof(LastName))
                   .Field(nameof(Email))
                   .Field(nameof(PhoneNumber))
                   .Field(nameof(Sex))
                   .Field(new FieldReflector <SaveCustomerForm>(nameof(customerId)).SetActive(inActiveField))
                   .Confirm("Are you selected the information: " +
                            "\n* Name: {FirstName} " +
                            "\n* Last name:  {LastName} " +
                            "\n* Email:  {Email} " +
                            "\n* Phone Number: {PhoneNumber} " +
                            "\n* Sex:  {Sex}? \n" +
                            "(yes/no)")
                   .AddRemainingFields()
                   .Message("The process for save your user has been started!")
                   .OnCompletion(processOrder)
                   .Build());
        }
Пример #7
0
        /// <summary>
        /// This method create IForm for save the customer information
        /// </summary>
        /// <returns></returns>
        public static IForm <SaveCustomerFormApp> BuildForm()
        {
            OnCompletionAsyncDelegate <SaveCustomerFormApp> processOrder = async(context, state) =>
            {
                ACFCustomer customer = new ACFCustomer();
                try
                {
                    customer.CustomerId = 0;//It is setted to 0, beacuse we will create new user, in other hand we can pass the id for update the record

                    if (!string.IsNullOrEmpty(state.name) && !string.IsNullOrEmpty(state.LastName))
                    {
                        try
                        {
                            customer.FirstName = state.name;
                            customer.LastName  = state.LastName;
                        }
                        catch (Exception)
                        {
                        }
                    }
                    customer.PhoneNumber = state.PhoneNumber;
                    int customerId = AppoinmentService.SaveCustomer(customer.PhoneNumber, customer.FirstName,
                                                                    customer.LastName, customer.PhoneNumber, customer.CustomerId);
                    state.customerId = customerId.ToString();
                    if (customerId > 0)
                    {
                        FRService frService = new FRService();
                        //Get the idImage Saved
                        int idImageSaved = 0;
                        if (!context.UserData.TryGetValue <int>("idImageSaveId", out idImageSaved))
                        {
                            idImageSaved = 0;
                        }
                        //Set the FaceRecognition Model,
                        FaceRecognitionModel faceRecognitionModel = new FaceRecognitionModel();
                        faceRecognitionModel.ObjectId = Utilities.Util.generateObjectId(customer.FirstName, customer.LastName, customer.PhoneNumber);
                        faceRecognitionModel.PhotoId  = idImageSaved.ToString();
                        faceRecognitionModel.Name     = imageName;
                        faceRecognitionModel.FileName = imageName;
                        context.UserData.SetValue <FaceRecognitionModel>("FaceRecognitionModel", faceRecognitionModel);
                        bool uploadImage = await frService.uploadImage(customer.FirstName, customer.LastName, customer.PhoneNumber
                                                                       , imageName, idImageSaved);

                        await context.PostAsync("Congratulations, your account was created!");

                        /* Create the userstate */
                        //Instance of the object ACFCustomer for keept the customer
                        ACFCustomer customerState = new ACFCustomer();
                        customerState.CustomerId  = customerId;
                        customerState.FirstName   = customer.FirstName;
                        customerState.PhoneNumber = customer.PhoneNumber;
                        customerState.PersonaId   = customer.PhoneNumber;
                        context.UserData.SetValue <ACFCustomer>("customerState", customerState);
                        context.UserData.SetValue <bool>("SignIn", true);
                    }
                }
                catch (Exception ex)
                {
                    await context.PostAsync("We have an error: " + ex.Message);
                }
            };
            CultureInfo ci = new CultureInfo("en");

            Thread.CurrentThread.CurrentCulture   = ci;
            Thread.CurrentThread.CurrentUICulture = ci;
            var culture  = Thread.CurrentThread.CurrentUICulture;
            var form     = new FormBuilder <SaveCustomerFormApp>();
            var yesTerms = form.Configuration.Yes.ToList();
            var noTerms  = form.Configuration.No.ToList();

            yesTerms.Add("Yes");
            noTerms.Add("No");
            form.Configuration.Yes = yesTerms.ToArray();
            return(form//.Message("Fill the next information, please")
                   .Field(nameof(name))
                   .Field(nameof(LastName))
                   .Field(nameof(PhoneNumber), validate: async(state, response) =>
            {
                //This source code appear in warning beacuse not have a method async implemented, but works good without these method
                Regex rgx = new Regex(@"^[1-9][0-9]{7,14}$");
                //Regex rgx = new Regex(@"^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$");
                var result = new ValidateResult {
                    IsValid = true, Value = response
                };
                if (!string.IsNullOrEmpty(result.Value.ToString()))
                {
                    if (rgx.IsMatch(result.Value.ToString()))
                    {
                        result.IsValid = true;
                    }
                    else
                    {
                        result.Feedback = "Invalid phone number format";
                        result.IsValid = false;
                    }
                }
                return result;
            })
                   .Field(new FieldReflector <SaveCustomerFormApp>(nameof(customerId)).SetActive(inActiveField))
                   .AddRemainingFields()
                   .OnCompletion(processOrder)
                   .Build());
        }