Пример #1
0
def get_album_photos_url():
    print("Running the function: ", get_album_photos_url.__name__)

    url_list = []
    offset = 0

    while True:
        photos = vk_sessionUser.method(
            'photos.getAll', {
                'owner_id': -id_group,
                'offset': offset,
                'count': 200,
                'photo_sizes': 0,
                'no_service_albums': 0
            })
        # Выбор разрешений изображений
        for image in photos['items']:
            code = False
            for type_index in range(len(config.get('photo_sizes'))):
                for size_ind in range(len(image['sizes'])):
                    if image['sizes'][size_ind]['type'] == config.get(
                            'photo_sizes')[type_index]:
                        url_list.append(image['sizes'][size_ind]['url'])
                        code = True
                        break
                if code:
                    break
        if len(photos['items']) != 200:
            break
        else:
            offset += 200

    print(get_album_photos_url.__name__, " function is completed", end='\n\n')
    return url_list
Пример #2
0
def send_example(user_id, state):
    print("Running the function: ", send_example.__name__)

    attachments = []
    keyboard = Create_board(state)

    vk_sessionGroup.method(
        'messages.send', {
            'user_id':
            user_id,
            'message':
            config.get('chat').get('errors').get('photo').get('one_person'),
            'random_id':
            0,
            'keyboard':
            keyboard
        })
    message = upload.photo_messages(
        f'{config.get("media_folder").get("name")}\\' +
        f'{config.get("media_folder").get("folders").get("photo_example")}\\' +
        'example.jpg')[0]
    attachments.append('photo{}_{}'.format(message['owner_id'], message['id']))
    vk_sessionGroup.method(
        'messages.send', {
            'user_id': user_id,
            'message': 'Образец:',
            'random_id': 0,
            'attachment': ','.join(attachments)
        })
    print(send_example.__name__, " function is completed", end='\n\n')
    return
Пример #3
0
def help_list(user, event):
    command = "/help_list"

    interface.print_menu(user, command)
    interface.print_text(user, config.get('chat').get(command).get('help'))
    mdb.set_user_state(user, command)
    return
Пример #4
0
def delete_user_data(user, event):
    user_id = user['user_id']
    mdb.delete_user(user_id)

    text = config.get('chat').get('success').get('photo').get(
        'delete_user_data')
    vk_sessionGroup.method('messages.send', {
        'user_id': user_id,
        'message': text,
        'random_id': 0
    })
Пример #5
0
def get_user_photo(event):
    print("Running the function: ", get_user_photo.__name__)

    attach_type = event.object['message']['attachments'][0]["type"]
    if len(event.object['message']
           ['attachments']) != 1 and attach_type != 'photo':
        raise PhotoCountError(
            config.get('chat').get('errors').get('photo').get('one_person'))

    # Выбор разрешения изображения
    url = None
    code = False

    photo_sizes_config = config.get('photo_sizes')
    photo_sizes = event.object['message']['attachments'][0]['photo']['sizes']

    for type_index in range(len(photo_sizes_config)):
        for size_ind in range(len(photo_sizes)):
            if photo_sizes[size_ind]['type'] == photo_sizes_config[type_index]:
                url = photo_sizes[size_ind]['url']
                code = True
                break
        if code:
            break
    if not code:
        raise InvalidPhotoError(
            config.get('chat').get('errors').get('photo').get('size'))

    # Сохранение в хранилище
    path = f'{config.get("media_folder").get("name")}\\{id_group}\\' \
           f'{config.get("media_folder").get("folders").get("public").get("users")}\\'
    img_name = download_photo(url, path)

    # Получение данных изображения
    face_data = get_faces(path + img_name)
    if len(face_data) != 1:
        raise InvalidPhotoError(
            config.get('chat').get('errors').get('photo').get('one_person'))

    print(get_user_photo.__name__, " function is completed", end='\n\n')
    return face_data
