def validate(self, dispatcher: CollectingDispatcher, tracker: Tracker,
                 domain: Dict[Text, Any]) -> List[Dict]:

        slot_values = self.extract_other_slots(dispatcher, tracker, domain)
        slot_to_fill = tracker.get_slot(REQUESTED_SLOT)

        if slot_to_fill:
            slot_values.update(
                self.extract_requested_slot(dispatcher, tracker, domain))

        else:
            temp = tracker.get_latest_entity_values('PER')
            aux = None
            for i in temp:
                if i.lower() != "hola":
                    aux = i
            aux2 = next(tracker.get_latest_entity_values('persona'), None)
            loc = next(tracker.get_latest_entity_values('LOC'), None)
            misc = next(tracker.get_latest_entity_values('MISC'), None)
            if aux is None and aux2 is not None:
                return [SlotSet('persona', aux2.title())]
            elif aux is not None and aux is not "Hola":
                return [SlotSet('persona', aux.title())]
            elif loc is not None:
                return [SlotSet('persona', loc)]
            elif misc is not None:
                return [SlotSet('persona', misc)]
            else:
                dispatcher.utter_message("Dime cómo te llamas")
                return []

        return [SlotSet(slot, value) for slot, value in slot_values.items()]
Exemple #2
0
    def run(self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict]:

        facility_type = tracker.get_slot('facility_type')
        healthcare_id = tracker.get_slot("facility_id")
        full_path = _create_path(ENDPOINTS["base"], facility_type,
                                 ENDPOINTS[facility_type]["id_query"],
                                 healthcare_id)
        results = requests.get(full_path).json()
        if results:
            selected = results[0]
            if facility_type == FACILITY_TYPES["hospital"]["resource"]:
                address = "{}, {}, {}".format(selected["address"].title(),
                                              selected["zip_code"].title(),
                                              selected["city"].title())
            elif facility_type == FACILITY_TYPES["nursing_home"]["resource"]:
                address = "{}, {}, {}".format(selected["provider_address"].title(),
                                              selected["provider_zip_code"].title(),
                                              selected["provider_city"].title())
            else:
                address = "{}, {}, {}".format(selected["address"].title(),
                                              selected["zip"].title(),
                                              selected["city"].title())

            return [SlotSet("facility_address", address)]
        else:
            print("No address found. Most likely this action was executed "
                  "before the user choose a healthcare facility from the "
                  "provided list. "
                  "If this is a common problem in your dialogue flow,"
                  "using a form instead for this action might be appropriate.")

            return [SlotSet("facility_address", "not found")]
Exemple #3
0
    def submit(self, dispatcher: CollectingDispatcher, tracker: Tracker,
               domain: Dict[Text, Any]) -> List[Dict]:
        """Define what the form has to do after all required slots are filled"""

        location = tracker.get_slot('location')
        speciality = tracker.get_slot('speciality')
        results = _find_providers(location, speciality)
        buttons = []
        for r in results:
            provider_id = r.get("provider_id")
            provider_name = r.get("provider_name")
            payload = "/inform{\"provider_id\":\"" + provider_id + "\"}"
            buttons.append({
                "title": "{}".format(provider_name.title()),
                "payload": payload
            })

        # limit number of buttons to 3 here for clear presentation purpose
        dispatcher.utter_button_message(
            "Here is a list of {} {} near you".format(len(buttons[:3]),
                                                      "providers"),
            buttons[:3],
            button_type="vertical")
        # todo: note: button options are not working BUG in rasa_core

        # utter submit template
        dispatcher.utter_template('utter_submit', tracker)
        return []
    def submit(self,
               dispatcher: CollectingDispatcher,
               tracker: Tracker,
               domain: Dict[Text, Any]) -> List[Dict]:
        """Define what the form has to do
            after all required slots are filled"""
        
        db = pymysql.connect('localhost', 'rasauser', 'rasapassword', 'rasa')
        cursor = db.cursor()

        name = tracker.get_slot('name')
        email = tracker.get_slot('email')
        password = tracker.get_slot('password')

        sql = f" INSERT INTO PERSON VALUES (NULL, '{name}', '{email}', '{password}')" 

        try:
            cursor.execute(sql)
            db.commit()
        except pymysql.Error as exc:
            print("error inserting...\n {}".format(exc))
        finally:
            db.close()

        # utter submit template
        dispatcher.utter_template('utter_submit', tracker)

        return []
