Beispiel #1
0
 def reply(self,
           query: TextQuery = None,
           user_id=None) -> SingleTextResponse:
     if self._props['is_museum_specific']:
         are_correct_details = False
         while not are_correct_details:
             query, slots = yield SingleTextWithFactAttachments(
                 is_finished=False,
                 is_successful=False,
                 text=
                 'Пожалуйста, уточните, для какого здания музея вам нужна эта информация',
                 attachments=list(self.MUSEUM_BUILDINGS))
             for building_name in self.MUSEUM_BUILDINGS:
                 if is_matching(
                         building_name, query,
                         textdistance.levenshtein.normalized_similarity):
                     question_responses = self._faq_dataset.responses[
                         self._props['question_category']]
                     selected_building = self.MUSEUM_BUILDINGS[
                         building_name]
                     yield SingleTextResponse(
                         is_finished=True,
                         is_successful=True,
                         text=question_responses['{}_response'.format(
                             selected_building)])
                     are_correct_details = True
     else:
         yield SingleTextResponse(
             is_finished=True,
             is_successful=True,
             text=self._faq_dataset.responses[
                 self._props['question_category']]['response'])
Beispiel #2
0
    def reply(self, slots: Dict[Slot, str], user_id=None) -> Union[SingleTextWithFactAttachments, SingleTextResponse]:
        query, _ = yield SingleTextWithFactAttachments(is_finished=False, is_successful=True,
                                                    text='Александ Сергеевич Пушкин - великий русский писатель',
                                                    attachments=list(self._qa.keys()))

        if query in self._qa:
            yield SingleTextResponse(is_finished=True, is_successful=True, text=self._qa[query])
        else:
            yield SingleTextResponse(is_finished=False, is_successful=False)
Beispiel #3
0
 def reply(cls, slots: Dict[Slot, str], user_id=None):
     address = slots.get(Slot.Address)
     if not address:
         query, slots = yield SingleTextResponse(
             is_finished=False,
             is_successful=True,
             text='Пожалуйста, уточните место отправления.')
         yield SingleTextResponse(is_finished=True,
                                  is_successful=True,
                                  text=cls._get_routes(query))
Beispiel #4
0
    def reply(cls, slots: Dict[Slot, str], user_id=None) -> Union[SingleTextWithFactAttachments, SingleTextResponse]:
        hall = slots.get(Slot.HallName)

        if not hall:
            yield cls.FALLBACK_RESPONSE

        previous_location = cls._get_previous_location(user_id)
        previous_location_changed = False

        if previous_location:
            query, slots = yield SingleTextResponse(is_finished=False,
                                             is_successful=True,
                                             text=f'Скажите, находитесь ли вы сейчас в холле "{previous_location}"?')
            if query.lower() not in ['да', 'верно', 'ага']:
                previous_location_changed = True

        if previous_location_changed or not previous_location:
            _, slots = yield SingleTextResponse(is_finished=False,
                                             is_successful=True,
                                             text='Пожалуйста, уточните, в каком холле вы сейчас находитесь.')
            previous_location = slots.get(Slot.HallName)
            if not previous_location:
                yield cls.FALLBACK_RESPONSE

        route_builder = RouteBuilder(NEIGHBOR_PLACES)
        from_place = cls._find_corresponding_hall(previous_location)
        to_place = cls._find_corresponding_hall(hall)
        cls._log_previous_location(user_id=user_id, location=hall)
        try:
            route = route_builder.get_nearest_route(from_place=from_place, to_place= to_place)
            if len(route) == 1:
                yield SingleTextResponse(is_finished=True,
                                         is_successful=True,
                                         text='Вы уже на месте!')
            if len(route) <= 3:
                yield SingleTextResponse(is_finished=True,
                                         is_successful=True,
                                         text=cls._generate_route_text_description(route))
            else:
                draw_route_on_image(image_path=cls.MAP_IMAGE_PATH,
                                    route=route,
                                    save_img_path=cls.SAVE_IMAGE_PATH)
                yield SingleImageResponse(is_finished=True,
                                          is_successful=True,
                                          img_local_path=cls.SAVE_IMAGE_PATH,
                                          text='Следуйте проложенному маршруту!')
        except (ValueError, RouteBuilderError):
            yield cls.FALLBACK_RESPONSE
    def reply(self,
              slots: Dict[Slot, str],
              user_id=None) -> SingleTextResponse:
        output = self._es.search(index='shop-index',
                                 body={
                                     "query": {
                                         "match": {
                                             "type": {
                                                 "query": 'rentalcar',
                                                 "fuzziness": "2"
                                             }
                                         }
                                     }
                                 })['hits']['hits'][0]['_source']
        text = f'{output["name"]}, floor: {output["floor"]}, type: {output["type"]}'

        if output['image_url']:
            yield SingleImageResponse(is_finished=True,
                                      is_successful=True,
                                      text=text,
                                      img_url=output['image_url'],
                                      img_description='')
        else:
            yield SingleTextResponse(is_finished=True,
                                     is_successful=True,
                                     text=text)
 def reply(self,
           slots: Dict[Slot, str],
           user_id=None) -> SingleTextResponse:
     yield SingleTextResponse(
         is_finished=True,
         is_successful=True,
         text='Emergency path is available, open AR and follow the guide')