Пример #6
0
def create_images_archive(person_photos):
    print("Running the function: ", create_images_archive.__name__)

    if len(person_photos) == 0:
        raise NotFoundError(
            config.get('chat').get('errors').get('photo').get('not_found'))

    path = f"{config.get('media_folder').get('name')}\\{id_group}\\" \
           f"{config.get('media_folder').get('folders').get('public').get('archives')}\\"
    name = uuid.uuid4()
    archive_name = f"{name}.zip"

    with ZipFile(path + archive_name, "w") as newzip:
        for photo in person_photos:
            im_path = photo["localhost"]["path"]
            im_name = photo["localhost"]["name"]
            newzip.write(im_path + im_name)

    print(create_images_archive.__name__, " function is completed", end='\n\n')
    return path, archive_name
Пример #7
0
def get_photos(user, event):
    command = '/get_photos'

    user_id = event.object['message']['from_id']
    state = user['chat']['state']

    if state == command:
        if len(event.object['message']['attachments']) == 0:
            raise UnexpectedRequestError

        face_data = vkbot_photo.get_user_photo(event)
        person_photos = vkbot_photo.search_person(user_id, face_data)
        vkbot_photo.send_archive_to_user(person_photos, user_id)

        parent = config.get('chat').get(command).get('parent')
        allfuncs[parent](user, event)
        return
    else:
        vkbot_photo.send_example(user_id, command)
        mdb.set_user_state(user, command)
    return
Пример #8
0
def search_person(user_id, face_data):
    print("Running the function: ", search_person.__name__)

    if len(face_data) != 1:
        raise FaceDataError(
            config.get('chat').get('errors').get('photo').get('face_data'))

    # Определяем класс
    '''
           Проверка на обученную модель sklearn.exceptions.NotFittedError
    '''
    cluster = int(model_learning.predict([face_data[0]['emb']])[0])

    # Выборка фотографий
    person_photos = []
    photos_id = set()

    # flag = False

    # if cluster == user_id:
    #     user_data = mdb.get_user_data(cluster)
    #     if user_data['embedding'] is not None and compare_faces([face_data[0]['emb']], user_data['embedding']):
    #         photos_id = mdb.get_user_photos(user_id)
    #     else:
    #         flag = True
    # if (cluster != user_id or flag) and cluster != -1:
    # Значение кластера соответствует id другого пользователя, иначе
    # натуральное значение кластера
    '''
            Если идентификация сменилась, но обучение уже прошло, то 
            как быть с классами id, они теперь ничьи
            Последствия изменения данных пользователя и времени переобучения
    '''
    if cluster != -1:

        # user_data = mdb.get_user_data(cluster)
        # if user_data:
        #     if user_data['embedding'] is not None and compare_faces([face_data[0]['emb']], user_data['embedding']):
        #         photos_id = mdb.get_user_photos(cluster)
        #
        # else:
        emb_id_list = []
        member = mdb.get_embedding({"cluster": cluster})

        # Сравниваем с одним лицом данного кластера
        if compare_faces([face_data[0]['emb']], member['embedding'])[0]:
            # user_data = mdb.get_user_data(user_id)
            # if user_data['embedding'] is not None and compare_faces([face_data[0]['emb']], user_data['embedding'])[0]:
            #     emb_list = mdb.get_embeddings_by_filter({"cluster": cluster})
            #     for emb in emb_list:
            #         emb_id_list.append(emb['_id'])
            #         photos_id.add(emb['photo_id'])
            #
            #     photos_id = list(photos_id)
            #
            #     mdb.update_user_photos(user_id, photos_id)
            #     mdb.update_embeddings_user_id(emb_id_list, user_id)
            # else:
            emb_list = mdb.get_embeddings_by_filter({"cluster": cluster})
            for emb in emb_list:
                photos_id.add(emb['photo_id'])

    photos_id = list(photos_id)

    for photo_id in photos_id:
        image = mdb.get_photo({"_id": photo_id})
        person_photos.append(image)

    if len(person_photos) == 0:
        raise NotFoundError(
            config.get('chat').get('errors').get('photo').get('not_found'))

    print(search_person.__name__, " function is completed", end='\n\n')
    return person_photos