Exemple #5
0
    def submit(self,
               dispatcher: CollectingDispatcher,
               tracker: Tracker,
               domain: Dict[Text, Any]) -> List[Dict]:
        location_name = tracker.get_slot('location')
        cuisine = tracker.get_slot('cuisine')
        budget = tracker.get_slot('budget')

        top_5_restaurants = []
        if self.lat is not None and self.lon is not None and self.cuisine_id is not None and self.budget_type is not None:
            top_5_restaurants = zomato_utils.get_top_restaurants_by_user_ratings(self.lat, self.lon, self.cuisine_id, self.budget_type)

        response = "No restaurants found in {} serving {} cuisine in {} budget".format(location_name, cuisine, budget)
        response_array = []

        if len(top_5_restaurants) > 0:
            index = 1
            response = "Following are top 5 restaurants matching your preference in order of average user rating on zomato:\n\n"
            for restaurant in top_5_restaurants:
                response = response + "{}. {} in {} has been rated {}\n".format(index, restaurant['name'], restaurant['address'], restaurant['user_rating'])
                index += 1
            response_array = [SlotSet("lat", self.lat), SlotSet("lon", self.lon), SlotSet("cuisine_id", self.cuisine_id), SlotSet("budget_type", self.budget_type)]

        dispatcher.utter_message(response)
        return response_array
Exemple #6
0
def test_activate_if_required():
    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

    form = CustomFormAction()

    tracker = Tracker('default', {}, {
        "intent": 'some_intent',
        "entities": [],
        "text": "some text"
    }, [], False, None, {}, 'action_listen')

    events = form._activate_if_required(tracker)
    # check that the form was activated
    assert events == [Form('some_form')]

    tracker = Tracker('default', {}, {}, [], False, None, {
        'name': 'some_form',
        'validate': True,
        'rejected': False
    }, 'action_listen')

    events = form._activate_if_required(tracker)
    # check that the form was not activated again
    assert events == []
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict]:

        facility_type = tracker.get_slot('facility_type')
        healthcare_id = tracker.get_slot("facility_id")
        full_path = _create_path(ENDPOINTS["base"], facility_type,
                                 ENDPOINTS[facility_type]["id_query"],
                                 healthcare_id)
        results = requests.get(full_path).json()
        selected = results[0]
        if facility_type == FACILITY_TYPES["hospital"]["resource"]:
            address = "{}, {}, {}".format(selected["address"].title(),
                                          selected["zip_code"].title(),
                                          selected["city"].title())
        elif facility_type == FACILITY_TYPES["nursing_home"]["resource"]:
            address = "{}, {}, {}".format(
                selected["provider_address"].title(),
                selected["provider_zip_code"].title(),
                selected["provider_city"].title())
        elif facility_type == FACILITY_TYPES["doctor"]["resource"]:
            adr = selected["adr_ln_1"].title()
            if "adr_ln_2" in selected.keys():
                adr += " {}".format(selected["adr_ln_2"].title())
            address = "{}, {}, {} {}\n Call {} to set up an appointment".format(
                adr, selected["cty"].title(),
                selected["st"], selected["zip"][:5].title(),
                phone_format(selected["phn_numbr"]))
        else:
            address = "{}, {}, {}".format(selected["address"].title(),
                                          selected["zip"].title(),
                                          selected["city"].title())

        return [
            SlotSet("facility_address", address if results is not None else "")
        ]
