def create_group_add_person(groupId, groupName):

    # Create PersonGroup
    result = face_api.createPersonGroup(groupId, groupName, "")
    flag_reuse_person_group = False
    if (result!=''):
        result = eval(result)
        
        if (result["error"]["code"] == "PersonGroupExists"):
            
            del_person_group = raw_input('Delete this PersonGroup? (y/n) ')
    
            if (del_person_group=='y') or (del_person_group=='1'):
                print 'PersonGroup exists, deleting...'
        
                res_del = face_api.deletePersonGroup(groupId)
                print ('Deleting PersonGroup succeeded' if res_del=='' else 'Deleting PersonGroup failed')
                
                result = face_api.createPersonGroup(groupId, groupName, "")
                print ('Re-create PersonGroup succeeded' if res_del=='' else 'Re-create PersonGroup failed')
                
            elif (del_person_group=='n') or (del_person_group=='0'):
                # Get PersonGroup training status
                res      = face_api.getPersonGroupTrainingStatus(groupId)
                res      = res.replace('null','None')
                res_dict = eval(res)
                training_status = res_dict['status']
                if (training_status=='succeeded'):
                    flag_reuse_person_group = True
        elif (result["error"]["code"] == "RateLimitExceeded"):
            print 'RateLimitExceeded, please retry after 30 seconds'
            sys.exit()
    
    if not flag_reuse_person_group:
        # Create person and add person image
        image_paths = [os.path.join(imgPath, f) for f in os.listdir(imgPath)]
        nbr = 0
        
        for image_path in image_paths:
            nom = os.path.split(image_path)[1].split(".")[0]
            if nom not in list_nom:
                # Create a Person in PersonGroup
                personName = nom
                personId   = face_api.createPerson(groupId, personName, "")
    
                list_nom.append(nom)
                list_personId.append(personId)
                nbr += 1
            else:
                personId = list_personId[nbr-1]
    
            # Add image
            face_api.addPersonFace(groupId, personId, None, image_path, None)
            print "Add image...", nom, '\t', image_path
            time.sleep(0.25)
def retake_validate_photos(clientId, personId, step_time, flag_show_photos, imgPath, name):

    global global_vars
    global_var = (item for item in global_vars if item["clientId"] == str(clientId)).next()

    # Ask users if they want to change photo(s) or validate them
    b = validate_photo(clientId)
    image_to_paths = [root_path+imgPath+str(name)+"."+str(j)+suffix for j in range(nb_img_max)]

    while (b==0):
        global_var['text3'] = "Veuillez repondre"
        simple_message(clientId, u"Veuillez répondre quelles photos que vous voulez changer ?")

        while (global_var['respFromHTML'] == ""):
            pass
        nb = global_var['respFromHTML']
        global_var['respFromHTML'] = ""

        if ('-' in nb):
            nb2 = ''
            for i in range(int(nb[0]), int(nb[2])+1):
                nb2 = nb2 + str(i)
            nb = nb2

        nb = str_replace_chars(nb, [',',';','.',' '], ['','','',''])

        if (nb!=""):
            str_nb = ""
            for j in range(0, len(nb)):
                if (j==len(nb)-1):
                    str_nb = str_nb + "'" + nb[j] + "'"
                else:
                    str_nb = str_nb + "'" + nb[j] + "', "

            simple_message(clientId, 'Vous souhaitez changer les photos: ' + str_nb + ' ?')

            global_var['text']  = 'Re-prenant photos'
            global_var['text2'] = 'Veuillez patienter... '
            global_var['text3'] = ''

            simple_message(clientId, global_var['text'] + ' ' + global_var['text2'])
            time.sleep(0.25)
            chrome_server2client(clientId, 'START')

        for j in range(0, len(nb)):
            global_var['text3'] = str(j) + ' ont ete prises, reste a prendre : ' + str(len(nb)-j)
            time.sleep(step_time)
            print "Reprendre photo ", nb[j]
            #TODO: add a facedetect here to cut the face from image
            image_path = image_to_paths[int(nb[j])-1]
            os.remove(image_path) # Remove old image
            with open(image_path, 'wb') as f:
                f.write(global_var['binary_data'])
                f.close()

            print "Enregistrer photo " + image_path + ", nb de photos prises : " + nb[j]
        chrome_server2client(clientId, 'DONE')
        time.sleep(0.25)

        a = yes_or_no(clientId, u'Reprise de photos finie, souhaitez-vous réviser vos photos ?', 4)
        if (a==1):
            thread_show_photos2 = Thread(target = show_photos, args = (clientId, imgPath, name), name = 'thread_show_photos2_'+clientId)
            thread_show_photos2.start()

        b = validate_photo(clientId)
        global_var['text']  = ''
        global_var['text2'] = ''
        global_var['text3'] = ''
        if (b==1):
            break
    # End of While(b==0)

    print "Adding faces to person group..."
    image_to_paths = [root_path+imgPath+str(name)+"."+str(j)+suffix for j in range(nb_img_max)]
    for image_path in image_to_paths:
        face_api.addPersonFace(groupId, personId, None, image_path, None)

    # Retrain Person Group
    resultTrainPersonGroup = face_api.trainPersonGroup(groupId)
    print "Re-train Person Group: ", resultTrainPersonGroup

    global_var['flag_enable_recog'] = 1  # Re-enable recognition
    global_var['flag_ask'] = 1 # Reset asking