Пример #9
0
def Create_board(state=None):
    # keyboard = VkKeyboard(one_time=True, inline=True)
    chat = 'chat'
    keyboard = VkKeyboard(one_time=False)
    if state is None:
        return keyboard.get_empty_keyboard()

    if state == '/start':
        keyboard.add_button(config.get(chat).get(state).get('ability'),
                            color=VkKeyboardColor.PRIMARY,
                            payload="{\"button:\": \"/ability\"}")
        keyboard.add_line()
        keyboard.add_button(config.get(chat).get(state).get('ask_admin'),
                            color=VkKeyboardColor.PRIMARY,
                            payload="{\"button:\": \"/ask_admin\"}")
        keyboard.add_line()
        keyboard.add_button(config.get(chat).get(state).get('help_list'),
                            color=VkKeyboardColor.PRIMARY,
                            payload="{\"button:\": \"/help_list\"}")
        keyboard = keyboard.get_keyboard()
        return keyboard

    elif state == '/ability':
        keyboard = VkKeyboard(one_time=True)
        keyboard.add_button(config.get(chat).get(state).get('search_photos'),
                            color=VkKeyboardColor.POSITIVE,
                            payload="{\"button:\": \"/search_photos\"}")
        keyboard.add_line()
        keyboard.add_button(config.get(chat).get(state).get('come_back'),
                            color=VkKeyboardColor.NEGATIVE,
                            payload="{\"button:\": \"/come_back\"}")
        keyboard = keyboard.get_keyboard()
        return keyboard

    elif state == '/ask_admin':
        keyboard.add_button(config.get(chat).get(state).get('come_back'),
                            color=VkKeyboardColor.NEGATIVE,
                            payload="{\"button:\": \"/come_back\"}")
        keyboard = keyboard.get_keyboard()
        return keyboard

    elif state == "/help_list":
        keyboard.add_button(
            config.get(chat).get(state).get('delete_user_data'),
            color=VkKeyboardColor.NEGATIVE,
            payload="{\"button:\": \"/delete_user_data\"}")
        keyboard.add_line()
        keyboard.add_button(config.get(chat).get(state).get('come_back'),
                            color=VkKeyboardColor.NEGATIVE,
                            payload="{\"button:\": \"/come_back\"}")
        keyboard = keyboard.get_keyboard()
        return keyboard

    elif state == '/search_photos':
        # keyboard.add_button(config.get(chat).get(state).get('identify'), color=VkKeyboardColor.POSITIVE,
        #                     payload="{\"button:\": \"/identify\"}")
        # keyboard.add_line()
        keyboard.add_button(config.get(chat).get(state).get('get_photos'),
                            color=VkKeyboardColor.PRIMARY,
                            payload="{\"button:\": \"/get_photos\"}")
        keyboard.add_line()
        keyboard.add_button(
            config.get(chat).get(state).get('help_search_photos'),
            color=VkKeyboardColor.PRIMARY,
            payload="{\"button:\": \"/help_search_photos\"}")
        keyboard.add_line()
        keyboard.add_button(config.get(chat).get(state).get('come_back'),
                            color=VkKeyboardColor.NEGATIVE,
                            payload="{\"button:\": \"/come_back\"}")
        keyboard.add_button(config.get(chat).get(state).get('start'),
                            color=VkKeyboardColor.NEGATIVE,
                            payload="{\"button:\": \"/start\"}")
        keyboard = keyboard.get_keyboard()
        return keyboard

    # elif state == "/ask_identify":
    #     keyboard = VkKeyboard(one_time=False, inline=True)
    #     keyboard.add_button(config.get(chat).get(state).get('yes'), color=VkKeyboardColor.PRIMARY,
    #                         payload="{\"button:\": \"/identify\"}")
    #     keyboard.add_button(config.get(chat).get(state).get('no'), color=VkKeyboardColor.PRIMARY,
    #                         payload="{\"button:\": \"/search_photos\"}")
    #     keyboard = keyboard.get_keyboard()
    #     return keyboard
    #
    # elif state == "/identify":
    #     keyboard = VkKeyboard(one_time=True)
    #     keyboard.add_button(config.get(chat).get(state).get('come_back'), color=VkKeyboardColor.NEGATIVE,
    #                         payload="{\"button:\": \"/come_back\"}")
    #     keyboard.add_line()
    #     keyboard.add_button(config.get(chat).get(state).get('start'), color=VkKeyboardColor.NEGATIVE,
    #                         payload="{\"button:\": \"/start\"}")
    #     keyboard = keyboard.get_keyboard()
    #     return keyboard

    elif state == "/get_photos":
        keyboard.add_button(config.get(chat).get(state).get('come_back'),
                            color=VkKeyboardColor.NEGATIVE,
                            payload="{\"button:\": \"/come_back\"}")
        keyboard.add_line()
        keyboard.add_button(config.get(chat).get(state).get('start'),
                            color=VkKeyboardColor.NEGATIVE,
                            payload="{\"button:\": \"/start\"}")
        keyboard = keyboard.get_keyboard()
        return keyboard