Exemple #8
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        #save in the slot the information that we got
        number_of_people = int(tracker.get_slot("num_persone"))
        orario = tracker.get_slot("orario")
        data = tracker.get_slot("data")
        prenotation_time = data + "T" + orario
        global number_of_seats
        service = authentication()
        if ":" == prenotation_time[-3:-2]:
            prenotation_time = prenotation_time[:-3] + prenotation_time[
                -2:]  # formattazione orario per chiamate successive
        prenotation_time_start = datetime.strptime(prenotation_time,
                                                   '%Y-%m-%dT%H:%M:%S.%f%z')
        prenotation_time_end = prenotation_time_start + timedelta(
            hours=2)  # si assume che una prenotazione duri 2 ore

        events_result = service.events().list(
            calendarId='*****@*****.**',
            timeMin=prenotation_time_start.isoformat(),
            timeMax=prenotation_time_end.isoformat()).execute()
        events = events_result.get('items', [])
        if check_available_seats(
                events, number_of_people
        ):  # si controlla che ci siano posti disponibili
            dispatcher.utter_template("utter_confirmation", tracker)
            return [SlotSet('available_seats', True)]
        else:
            dispatcher.utter_message("Mi dispiace ma siamo al completo.")
            return [SlotSet('available_seats', False)]
def test_extract_other_slots_with_intent():
    """Test extraction of other not requested slots values
        from entities with the same names
    """

    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        @staticmethod
        def required_slots(_tracker):
            return ["some_slot", "some_other_slot"]

        def slot_mappings(self):
            return {
                "some_other_slot": self.from_entity(
                    entity="some_other_slot", intent="some_intent"
                )
            }

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {"requested_slot": "some_slot"},
        {
            "intent": {"name": "some_other_intent", "confidence": 1.0},
            "entities": [{"entity": "some_other_slot", "value": "some_other_value"}],
        },
        [],
        False,
        None,
        {},
        "action_listen",
    )

    slot_values = form.extract_other_slots(CollectingDispatcher(), tracker, {})
    # check that the value was extracted for non requested slot
    assert slot_values == {}

    tracker = Tracker(
        "default",
        {"requested_slot": "some_slot"},
        {
            "intent": {"name": "some_intent", "confidence": 1.0},
            "entities": [{"entity": "some_other_slot", "value": "some_other_value"}],
        },
        [],
        False,
        None,
        {},
        "action_listen",
    )

    slot_values = form.extract_other_slots(CollectingDispatcher(), tracker, {})
    # check that the value was extracted only for non requested slot
    assert slot_values == {"some_other_slot": "some_other_value"}
Exemple #10
0
def test_extract_trigger_slots():
    """Test extraction of a slot value from trigger intent
    """

    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        @staticmethod
        def required_slots(_tracker):
            return ['some_slot']

        def slot_mappings(self):
            return {
                "some_slot":
                self.from_trigger_intent(intent="trigger_intent",
                                         value="some_value")
            }

    form = CustomFormAction()

    tracker = Tracker(
        'default', {},
        {'intent': {
            'name': 'trigger_intent',
            'confidence': 1.0
        }}, [], False, None, {}, 'action_listen')

    slot_values = form.extract_other_slots(CollectingDispatcher(), tracker, {})
    # check that the value was extracted for correct intent
    assert slot_values == {'some_slot': 'some_value'}

    tracker = Tracker('default', {},
                      {'intent': {
                          'name': 'other_intent',
                          'confidence': 1.0
                      }}, [], False, None, {}, 'action_listen')

    slot_values = form.extract_other_slots(CollectingDispatcher(), tracker, {})
    # check that the value was not extracted for incorrect intent
    assert slot_values == {}

    # tracker with active form
    tracker = Tracker(
        'default', {},
        {'intent': {
            'name': 'trigger_intent',
            'confidence': 1.0
        }}, [], False, None, {
            'name': 'some_form',
            'validate': True,
            'rejected': False
        }, 'action_listen')

    slot_values = form.extract_other_slots(CollectingDispatcher(), tracker, {})
    # check that the value was not extracted for correct intent
    assert slot_values == {}
