public static async Task ResetFaceLists()
        {
            faceLists = new Dictionary <string, FaceListInfo>();

            try
            {
                //IEnumerable<FaceListMetadata> metadata = await FaceServiceHelper.GetFaceListsAsync(FaceListsUserDataFilter);
                IEnumerable <FaceListMetadata> metadata = await FaceServiceHelper.GetFaceListsAsync();

                foreach (var item in metadata)
                {
                    await FaceServiceHelper.DeleteFaceListAsync(item.FaceListId);
                }

                //We want to delete also local persisted DB
                using (var db = new KioskDBContext())
                {
                    db.SimilarFaces.RemoveRange(db.SimilarFaces);
                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                ErrorTrackingHelper.TrackException(e, "Error resetting face lists");
            }
        }
Example #2
0
        private async Task CreatePrsonIfNoSimilarFaceExistsAsync(List <FaceSendInfo> facesInfo, Guid newPersonID, Face f)
        {
            //TODO return person result so we can change candidate if we are not going with the one selected

            //We try to find person also thru similar face api
            SimilarFaceMatch result = await GetSimilarFace(f);

            using (var db = new KioskDBContext())
            {
                //If we create new similar face, we create also new person
                if (result.isNew)
                {
                    //We create db where we map SimilarPersonID to PersonID, because those are different in cognitive services
                    var perResult = await CreatePerson(facesInfo, newPersonID, f);

                    db.SimilarFaces.Add(new DBSimilarFace()
                    {
                        CreatedAt = DateTime.Now, FaceId = result.SimilarPersistedFace.PersistedFaceId.ToString(), PersonId = perResult.ToString()
                    });
                    await db.SaveChangesAsync();
                }

                else
                {
                    string personId = "";
                    try
                    {
                        personId = db.SimilarFaces.Where(sf => sf.FaceId == result.SimilarPersistedFace.PersistedFaceId.ToString()).FirstOrDefault().PersonId;

                        var person = await FaceServiceHelper.GetPersonAsync(groupId, new Guid(personId));

                        //Fill new info
                        var fi = facesInfo.Where(fin => fin.faceId == f.FaceId.ToString()).FirstOrDefault();
                        fi.canid   = personId;
                        fi.canname = person.Name;
                        fi.canconf = result.SimilarPersistedFace.Confidence;

                        //We did not identified person thru person group and we needed to use silimar face api, so we add picture
                        await AddFaceToPerson(f, person, new Guid(personId));
                    }
                    catch (Exception)
                    {
                        //Person was not found due to old entry in local DB (Exception thrown by FaceApi GetPersonAsync) or face was created only in list when not using complex identification

                        //If person is only in list,  we need to create it also in person list
                        if (personId == "")
                        {
                            var perResult2 = await CreatePerson(facesInfo, newPersonID, f);

                            db.SimilarFaces.Add(new DBSimilarFace()
                            {
                                CreatedAt = DateTime.Now, FaceId = result.SimilarPersistedFace.PersistedFaceId.ToString(), PersonId = perResult2.ToString()
                            });
                            await db.SaveChangesAsync();
                        }

                        //We clean the old entry from DB and create new Person
                        var oldDbEntry = db.SimilarFaces.Where(sf => sf.FaceId == result.SimilarPersistedFace.PersistedFaceId.ToString()).FirstOrDefault();
                        var perResult  = await CreatePerson(facesInfo, newPersonID, f);

                        if (oldDbEntry != null)
                        {
                            db.SimilarFaces.Update(oldDbEntry);
                            oldDbEntry.FaceId   = result.SimilarPersistedFace.PersistedFaceId.ToString();
                            oldDbEntry.PersonId = perResult.ToString();
                        }
                        else
                        {
                            db.SimilarFaces.Add(new DBSimilarFace()
                            {
                                CreatedAt = DateTime.Now, FaceId = result.SimilarPersistedFace.PersistedFaceId.ToString(), PersonId = perResult.ToString()
                            });
                        }

                        await db.SaveChangesAsync();
                    }
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="imageStream"></param>
        /// <param name="faceId"></param>
        /// <param name="faceRectangle"></param>
        /// <param name="complexScenario"> - Whether we are identifying face hard way - means whether we need to use db or not</param>
        /// <returns></returns>
        public static async Task <Tuple <SimilarPersistedFace, string> > FindSimilarPersistedFaceAsync(Stream imageStream, Guid faceId, FaceRectangle faceRectangle)
        {
            if (faceLists == null)
            {
                await Initialize();
            }

            Tuple <SimilarPersistedFace, string> bestMatch = null;

            var faceListId = faceLists.FirstOrDefault().Key;

            //Delete for testing purposes
            //await FaceServiceHelper.DeleteFaceListAsync(faceListId);
            try
            {
                SimilarPersistedFace similarFace = null;
                if (faceListId != null)
                {
                    try
                    {
                        similarFace = (await FaceServiceHelper.FindSimilarAsync(faceId, faceListId))?.FirstOrDefault();
                    }
                    catch (Exception e)
                    {
                        if ((e as FaceAPIException).ErrorCode == "FaceListNotReady")
                        {
                            // do nothing, list is empty but we continue
                        }
                    }
                }
                if (similarFace != null)
                {
                    if (bestMatch != null)
                    {
                        // We already found a match for this face in another list. Replace the previous one if the new confidence is higher.
                        if (bestMatch.Item1.Confidence < similarFace.Confidence)
                        {
                            bestMatch = new Tuple <SimilarPersistedFace, string>(similarFace, faceListId);
                        }
                    }
                    else
                    {
                        bestMatch = new Tuple <SimilarPersistedFace, string>(similarFace, faceListId);
                    }
                }
                else
                {
                    // If we are here we didnt' find a match, so let's add the face to the first FaceList that we can add it to. We
                    // might create a new list if none exist, and if all lists are full we will delete the oldest face list (based on when we
                    // last matched anything on it) so that we can add the new one.

                    if (!faceLists.Any())
                    {
                        // We don't have any FaceLists yet. Create one
                        newFaceListId = Guid.NewGuid().ToString();
                        // await FaceServiceHelper.CreateFaceListAsync(newFaceListId, "ManagedFaceList", FaceListsUserDataFilter);
                        //We are not using filters
                        await FaceServiceHelper.CreateFaceListAsync(newFaceListId, "ManagedFaceList");

                        faceLists.Add(newFaceListId, new FaceListInfo {
                            FaceListId = newFaceListId, LastMatchTimestamp = DateTime.Now
                        });
                    }

                    AddPersistedFaceResult addResult = null;

                    var faceList = faceLists.First();
                    if (faceList.Value.IsFull)
                    {
                        //It is here only for complex scenario where we use groups and lists mappings
                        try
                        {
                            DBSimilarFace faceToDelete = null;
                            using (var db = new KioskDBContext())
                            {
                                faceToDelete = db.SimilarFaces.OrderByDescending(sf => sf.PersonId).First();
                                db.SimilarFaces.Remove(faceToDelete);
                                await db.SaveChangesAsync();
                            }

                            await FaceServiceHelper.DeleteFaceFromFaceListAsync(faceList.Key, new Guid(faceToDelete.FaceId));
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine("No face to be deleted" + e.Message);
                        }
                    }

                    addResult = await FaceServiceHelper.AddFaceToFaceListAsync(faceList.Key, imageStream, faceRectangle);

                    if (addResult != null)
                    {
                        bestMatch = new Tuple <SimilarPersistedFace, string>(new SimilarPersistedFace {
                            Confidence = 1, PersistedFaceId = addResult.PersistedFaceId
                        }, null);
                    }
                }
            }
            catch (Exception e)
            {
                // Catch errors with individual face lists so we can continue looping through all lists. Maybe an answer will come from
                // another one.
                ErrorTrackingHelper.TrackException(e, "Face API FindSimilarAsync error");
            }

            return(bestMatch);
        }
Example #4
0
        public async Task <List <FaceSendInfo> > IdentifyOrAddPersonWithEmotionsAsync(string groupName, ObservableCollection <IdentifiedFaces> identifiedPersonsIdCollection)
        {
            var facesInfo = new List <FaceSendInfo>();

            //Loop thru all detected faces from previous steps and fill the facesInfo array
            //For ease of processing in Azure Stream Analytics we create single level object
            foreach (var f in this.DetectedFaces)
            {
                var fsi = new FaceSendInfo();

                //Add emotions
                var e = CoreUtil.FindEmotionForFace(f, this.DetectedEmotion);
                FeedFaceInfo(f, fsi, e);
                //We sen also info how many faces in total were recognized on the picture with current face
                fsi.facesNo = this.DetectedFaces.Count();

                facesInfo.Add(fsi);
            }

            //Now we proceed to face recognition/identification
            //First we create group if it does not exist
            try
            {
                var g = await FaceServiceHelper.CreatePersonGroupIfNoGroupExists(groupName);

                groupId = g.PersonGroupId;
            }
            catch (Exception e)
            {
                // Catch errors with individual groups so we can continue looping through all groups. Maybe an answer will come from
                // another one.
                ErrorTrackingHelper.TrackException(e, "Problem creating group");

                if (this.ShowDialogOnFaceApiErrors)
                {
                    await ErrorTrackingHelper.GenericApiCallExceptionHandler(e, "Problem creating group");
                }
            }


            //We need to find candidate for every face
            try
            {
                IdentifyResult[] groupResults = await this.IdentifyFacesAsync(groupId);

                //We loop thri all faces again in order to find candidate
                foreach (var f in this.DetectedFaces)
                {
                    bool needToRetrain = true;
                    var  fi            = facesInfo.Where(fin => fin.faceId == f.FaceId.ToString()).FirstOrDefault();
                    var  newPersonID   = Guid.NewGuid();

                    if (groupResults != null && groupResults.Where(gr => gr.FaceId == f.FaceId).Any() && groupResults.Where(gr => gr.FaceId == f.FaceId).FirstOrDefault().Candidates.Any())
                    {
                        var candidates = groupResults.Where(gr => gr.FaceId == f.FaceId).FirstOrDefault().Candidates.OrderByDescending(ca => ca.Confidence);

                        Person p   = new Person();
                        var    can = candidates.FirstOrDefault();

                        //If we have sufficient confidence, we add Face for person
                        if (can.Confidence >= SettingsHelper.Instance.Confidence)
                        {
                            fi.canid   = can.PersonId.ToString();
                            fi.canconf = can.Confidence;

                            //In order to get also name we need to obtain Person
                            p = await FaceServiceHelper.GetPersonAsync(groupId, can.PersonId);

                            fi.canname = p.Name;

                            var identifiedPersonFromList = identifiedPersonsIdCollection.Where(ip => ip.Id == can.PersonId.ToString()).FirstOrDefault();

                            //Check whether we did not added too much photos lately, it is not neccesary to add photo for face every time
                            if (identifiedPersonFromList == null)
                            {
                                await AddFaceToPerson(f, p, can.PersonId);
                            }
                            else if (identifiedPersonFromList.NumOfAddedPhotosInLastPeriod < SettingsHelper.Instance.NumberOfPhotoAddsInPeriod)
                            {
                                await AddFaceToPerson(f, p, can.PersonId);

                                identifiedPersonFromList.NumOfAddedPhotosInLastPeriod++;
                            }
                            else if ((DateTime.Now - identifiedPersonFromList.FirstPhotoAddedInLastPeriod).Hours > SettingsHelper.Instance.PhotoAddPeriodSize)
                            {
                                identifiedPersonFromList.NumOfAddedPhotosInLastPeriod = 1;
                                identifiedPersonFromList.FirstPhotoAddedInLastPeriod  = DateTime.Now;
                                await AddFaceToPerson(f, p, can.PersonId);
                            }
                            else
                            {
                                needToRetrain = false;
                            }
                        }
                        else
                        {
                            //if not sufficient confidence we also need to check whether there is similar face/ if not create new person
                            await CreatePrsonIfNoSimilarFaceExistsAsync(facesInfo, newPersonID, f);
                        }
                    }
                    else
                    {
                        //if no candidate we also need to check whether there is similar fac,e if not create new person
                        await CreatePrsonIfNoSimilarFaceExistsAsync(facesInfo, newPersonID, f);
                    }
                    try
                    {
                        //We need to train after operation on top of group (addition of photo, person etc.)
                        if (needToRetrain)
                        {
                            await FaceServiceHelper.TrainPersonGroupAsync(groupId);
                        }
                    }
                    catch (Exception e)
                    {
                        // Catch error with training of group
                        ErrorTrackingHelper.TrackException(e, "Problem training group");

                        if (this.ShowDialogOnFaceApiErrors)
                        {
                            await ErrorTrackingHelper.GenericApiCallExceptionHandler(e, "Problem training group");
                        }
                    }


                    //Handle the identified persons collection to which we locally save every identified person
                    if (!identifiedPersonsIdCollection.Where(ip => ip.Id == fi.canid).Any())
                    {
                        identifiedPersonsIdCollection.Add(new IdentifiedFaces()
                        {
                            Id = fi.canid
                        });
                    }

                    //Increase counter of identifications
                    else if (identifiedPersonsIdCollection.Where(ip => ip.Id == fi.canid).Any())
                    {
                        identifiedPersonsIdCollection.Where(ip => ip.Id == fi.canid).FirstOrDefault().NumberOfIdentifications++;
                    }

                    //Find faces which were wrongly learned (small number of identifications)
                    var tbd = new List <IdentifiedFaces>();
                    foreach (var ip in identifiedPersonsIdCollection)
                    {
                        if (ip.NumberOfIdentifications <= SettingsHelper.Instance.NeededFaceIdentNum && (ip.CreatedAt.AddSeconds(SettingsHelper.Instance.DeleteWindow) < DateTime.Now))
                        {
                            var    g    = (await FaceServiceHelper.GetPersonGroupsAsync()).Where(gr => gr.Name == groupName).FirstOrDefault();
                            Person pers = await FaceServiceHelper.GetPersonAsync(g.PersonGroupId, new Guid(ip.Id));

                            //if we saved insufficient number of faces than delete
                            if (pers.PersistedFaceIds.Length <= SettingsHelper.Instance.NeededFaceIdentNum)
                            {
                                await FaceServiceHelper.DeletePersonAsync(g.PersonGroupId, pers.PersonId);

                                string similarFaceId = "";
                                using (var db = new KioskDBContext())
                                {
                                    var sfToDelete = db.SimilarFaces.Where(sf => sf.PersonId == pers.PersonId.ToString()).FirstOrDefault();
                                    similarFaceId = sfToDelete.FaceId.ToString();
                                    db.SimilarFaces.Remove(sfToDelete);
                                }

                                await FaceListManager.DeleteFaceFromFaceList(similarFaceId);

                                await FaceServiceHelper.TrainPersonGroupAsync(g.PersonGroupId);

                                tbd.Add(ip);
                            }
                        }
                    }


                    foreach (var iptodelete in tbd)
                    {
                        identifiedPersonsIdCollection.Remove(iptodelete);
                    }
                }
            }
            catch (Exception e)
            {
                // Catch error with training of group
                ErrorTrackingHelper.TrackException(e, "Problem with cognitive services");

                if (this.ShowDialogOnFaceApiErrors)
                {
                    await ErrorTrackingHelper.GenericApiCallExceptionHandler(e, "Problem with cognitive services");
                }
            }
            return(facesInfo);
        }