Beispiel #7
0
    def _filter_by_material_answer(self, material):
        output = self._es.search(index='collection-index',
                                 body={
                                     "query": {
                                         "match": {
                                             "material": {
                                                 "query": material,
                                                 "fuzziness": "2"
                                             }
                                         }
                                     }
                                 })['hits']['hits']

        if len(output) > 3:
            output = output[0:3]
        authors = [
            x["_source"]["about_author"]["name"]
            if 'about_author' in x["_source"] else 'неизвестен' for x in output
        ]
        answer = '.\n'.join([
            f'{idx}. {x["_source"]["art_name"]}, автор {authors[idx-1]}. Зал {random.randint(1, 25)}'
            for idx, x in enumerate(output, start=1)
        ])

        return SingleTextResponse(is_finished=True,
                                  is_successful=True,
                                  text=f'Предлагаю вам ознакомиться '
                                  f'с следюущими шедеврами именно в таком '
                                  f'поряке:\n{answer}')
Beispiel #8
0
 def reply(self,
           slots: Dict[Slot, str],
           user_id=None) -> SingleTextResponse:
     yield SingleTextResponse(
         is_finished=True,
         is_successful=True,
         text='hello, dear guest and welcome to the Stuttgart airport')
    def reply(self,
              slots: Dict[Slot, str],
              user_id=None) -> Union[SingleTextResponse, SingleImageResponse]:
        shop_name = self._initial_slots[Slot.ShopByName]

        output = self._es.search(index='shop-index',
                                 body={
                                     "query": {
                                         "match": {
                                             "name": {
                                                 "query": shop_name,
                                                 "fuzziness": "2"
                                             }
                                         }
                                     }
                                 })['hits']['hits'][0]['_source']

        text = f'{output["name"]}, floor: {output["floor"]}, type: {output["type"]}'
        # TODO add description

        if output['image_url']:
            yield SingleImageResponse(is_finished=True,
                                      is_successful=True,
                                      text=text,
                                      img_url=output['image_url'],
                                      img_description='')
        else:
            yield SingleTextResponse(is_finished=True,
                                     is_successful=True,
                                     text=text)
Beispiel #10
0
    def reply(self, slots: Dict[Slot, str], user_id=None) -> Union[SingleTextResponse, SingleImageResponse]:

        name, profession = self._initial_slots[Slot.Name], self._initial_slots[Slot.NameProfession]
        output = self._es.search(index='collection-index', body={
            "query": {
                "match": {
                    "about_author.name": {
                        "query": name,
                        "fuzziness": "2"
                    }
                }
            }
        })['hits']['hits']
        output = random.choice(output)

        hall = output["_source"]["hall"] if output["_source"]["hall"] else random.randint(1, 25)
        picture_name = "'{}'".format(output["_source"]["art_name"])

        text = f'{name}, основная отрасль искусства: {profession}. Страна {output["_source"]["country"]}. ' \
               f'Одно из популярных произведений {picture_name}. Посмотреть на шедевр можно в {hall} зале'

        raw_text = clean_html(output['_source']['text']).split('.')

        summary = '.'.join(raw_text[0:2]) if len(raw_text) >= 2 else '.'.join(raw_text) + '.'

        descr = clean_html(output['_source']['annotation']) if output['_source']['annotation'] != 'empty' \
            else summary

        if output["_source"]['img']:
            yield SingleImageResponse(is_finished=True, is_successful=True, text=text,
                                      img_url=f'https://pushkinmuseum.art{output["_source"]["img"]}', img_description=descr)
        else:
            yield SingleTextResponse(is_finished=True, is_successful=True, text=text)