Exemple #11
0
def test_extract_requested_slot_from_text_with_not_intent():
    """Test extraction of a slot value from text with certain intent
    """

    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        def slot_mappings(self):
            return {"some_slot": self.from_text(not_intent="some_intent")}

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {"requested_slot": "some_slot"},
        {
            "text": "some_text",
            "intent": {
                "name": "some_intent",
                "confidence": 1.0
            }
        },
        [],
        False,
        None,
        {},
        "action_listen",
    )

    slot_values = form.extract_requested_slot(CollectingDispatcher(), tracker,
                                              {})
    # check that the value was extracted for correct intent
    assert slot_values == {}

    tracker = Tracker(
        "default",
        {"requested_slot": "some_slot"},
        {
            "text": "some_text",
            "intent": {
                "name": "some_other_intent",
                "confidence": 1.0
            },
        },
        [],
        False,
        None,
        {},
        "action_listen",
    )

    slot_values = form.extract_requested_slot(CollectingDispatcher(), tracker,
                                              {})
    # check that the value was not extracted for incorrect intent
    assert slot_values == {"some_slot": "some_text"}
Exemple #12
0
def test_latest_input_channel():
    tracker = Tracker(
        'default', {}, {'intent': {
            'name': 'some_intent',
            'confidence': 1.0
        }}, [
            UserUttered("my message text", input_channel="superchat"),
            ActionExecuted("action_listen")
        ], False, None, {}, 'action_listen')

    assert tracker.get_latest_input_channel() == "superchat"
Exemple #13
0
def test_activate_if_required():
    # noinspection PyAbstractClass
    class CustomCustomFormAction(CustomFormAction):
        def name(self):
            return "some_form"

        @staticmethod
        def required_slots(_tracker):
            return ["some_slot", "some_other_slot"]

    form = CustomCustomFormAction()

    tracker = Tracker(
        "default",
        {},
        {
            "intent": "some_intent",
            "entities": [],
            "text": "some text"
        },
        [],
        False,
        None,
        {},
        "action_listen",
    )

    events = form._activate_if_required(dispatcher=None,
                                        tracker=tracker,
                                        domain=None)
    # check that the form was activated
    assert events == [Form("some_form")]

    tracker = Tracker(
        "default",
        {},
        {},
        [],
        False,
        None,
        {
            "name": "some_form",
            "validate": True,
            "rejected": False
        },
        "action_listen",
    )

    events = form._activate_if_required(dispatcher=None,
                                        tracker=tracker,
                                        domain=None)
    # check that the form was not activated again
    assert events == []
Exemple #14
0
def test_validate():
    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        @staticmethod
        def required_slots(_tracker):
            return ["some_slot", "some_other_slot"]

    form = CustomFormAction()

    tracker = Tracker('default', {'requested_slot': 'some_slot'}, {
        'entities': [{
            'entity': 'some_slot',
            'value': 'some_value'
        }, {
            'entity': 'some_other_slot',
            'value': 'some_other_value'
        }]
    }, [], False, None, {}, 'action_listen')

    events = form.validate(CollectingDispatcher(), tracker, {})
    # check that validation succeed
    assert (events == [
        SlotSet('some_other_slot', 'some_other_value'),
        SlotSet('some_slot', 'some_value')
    ] or events == [
        SlotSet('some_slot', 'some_value'),
        SlotSet('some_other_slot', 'some_other_value')
    ])

    tracker = Tracker('default', {'requested_slot': 'some_slot'}, {
        'entities': [{
            'entity': 'some_other_slot',
            'value': 'some_other_value'
        }]
    }, [], False, None, {}, 'action_listen')

    events = form.validate(CollectingDispatcher(), tracker, {})
    # check that validation succeed because other slot was extracted
    assert events == [SlotSet('some_other_slot', 'some_other_value')]

    tracker = Tracker('default', {'requested_slot': 'some_slot'},
                      {'entities': []}, [], False, None, {}, 'action_listen')
    with pytest.raises(Exception) as execinfo:
        form.validate(CollectingDispatcher(), tracker, {})

    # check that validation failed gracefully
    assert execinfo.type == ActionExecutionRejection
    assert ("Failed to validate slot some_slot "
            "with action some_form" in str(execinfo.value))