Пример #10
0
def message_processing(event):
    chat = 'chat'

    # Получение данных о пользователе
    user = check_user(event)
    state = user[chat]['state']

    if state is None:
        # Вывод главного меню
        allfuncs['/start'](user, event)
    else:
        # Определение запрашиваемой команды
        command = parse(event)

        # Выполнение пункта меню
        try:
            '''
                Решить, как избавиться
            '''
            # if state == "/ask_admin" and command is None:
            #     allfuncs[state](user, event)
            #
            # # Рассмотреть случай удаления вопроса
            # elif state == "/ask_identify" and command is not None:
            #     allfuncs[state](user, event, command)
            #
            # elif state == "/identify" and command is None:
            #     allfuncs[state](user, event)
            #
            # elif state == "/get_all" and command is None:
            #     allfuncs[state](user, event)
            #
            # elif state == "/get_series" and command is None:
            #     allfuncs[state](user, event)
            # elif state == "/get_series""/command is None:
            #     person_photos = allfuncs[command]
            if command is None:
                allfuncs[state](user, event)
            else:
                allfuncs[command](user, event)
        except KeyError:
            vk_sessionGroup.method(
                'messages.send', {
                    'user_id':
                    user['user_id'],
                    'message':
                    random.choice(config.get(chat).get('failure_phrases')),
                    'random_id':
                    0
                })
            allfuncs[state](user, event)

        except UnexpectedRequestError:
            vk_sessionGroup.method(
                'messages.send', {
                    'user_id':
                    user['user_id'],
                    'message':
                    random.choice(config.get(chat).get('failure_phrases')),
                    'random_id':
                    0
                })
            parent = config.get('chat').get(state).get('parent')
            allfuncs[parent](user, event)

        except (InvalidPhotoError, NotFoundError, PhotoCountError,
                FaceDataError) as error:
            vk_sessionGroup.method(
                'messages.send', {
                    'user_id': user['user_id'],
                    'message': error.message,
                    'random_id': 0
                })
            parent = config.get('chat').get(state).get('parent')
            allfuncs[parent](user, event)
Пример #11
0
def come_back(user, event):
    state = user['chat']['state']
    parent = config.get('chat').get(state).get('parent')
    allfuncs[parent](user, event)
    return
Пример #12
0
def help_search_photos(user, event):
    command = 'help_search_photos'
    interface.print_text(user, config.get('chat').get('/help_search_photos'))
    return