def create_group_add_person(groupId, groupName):

    # Create PersonGroup
    result = face_api.createPersonGroup(groupId, groupName, "")
    flag_reuse_person_group = False
    # if (result!=''):
    if ('error' in result):
        result = eval(result)

        if (result["error"]["code"] == "PersonGroupExists"):

            res_train_status      = face_api.getPersonGroupTrainingStatus(groupId)
            res_train_status      = res_train_status.replace('null','None')
            res_train_status_dict = eval(res_train_status)

            if ('error' not in res_train_status_dict):
                createdDateTime = res_train_status_dict['createdDateTime']
                year, month, day, hour, mi, sec = convert_datetime(createdDateTime)

                structTime = time.localtime()
                dt_now = datetime(*structTime[:6])


                # Compare if the PersonGroup has expired or not (24 hours)
                if (dt_now.year==year):
                    if (dt_now.month==month):
                        if (dt_now.day==day):
                            del_person_group = False
                        elif (dt_now.day-1==day):
                            if (dt_now.hour<hour):
                                del_person_group = False
                            else:
                                del_person_group = True
                        else:
                            del_person_group = True
                    else:
                        del_person_group = True
            else:
                del_person_group = True

            if (del_person_group):
                print 'PersonGroup exists, deleting...'

                res_del = face_api.deletePersonGroup(groupId)
                print ('Deleting PersonGroup succeeded' if res_del=='' else 'Deleting PersonGroup failed')

                result = face_api.createPersonGroup(groupId, groupName, "")
                print ('Re-create PersonGroup succeeded' if res_del=='' else 'Re-create PersonGroup failed')

                flag_reuse_person_group = False

            elif (not del_person_group):
                # Get PersonGroup training status
                training_status = res_train_status_dict['status']
                if (training_status=='succeeded'):
                    flag_reuse_person_group = True

        elif (result["error"]["code"] == "RateLimitExceeded"):
            print 'RateLimitExceeded, please retry after 30 seconds'
            sys.exit()

    if not flag_reuse_person_group:
        # Create person and add person image
        image_paths = [os.path.join(imgPath, f) for f in os.listdir(imgPath)]
        nbr = 0

        for image_path in image_paths:
            nom = os.path.split(image_path)[1].split(".")[0]
            if nom not in list_nom:
                # Create a Person in PersonGroup
                personName = nom
                personId   = face_api.createPerson(groupId, personName, "")

                list_nom.append(nom)
                list_personId.append(personId)
                nbr += 1
            else:
                personId = list_personId[nbr-1]

            # Add image
            face_api.addPersonFace(groupId, personId, None, image_path, None)
            print "Add image...", nom, '\t', image_path
            time.sleep(0.25)