Exemple #15
0
def test_extract_other_slots_with_intent():
    """Test extraction of other not requested slots values
        from entities with the same names
    """

    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        @staticmethod
        def required_slots(_tracker):
            return ["some_slot", "some_other_slot"]

        def slot_mappings(self):
            return {
                "some_other_slot":
                self.from_entity(entity="some_other_slot",
                                 intent="some_intent")
            }

    form = CustomFormAction()

    tracker = Tracker('default', {'requested_slot': 'some_slot'}, {
        'intent': {
            'name': 'some_other_intent',
            'confidence': 1.0
        },
        'entities': [{
            'entity': 'some_other_slot',
            'value': 'some_other_value'
        }]
    }, [], False, None, {}, 'action_listen')

    slot_values = form.extract_other_slots(CollectingDispatcher(), tracker, {})
    # check that the value was extracted for non requested slot
    assert slot_values == {}

    tracker = Tracker('default', {'requested_slot': 'some_slot'}, {
        'intent': {
            'name': 'some_intent',
            'confidence': 1.0
        },
        'entities': [{
            'entity': 'some_other_slot',
            'value': 'some_other_value'
        }]
    }, [], False, None, {}, 'action_listen')

    slot_values = form.extract_other_slots(CollectingDispatcher(), tracker, {})
    # check that the value was extracted only for non requested slot
    assert slot_values == {'some_other_slot': 'some_other_value'}
Exemple #16
0
def test_extract_requested_slot_from_entity_with_not_intent():
    """Test extraction of a slot value from entity with the different name
        and certain intent
    """

    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        def slot_mappings(self):
            return {
                "some_slot":
                self.from_entity(entity="some_entity",
                                 not_intent="some_intent")
            }

    form = CustomFormAction()

    tracker = Tracker('default', {'requested_slot': 'some_slot'}, {
        'intent': {
            'name': 'some_intent',
            'confidence': 1.0
        },
        'entities': [{
            'entity': 'some_entity',
            'value': 'some_value'
        }]
    }, [], False, None, {}, 'action_listen')

    slot_values = form.extract_requested_slot(CollectingDispatcher(), tracker,
                                              {})
    # check that the value was extracted for correct intent
    assert slot_values == {}

    tracker = Tracker('default', {'requested_slot': 'some_slot'}, {
        'intent': {
            'name': 'some_other_intent',
            'confidence': 1.0
        },
        'entities': [{
            'entity': 'some_entity',
            'value': 'some_value'
        }]
    }, [], False, None, {}, 'action_listen')

    slot_values = form.extract_requested_slot(CollectingDispatcher(), tracker,
                                              {})
    # check that the value was not extracted for incorrect intent
    assert slot_values == {'some_slot': 'some_value'}