Beispiel #11
0
 def reply(self,
           slots: Dict[Slot, str],
           user_id=None) -> SingleTextResponse:
     yield SingleTextResponse(
         is_finished=True,
         is_successful=True,
         text=
         'Following directions are the most popular, choose one and proceed:\n'
         'S2 From Stuttgart Airport to Stuttgart Central Station will arrive in 7 minutes\n'
         'S3 From Stuttgart Airport to Maubach Station will arrive in 22 minutes'
     )
Beispiel #12
0
    def reply(self,
              slots: Dict[Slot, str],
              user_id=None) -> Union[SingleTextResponse, SingleImageResponse]:
        event_name = self._initial_slots[Slot.EventName]

        output = self._es.search(index='event-index',
                                 body={
                                     "query": {
                                         "match": {
                                             "event_name": {
                                                 "query": event_name,
                                                 "fuzziness": "2"
                                             }
                                         }
                                     }
                                 })['hits']['hits'][0]['_source']

        data_begin, data_end = output['dateBegin'], output['dateEnd']
        name = output['event_name']
        halls = output['halls'] if output['halls'] else 'уточняется'
        event_type = output['type']
        price = clean_html(
            output['price']) if output['price'] else 'уточняется'
        raw_text = clean_html(output['text']).split('.')
        summary = '.'.join(
            raw_text[0:5]) if len(raw_text) >= 5 else '.'.join(raw_text) + '.'

        text = f"{name}. Тип мероприятия: {event_type}. Будет проходить с {data_begin} по {data_end}. " \
               f"Место проведения: {halls}. Стоимость билетов: {price}.\nКоротко о событии: {summary}.".replace('\n'
                                                                                                                '<br '
                                                                                                                '/>',
                                                                                                                '').replace(' 00:00:00', '')
        img = output['img'] if output['img'] else output['extra_img']

        if img:
            yield SingleImageResponse(
                is_finished=True,
                is_successful=True,
                text=text,
                img_url=f'https://pushkinmuseum.art/{img}',
                img_description='')
        else:
            yield SingleTextResponse(is_finished=True,
                                     is_successful=True,
                                     text=text)
    def reply(self,
              slots: Dict[Slot, str],
              user_id=None) -> Union[SingleTextResponse, SingleImageResponse]:
        art_name = self._initial_slots[Slot.ArtName]

        output = self._es.search(index='collection-index',
                                 body={
                                     "query": {
                                         "match": {
                                             "art_name": {
                                                 "query": art_name,
                                                 "fuzziness": "2"
                                             }
                                         }
                                     }
                                 })['hits']['hits'][0]

        author = output['_source']['about_author'][
            'name'] if 'about_author' in output['_source'] else 'неизвестен'
        hall = output["_source"]["hall"] if output["_source"][
            "hall"] != 'empty' else random.randint(1, 25)
        text = f'Работа {art_name}. Автор {author}. Посмотреть на шедевр можно в зале {hall}'

        raw_text = clean_html(output['_source']['text']).split('.')
        summary = '.'.join(
            raw_text[0:2]) if len(raw_text) >= 2 else '.'.join(raw_text) + '.'

        descr = clean_html(output['_source']['annotation']) if output['_source']['annotation'] != 'empty' \
            else summary

        if output["_source"]['img']:
            yield SingleImageResponse(
                is_finished=True,
                is_successful=True,
                text=text,
                img_url=f'https://pushkinmuseum.art{output["_source"]["img"]}',
                img_description=descr)
        else:
            yield SingleTextResponse(is_finished=True,
                                     is_successful=True,
                                     text=f'{text}\n{descr}')
Beispiel #14
0
 def _generate_answer_for_given_author(self, material, name):
     output = [
         x for x in self._es.search(index='collection-index',
                                    body={
                                        "query": {
                                            "match": {
                                                "about_author.name": {
                                                    "query": name,
                                                    "fuzziness": "2"
                                                }
                                            }
                                        }
                                    })['hits']['hits']
         if x[Slot.Material] == material
     ]
     if not output:
         return SingleTextResponse(is_finished=True,
                                   is_successful=True,
                                   text=f'К сожалению, ничего не удалось '
                                   f'найти для {name}')
     else:
         pass
 def reply(self, slots: Dict[Slot, str], user_id=None) -> SingleTextResponse:
     yield SingleTextResponse(is_finished=True, is_successful=True, text='Авторы не научили меня отвечать '
                                                                         'на такие вопросы, но я исправлюсь!')
Beispiel #16
0
 def reply(self, slots: Dict[Slot, str], user_id=None) -> SingleTextResponse:
     yield SingleTextResponse(is_finished=True, is_successful=True, text='Привет! Я виртуалньый '
                                                                         'помощник Наталья по Пушкинскому музею и готова тебе помочь в любой момент!')
 def reply(self,
           slots: Dict[Slot, str],
           user_id=None) -> SingleTextResponse:
     yield SingleTextResponse(is_finished=True,
                              is_successful=True,
                              text='Sorry, I did not get ya!')