def retake_validate_photos(clientId, personId, step_time, flag_show_photos, imgPath, name):

    global global_vars
    global_var = (item for item in global_vars if item["clientId"] == str(clientId)).next()

    # Ask users if they want to change photo(s) or validate them
    b = validate_photo(clientId)
    image_to_paths = [root_path+imgPath+str(name)+"."+str(j)+suffix for j in range(nb_img_max)]

    while (b==0):
        global_var['text3'] = "Veuillez repondre"
        simple_message(clientId, u"Veuillez répondre quelles photos que vous voulez changer ?")

        while (global_var['respFromHTML'] == ""):
            pass
        nb = global_var['respFromHTML']
        global_var['respFromHTML'] = ""

        if ('-' in nb):
            nb2 = ''
            for i in range(int(nb[0]), int(nb[2])+1):
                nb2 = nb2 + str(i)
            nb = nb2
        elif (nb=='*' or nb=='all'):
            nb=''
            for j in range(0, nb_img_max):
                nb = nb+str(j+1)
        elif any(nb[idx] in a for idx in range(0, len(nb))): # If there is any number in string
            nb2 = ''
            for j in range(0, len(nb)):
                if (nb[j] in a):
                    nb2 = nb2 + nb[j]
            nb = nb2
        else:
            print 'Fatal error: invalid response'
            nb = ''

        nb = str_replace_chars(nb, [',',';','.',' '], ['','','',''])

        if (nb!=""):
            str_nb = ""
            for j in range(0, len(nb)):
                if (j==len(nb)-1):
                    str_nb = str_nb + "'" + nb[j] + "'"
                else:
                    str_nb = str_nb + "'" + nb[j] + "', "

            simple_message(clientId, 'Vous souhaitez changer les photos: ' + str_nb + ' ?')

            global_var['text']  = 'Re-prenant photos'
            global_var['text2'] = 'Veuillez patienter... '
            global_var['text3'] = ''

            simple_message(clientId, global_var['text'] + ' ' + global_var['text2'])
            time.sleep(0.25)
            chrome_server2client(clientId, 'START')

        for j in range(0, len(nb)):
            global_var['text3'] = str(j) + ' ont ete prises, reste a prendre : ' + str(len(nb)-j)
            time.sleep(step_time)
            print "Reprendre photo ", nb[j]
            #TODO: add a facedetect here to cut the face from image
            image_path = image_to_paths[int(nb[j])-1]
            # os.remove(image_path) # Remove old image
            delete_image_on_github(image_path)

            # with open(image_path, 'wb') as f:
            #     f.write(global_var['binary_data'])
            #     f.close()
            put_image_to_github(image_path, global_var['binary_data'])

            print "Enregistrer photo " + image_path + ", nb de photos prises : " + nb[j]

        chrome_server2client(clientId, 'DONE')
        time.sleep(0.25)

        a = yes_or_no(clientId, u'Reprise de photos finie, souhaitez-vous réviser vos photos ?', 4)
        if (a==1):
            thread_show_photos2 = Thread(target = show_photos, args = (clientId, imgPath, name), name = 'thread_show_photos2_'+clientId)
            thread_show_photos2.start()

        b = validate_photo(clientId)
        global_var['text']  = ''
        global_var['text2'] = ''
        global_var['text3'] = ''
        if (b==1):
            break
    # End of While(b==0)

    print "Adding faces to person group..."
    image_to_paths = [root_path+imgPath+str(name)+"."+str(j)+suffix for j in range(nb_img_max)]
    for image_path in image_to_paths:
        image_data = get_image_from_github(image_path)
        face_api.addPersonFace(groupId, personId, None, None, image_data)

    # Retrain Person Group
    resultTrainPersonGroup = face_api.trainPersonGroup(groupId)
    print "Re-train Person Group: ", resultTrainPersonGroup

    global_var['flag_enable_recog'] = 1  # Re-enable recognition
    global_var['flag_ask'] = 1 # Reset asking