Exemple #17
0
def test_extract_other_slots_no_intent():
    """Test extraction of other not requested slots values
        from entities with the same names
    """

    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        @staticmethod
        def required_slots(_tracker):
            return ["some_slot", "some_other_slot"]

    form = CustomFormAction()

    tracker = Tracker(
        'default', {'requested_slot': 'some_slot'},
        {'entities': [{
            'entity': 'some_slot',
            'value': 'some_value'
        }]}, [], False, None, {}, 'action_listen')

    slot_values = form.extract_other_slots(CollectingDispatcher(), tracker, {})
    # check that the value was not extracted for requested slot
    assert slot_values == {}

    tracker = Tracker('default', {'requested_slot': 'some_slot'}, {
        'entities': [{
            'entity': 'some_other_slot',
            'value': 'some_other_value'
        }]
    }, [], False, None, {}, 'action_listen')

    slot_values = form.extract_other_slots(CollectingDispatcher(), tracker, {})
    # check that the value was extracted for non requested slot
    assert slot_values == {'some_other_slot': 'some_other_value'}

    tracker = Tracker('default', {'requested_slot': 'some_slot'}, {
        'entities': [{
            'entity': 'some_slot',
            'value': 'some_value'
        }, {
            'entity': 'some_other_slot',
            'value': 'some_other_value'
        }]
    }, [], False, None, {}, 'action_listen')

    slot_values = form.extract_other_slots(CollectingDispatcher(), tracker, {})
    # check that the value was extracted only for non requested slot
    assert slot_values == {'some_other_slot': 'some_other_value'}
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List:

        location = tracker.get_slot('location')
        facility_type = tracker.get_slot('facility_type')

        results = _find_facilities(location, facility_type)
        button_name = _resolve_name(FACILITY_TYPES, facility_type)
        if len(results) == 0:
            dispatcher.utter_message(
                "Sorry, we could not find a {} in {}.".format(
                    button_name, location))
            return []

        buttons = []
        print("found {} facilities".format(len(results)))
        for r in results:
            if facility_type == FACILITY_TYPES["hospital"]["resource"]:
                facility_id = r.get("provider_id")
                name = r["hospital_name"]
            elif facility_type == FACILITY_TYPES["nursing_home"]["resource"]:
                facility_id = r["federal_provider_number"]
                name = r["provider_name"]
            elif facility_type == FACILITY_TYPES["doctor"]["resource"]:
                facility_id = r["ind_enrl_id"]
                name = "{} {}".format(r["frst_nm"], r["lst_nm"])
            else:
                facility_id = r["provider_number"]
                name = r["provider_name"]

            payload = "/inform{\"facility_id\":\"" + facility_id + "\"}"
            buttons.append({
                "title": "{}".format(name.title()),
                "payload": payload
            })

        # limit number of buttons to 3 here for clear presentation purpose
        if "near" in location:
            location = "you"

        dispatcher.utter_button_message(
            "Here is a list of {} {}s near {}".format(len(buttons[:3]),
                                                      button_name, location),
            buttons[:3],
            button_type="custom")
        # todo: note: button options are not working BUG in rasa_core

        return []
Exemple #19
0
    def _utter_next_event(self, tracker: Tracker,
                          dispatcher: CollectingDispatcher) -> None:
        location = next(tracker.get_latest_entity_values('location'), None)
        events = self._get_events()

        if location:
            events_for_location = [e for e in events if e.location == location]
            if not events_for_location and events:
                next_event = events[0]
                dispatcher.utter_message(
                    "Sorry, there are currently no events "
                    "at your location. However, the next "
                    "event is the {} in {} on {}."
                    "".format(next_event.name_as_link(), next_event.location,
                              next_event.formatted_date()))
            elif events_for_location:
                next_event = events_for_location[0]
                dispatcher.utter_message(
                    "The next event in {} is the {} on {}."
                    " Hope to see you there!"
                    "".format(location, next_event.name_as_link(),
                              next_event.formatted_date()))
        elif events:
            next_event = events[0]
            dispatcher.utter_message("The next event is the {} in {} on {}. "
                                     "Hope to see you there!"
                                     "".format(next_event.name_as_link(),
                                               next_event.location,
                                               next_event.formatted_date()))
Exemple #20
0
    def _utter_next_event(self,
                          tracker: Tracker,
                          dispatcher: CollectingDispatcher
                          ) -> None:
        location = next(tracker.get_latest_entity_values('location'), None)
        events = self._get_events()

        if location:
            events_for_location = [e for e in events
                                   if e.city == location or
                                   e.country == location]
            if not events_for_location and events:
                next_event = events[0]
                dispatcher.utter_template(
                    'utter_no_event_for_location_but_next',
                    tracker, **next_event.as_kwargs())
            elif events_for_location:
                next_event = events_for_location[0]
                dispatcher.utter_template('utter_next_event_for_location',
                                          tracker,
                                          **next_event.as_kwargs())
        elif events:
            next_event = events[0]
            dispatcher.utter_template('utter_next_event', tracker,
                                      **next_event.as_kwargs())