Beispiel #18
0
class InsideNavigationAction(AbstractAction):
    PREVIOUS_LOCATION_LOG_PATH = os.path.join('data', 'previous_location_log.json')
    MAP_IMAGE_PATH = os.path.join('navigation', 'data', 'main_floor_1.jpg')
    SAVE_IMAGE_PATH = os.path.join('navigation', 'data', 'route.jpg')
    recognized_types = [TextQuery, ImageQuery]
    triggering_phrases = ['как пройти', 'как найти', 'где картина', 'где зал', 'как дойти', 'хочу пойти',
                          'хочу посмотреть', 'хочу найти', 'как попасть']

    FALLBACK_RESPONSE = SingleTextResponse(is_finished=True,
                                     is_successful=True,
                                     text='Извините, на данный момент я не могу вам помочь с поиском. Но скоро я научусь!')

    @classmethod
    def _get_previous_location(cls, user_id):
        with open(cls.PREVIOUS_LOCATION_LOG_PATH) as f:
            log = json.load(f)
            if user_id in log:
                return log[user_id]

    @classmethod
    def _log_previous_location(cls, user_id, location):
        with open(cls.PREVIOUS_LOCATION_LOG_PATH, 'r') as f:
            log = json.load(f)
            log[user_id] = location
        with open(cls.PREVIOUS_LOCATION_LOG_PATH, 'w', encoding='utf8') as f:
            json.dump(log, f)

    @classmethod
    def _find_corresponding_hall(cls, hall_title):
        for hall in HALLS:
            if hall_title == hall.area.title:
                return hall

    @classmethod
    def _generate_route_text_description(cls, route: List[Place]) -> str:
        description = ['Следуйте моим указаниям!']
        description.append(f'Из зала "{route[0].area.title}" пройдите в зал "{route[1].area.title}".')
        for place in route[2:]:
            description.append(f'Далее - "{place.area.title}"')
        return ' '.join(description)

    @classmethod
    def activation_response(cls, initial_query: TextQuery, slots: Dict[Slot, str]) -> ActivationResponse:
        for phrase in cls.triggering_phrases:
            if phrase in initial_query.lower():
                return ActivationResponse(intent_detected=True)

    @classmethod
    def reply(cls, slots: Dict[Slot, str], user_id=None) -> Union[SingleTextWithFactAttachments, SingleTextResponse]:
        hall = slots.get(Slot.HallName)

        if not hall:
            yield cls.FALLBACK_RESPONSE

        previous_location = cls._get_previous_location(user_id)
        previous_location_changed = False

        if previous_location:
            query, slots = yield SingleTextResponse(is_finished=False,
                                             is_successful=True,
                                             text=f'Скажите, находитесь ли вы сейчас в холле "{previous_location}"?')
            if query.lower() not in ['да', 'верно', 'ага']:
                previous_location_changed = True

        if previous_location_changed or not previous_location:
            _, slots = yield SingleTextResponse(is_finished=False,
                                             is_successful=True,
                                             text='Пожалуйста, уточните, в каком холле вы сейчас находитесь.')
            previous_location = slots.get(Slot.HallName)
            if not previous_location:
                yield cls.FALLBACK_RESPONSE

        route_builder = RouteBuilder(NEIGHBOR_PLACES)
        from_place = cls._find_corresponding_hall(previous_location)
        to_place = cls._find_corresponding_hall(hall)
        cls._log_previous_location(user_id=user_id, location=hall)
        try:
            route = route_builder.get_nearest_route(from_place=from_place, to_place= to_place)
            if len(route) == 1:
                yield SingleTextResponse(is_finished=True,
                                         is_successful=True,
                                         text='Вы уже на месте!')
            if len(route) <= 3:
                yield SingleTextResponse(is_finished=True,
                                         is_successful=True,
                                         text=cls._generate_route_text_description(route))
            else:
                draw_route_on_image(image_path=cls.MAP_IMAGE_PATH,
                                    route=route,
                                    save_img_path=cls.SAVE_IMAGE_PATH)
                yield SingleImageResponse(is_finished=True,
                                          is_successful=True,
                                          img_local_path=cls.SAVE_IMAGE_PATH,
                                          text='Следуйте проложенному маршруту!')
        except (ValueError, RouteBuilderError):
            yield cls.FALLBACK_RESPONSE