def create_group_add_person(groupId, groupName):

    # Create PersonGroup
    result = face_api.createPersonGroup(groupId, groupName, "")
    flag_reuse_person_group = False

    # if (result!=''):
    if ('error' in result):
        result = eval(result)

        if (result["error"]["code"] == "PersonGroupExists"):

            res_train_status      = face_api.getPersonGroupTrainingStatus(groupId)
            res_train_status      = res_train_status.replace('null','None')
            res_train_status_dict = eval(res_train_status)
            print res_train_status

            if 'error' not in res_train_status_dict:
                createdDateTime = res_train_status_dict['createdDateTime']
                year, month, day, hour, mi, sec = convert_datetime(createdDateTime)

                structTime = time.localtime()
                dt_now = datetime(*structTime[:6])


                # Compare if the PersonGroup has expired or not (24 hours)
                if (dt_now.year==year):
                    if (dt_now.month==month):
                        if (dt_now.day==day):
                            del_person_group = False
                        elif (dt_now.day-1==day):
                            if (dt_now.hour<hour):
                                del_person_group = False
                            else:
                                del_person_group = True
                        else:
                            del_person_group = True
                    else:
                        del_person_group = True
            else:
                del_person_group = True

            if (del_person_group):
                print 'PersonGroup exists, deleting...'

                res_del = face_api.deletePersonGroup(groupId)
                print ('Deleting PersonGroup succeeded' if res_del=='' else 'Deleting PersonGroup failed')

                result = face_api.createPersonGroup(groupId, groupName, "")
                print ('Re-create PersonGroup succeeded' if res_del=='' else 'Re-create PersonGroup failed')

                flag_reuse_person_group = False

            elif (not del_person_group):
                # Get PersonGroup training status
                training_status = res_train_status_dict['status']
                if (training_status=='succeeded'):
                    flag_reuse_person_group = True

        elif (result["error"]["code"] == "RateLimitExceeded"):
            print 'RateLimitExceeded, please retry after 30 seconds'
            sys.exit()



    if not flag_reuse_person_group:
        # Create person and add person image
        image_paths = [os.path.join(imgPath, f) for f in os.listdir(imgPath)]
        nbr = 0

        for image_path in image_paths:
            nom = os.path.split(image_path)[1].split(".")[0]
            if nom not in list_nom:
                # Create a Person in PersonGroup
                personName = nom
                personId   = face_api.createPerson(groupId, personName, "")

                list_nom.append(nom)
                list_personId.append(personId)
                nbr += 1
            else:
                personId = list_personId[nbr-1]

            # Add image
            image_data = get_image_from_github(image_path)
            face_api.addPersonFace(groupId, personId, None, None, image_data)
            print "Add image...", nom, '\t', image_path
            time.sleep(0.25)
for image_path in image_paths:
    nom = os.path.split(image_path)[1].split(".")[0]
    if nom not in list_nom:
        # Create a Person in a PersonGroup
        personName = nom
        personId   = face_api.createPerson(groupId, personName, "")

        list_nom.append(nom)
        list_personId.append(personId)
        nbr += 1
    else:
        personId = list_personId[nbr-1]

    print "Add image...", nom, '\t', image_path
    face_api.addPersonFace(groupId, personId, "", image_path, None)
    time.sleep(0.25)

resultTrainPersonGroup = face_api.trainPersonGroup(groupId)

res      = face_api.getPersonGroupTrainingStatus(groupId)
res      = res.replace('null','None')
res_dict = eval(res)
training_status = res_dict['status']
print training_status


while (training_status=='running'):
    time.sleep(0.25)
    res = face_api.getPersonGroupTrainingStatus(groupId)
    res = res.replace('null','None')