Exemple #21
0
def test_validate_extracted_no_requested():
    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        @staticmethod
        def required_slots(_tracker):
            return ["some_slot", "some_other_slot"]

        def validate_some_slot(self, value, dispatcher, tracker, domain):
            if value == "some_value":
                return {"some_slot": "validated_value"}

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {"requested_slot": None},
        {"entities": [{
            "entity": "some_slot",
            "value": "some_value"
        }]},
        [],
        False,
        None,
        {},
        "action_listen",
    )

    events = form.validate(CollectingDispatcher(), tracker, {})
    # check that some_slot gets validated correctly
    assert events == [SlotSet("some_slot", "validated_value")]
Exemple #22
0
def test_extract_requested_slot_from_entity_no_intent():
    """Test extraction of a slot value from entity with the different name
        and any intent
    """

    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        def slot_mappings(self):
            return {"some_slot": self.from_entity(entity="some_entity")}

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {"requested_slot": "some_slot"},
        {"entities": [{
            "entity": "some_entity",
            "value": "some_value"
        }]},
        [],
        False,
        None,
        {},
        "action_listen",
    )

    slot_values = form.extract_requested_slot(CollectingDispatcher(), tracker,
                                              {})
    assert slot_values == {"some_slot": "some_value"}
Exemple #23
0
def test_extract_requested_slot_from_text_no_intent():
    """Test extraction of a slot value from text with any intent
    """

    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        def slot_mappings(self):
            return {"some_slot": self.from_text()}

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {"requested_slot": "some_slot"},
        {"text": "some_text"},
        [],
        False,
        None,
        {},
        "action_listen",
    )

    slot_values = form.extract_requested_slot(CollectingDispatcher(), tracker,
                                              {})
    assert slot_values == {"some_slot": "some_text"}
Exemple #24
0
def test_early_deactivation():
    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        @staticmethod
        def required_slots(_tracker):
            return ["some_slot", "some_other_slot"]

        def validate(self, dispatcher, tracker, domain):
            return self.deactivate()

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {"some_slot": "some_value"},
        {"intent": "greet"},
        [],
        False,
        None,
        {
            "name": "some_form",
            "validate": True,
            "rejected": False
        },
        "action_listen",
    )

    events = form.run(dispatcher=None, tracker=tracker, domain=None)

    # check that form was deactivated before requesting next slot
    assert events == [Form(None), SlotSet("requested_slot", None)]
    assert SlotSet("requested_slot", "some_other_slot") not in events
Exemple #25
0
def test_deprecated_helper_style():
    # noinspection PyAbstractClass
    # This method tests the old style of returning values instead of {'slot':'value'}
    # dicts, and can be removed if we officially stop supporting the deprecated style.
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        @staticmethod
        def required_slots(_tracker):
            return ["some_slot", "some_other_slot"]

        def validate_some_slot(self, value, dispatcher, tracker, domain):
            if value == "some_value":
                return "validated_value"

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {"requested_slot": "some_value"},
        {"entities": [{
            "entity": "some_slot",
            "value": "some_value"
        }]},
        [],
        False,
        None,
        {},
        "action_listen",
    )

    events = form.validate(CollectingDispatcher(), tracker, {})
    # check that some_slot gets validated correctly
    assert events == [SlotSet("some_slot", "validated_value")]
Exemple #26
0
def test_restaurant_1():
    form = RestaurantForm()

    ## sender_id, slots,
    #                  latest_message, events, paused, followup_action,
    #                  active_form, latest_action_name
    tracker = Tracker('default', {'requested_slot': 'cuisine'}, {
        'entities': [{
            'entity': 'cuisine',
            'value': 'some_value'
        }, {
            'entity': 'some_other_slot',
            'value': 'some_other_value'
        }]
    }, [], False, None, {
        'name': 'restaurant_form',
        'validate': True,
        'rejected': False
    }, 'action_listen')
    print("✁ req", tracker.slots, tracker.latest_message)

    dispatcher = CollectingDispatcher()
    events = form.run(dispatcher, tracker, domain)
    for ev in events:
        print(str(ev))
    print("☈", dispatcher.messages)
Exemple #27
0
def test_early_deactivation():
    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        @staticmethod
        def required_slots(_tracker):
            return ["some_slot", "some_other_slot"]

        def validate(self, dispatcher, tracker, domain):
            return self.deactivate()

    form = CustomFormAction()

    tracker = Tracker('default', {'some_slot': 'some_value'},
                      {'intent': 'greet'}, [], False, None, {
                          'name': 'some_form',
                          'validate': True,
                          'rejected': False
                      }, 'action_listen')

    events = form.run(dispatcher=None, tracker=tracker, domain=None)

    # check that form was deactivated before requesting next slot
    assert events == [Form(None), SlotSet('requested_slot', None)]
    assert SlotSet('requested_slot', "some_other_slot") not in events
Exemple #28
0
    def run(self, dispatcher, tracker: Tracker, domain):
        # type: (Dispatcher, DialogueStateTracker, Domain) -> List[Event]
        eventdate = tracker.get_slot('date')

        query = {
            "date": {
                "$gte": datetime.now(tz=pytz.timezone('America/Santo_Domingo'))
            }
        }
        # if eventdate:
        #    query = {"date": datetime.strptime(eventdate+"-"+str(datetime.now().year), '%B-%Y')}
        projection = dict()
        query["evento.asueto"] = "true"
        projection["evento.nombre"] = 1
        projection["date"] = 1
        matches = list()

        with MongoClient("mongodb://localhost:27017/") as client:
            database = client["kb"]
            collection = database["Calendarios"]
            docs = collection.find(query, projection=projection)

            if docs:
                for doc in docs:
                    dia = doc['date'].strftime('%d de %B del %Y')
                    matches.append(doc['evento']['nombre'] + " " + dia + '\n')

                dispatcher.utter_template('utter_ack_asuetos', tracker)
                dispatcher.utter_message(matches.__str__())
        return [SlotSet('asueto_count', docs.count())]
Exemple #29
0
    def validate(self,
                 dispatcher: CollectingDispatcher,
                 tracker: Tracker,
                 domain: Dict[Text, Any]) -> List[Dict]:

        slot_values = self.extract_other_slots(dispatcher, tracker, domain)


        slot_to_fill = tracker.get_slot(REQUESTED_SLOT)
        if slot_to_fill:
            slot_values.update(self.extract_requested_slot(dispatcher,
                                                           tracker, domain))
            if not slot_values:
                raise ActionExecutionRejection(self.name(),
                                               "Failed to validate slot {0}"
                                               "with action {1}"
                                               "".format(slot_to_fill,
                                                         self.name()))

        for slot, value in slot_values.items():
            if slot == "TypeOfVehicle":
                if value not in self.TypeOfVehicle_db():
                    dispatcher.utter_template('utter_wrong_TypeOfVehicle', tracker)
                    # validation failed, set slot to None
                    slot_values[slot] = None

        # validation succeed, set the slots values to the extracted values
        return [SlotSet(slot, value) for slot, value in slot_values.items()]
Exemple #30
0
    def validate(self, dispatcher: CollectingDispatcher, tracker: Tracker,
                 domain: Dict[Text, Any]) -> List[Dict]:
        """Validate extracted requested slot
            else reject the execution of the form action
        """
        # extract other slots that were not requested
        # but set by corresponding entity
        slot_values = self.extract_other_slots(dispatcher, tracker, domain)

        # extract requested slot
        slot_to_fill = tracker.get_slot(REQUESTED_SLOT)
        if slot_to_fill:
            slot_values.update(
                self.extract_requested_slot(dispatcher, tracker, domain))
            if not slot_values:
                # reject form action execution
                # if some slot was requested but nothing was extracted
                # it will allow other policies to predict another action
                raise ActionExecutionRejection(
                    self.name(), "Failed to validate slot {0} "
                    "with action {1}"
                    "".format(slot_to_fill, self.name()))

        # we'll check when validation failed in order
        # to add appropriate utterances
        for slot, value in slot_values.items():
            if slot == 'date':
                if self.date_validation(value) == False:
                    dispatcher.utter_template('utter_wrong_date', tracker)
                    slot_values[slot] = None

        # validation succeed, set the slots values to the extracted values
        return [SlotSet(slot, value) for slot, value in slot_values.items()]