Example #1
0
    def connect_to_dataflow(self, udc):
        """
        makes preparations fpor particular UserDomain. Here we may attach special receptors for
        VIP Users

        Args:
            udc: UserDomainController
        """
        self.ic = udc

        udc.sm.register_slot(self.username_slot)
        udc.sm.register_slot(self.interests_slot)
        # Connecting to dataflow
        self.sfi.connect_to_dataflow(udc)

        udc.im.register_interaction(self.sfi)
        # ############### Prepare RECEPTOR #################################################
        # ##################### System Connection (must be redone on system restart) #############
        from components.receptors.models import Receptor
        from components.signal_pattern_reflex.signal_pattern import SignalPattern
        receptor, created = Receptor.get_or_create(
            class_name='PhrasesMatcher',
            init_args={'phrases': ["ПОЗНАКОМИМСЯ", "ЗНАКОМСТВО"]})

        sp, _ = SignalPattern.get_or_create_strict(
            signal_type="UserMessageSignal")
        udc.user_domain.user_message_signal_pattern.connect(receptor.__call__)
        receptor_trigger_signal_pattern, _ = SignalPattern.get_or_create_strict(
            signal_type="ReceptorTriggeredSignal", receptor=receptor)
        receptor_trigger_signal_pattern.connect(self.start)
    def __init__(self, *args, **values):
        super().__init__(*args, **values)
        # create signal for each exit gate in interaction
        # Exit Gate Signals and Registry initialization
        self.EXIT_GATES_SIGNALS = {}
        self.EXIT_GATES_SIGNAL_PATTERNS = {}

        if not hasattr(self.interaction, 'EXIT_GATES_NAMES_LIST'):
            # TODO fix to support inheritance of ExitGates!
            # then import default Gates :
            self.EXIT_GATES_NAMES_LIST = self.interaction.base_EXIT_GATES_NAMES_LIST
        else:

            self.EXIT_GATES_NAMES_LIST = self.interaction.EXIT_GATES_NAMES_LIST

        # now init signal objects for each exit gate:
        # from components.signal_reflex_routes.models.signals import InteractionProcessCompletedSignal
        from components.signal_pattern_reflex.signal import Signal
        from components.signal_pattern_reflex.signal_pattern import SignalPattern

        for each_exit_gate_name in self.EXIT_GATES_NAMES_LIST:
            # create a signal object for each exit gate
            self.EXIT_GATES_SIGNAL_PATTERNS[
                each_exit_gate_name], _ = SignalPattern.get_or_create_strict(
                signal_type="InteractionProcessCompletedSignal", user_domain=self.user_domain,
                interaction=self.interaction,
                exit_gate=each_exit_gate_name
            )
            self.EXIT_GATES_SIGNALS[each_exit_gate_name] = Signal(
                signal_type="InteractionProcessCompletedSignal", user_domain=self.user_domain,
                interaction=self.interaction,
                exit_gate=each_exit_gate_name)
Example #3
0
    def _connect_receptor(self, receptor_type, init_args, callback_fn):
        """Connects receptor to the system"""
        # ###########################################################
        from components.receptors.models import Receptor
        receptor, created = Receptor.get_or_create(class_name=receptor_type,
                                                   init_args=init_args)

        # udc.user_domain.user_message_signal.connect_receptor(receptor)
        from components.signal_pattern_reflex.signal_pattern import SignalPattern
        sp, _ = SignalPattern.get_or_create_strict(
            signal_type="UserMessageSignal")
        sp.connect(receptor.__call__)

        receptor_trigger_signal_pattern, _ = SignalPattern.get_or_create_strict(
            signal_type="ReceptorTriggeredSignal", receptor=receptor)
        receptor_trigger_signal_pattern.connect(callback_fn)
Example #4
0
    def connect_to_dataflow(self, udc):
        """
        makes preparations fpor particular UserDomain. Here we may attach special receptors for
        VIP Users

        Args:
            udc: UserDomainController
        """

        # ############### Prepare RECEPTOR #################################################
        # # this Interaction may be activated by Receptor (actually it is binary intent classifier here)
        # self.global_trigger_receptor = PhrasesMatcher(phrases=["ПОЗНАКОМИМСЯ", "ЗНАКОМСТВО"],
        #                                               daemon_if_matched=self.sfi.start)
        # # TODO Receptor has intrification of connection. Is it BAD? How to restore it?
        #
        # ##################### System Connection (must be redone on system restart) #############
        # # connect receptor:
        # udc.receptors_pool.connect(self.global_trigger_receptor)
        # # self.ic.user_message_signal.connect(self.global_trigger_receptor, weak=False)
        # self.ic.DialogPlanner.sendText("Добро пожаловать в мир глубокого обучения!")

        from components.receptors.models import Receptor
        # from components.signal_reflex_routes.models.signals import ReceptorTriggeredSignal
        receptor, created = Receptor.get_or_create(
            class_name='PhrasesMatcher',
            init_args={
                'phrases':
                ["Привет", "Здравствуйте", "Hello", "Kek", "Hi", "Приветик"]
            })

        #udc.user_domain.user_message_signal.connect_receptor(receptor)
        from components.signal_pattern_reflex.signal_pattern import SignalPattern
        sp, _ = SignalPattern.get_or_create_strict(
            signal_type="UserMessageSignal")
        udc.user_domain.user_message_signal_pattern.connect(receptor.__call__)
        # udc.user_domain.user_message_signal_pattern.connect(receptor.__call__)
        from components.signal_pattern_reflex.signal import Signal
        from components.signal_pattern_reflex.signal_pattern import SignalPattern
        receptor_trigger_signal_pattern, _ = SignalPattern.get_or_create_strict(
            signal_type="ReceptorTriggeredSignal", receptor=receptor)
        # import ipdb; ipdb.set_trace()
        #receptor_trigger_signal.connect_object_method(instance_locator=self, method_name='start')
        receptor_trigger_signal_pattern.connect(self.start)
Example #5
0
    def test_signal_pattern_get_or_create(self):
        # import ipdb; ipdb.set_trace()

        user_message_pattern1, created = SignalPattern.get_or_create_strict(
            signal_type="UserMessageSignal", user_domain=self.user_domain)
        user_message_pattern2, created2 = SignalPattern.get_or_create_strict(
            signal_type="UserMessageSignal", user_domain=self.user_domain)
        self.assertTrue(created)
        self.assertFalse(created2)

        user_message_pattern3, created3 = SignalPattern.get_or_create_strict(
            signal_type="UserMessageSignal1", user_domain=self.user_domain)
        self.assertTrue(created3)

        user_message_pattern4, created4 = SignalPattern.get_or_create_strict(
            signal_type="UserMessageSignal",
            user_domain=self.user_domain,
            receptor=self.receptor)
        self.assertTrue(created4)
Example #6
0
    def initialize(cls, ic, name=None, *args, **kwargs):
        """
        Interaction initialization requres:
        1. specify its name (And register it in the Interactions Registry)
        2. initilize EXIT GATES of the interaction.
            EXIT GATES are declared in implementation class, if not then default set of exit gates is assumed
            (the only: ExitGate_Ok)

        :param ic:
        :param name:
        :param args:
        :param kwargs:
        :return:
        """
        if not name:
            # default name is a name of class
            name = cls.__name__
        # import ipdb; ipdb.set_trace()

        intrctn = cls()

        intrctn.ic = ic

        # #########################################################################################
        # # Exit Gate Signals and Registry initialization
        intrctn.EXIT_GATES_SIGNALS = {}
        from components.signal_pattern_reflex.signal_pattern import SignalPattern
        intrctn.EXIT_GATES_SIGNAL_PATTERNS = {}

        if not hasattr(intrctn, 'EXIT_GATES_NAMES_LIST'):
            # TODO fix to support inheritance of ExitGates!
            # then import default Gates :
            intrctn.EXIT_GATES_NAMES_LIST = cls.base_EXIT_GATES_NAMES_LIST

        # now init signal objects for each exit gate:
        for each_exit_gate_name in intrctn.EXIT_GATES_NAMES_LIST:
            # create a signal object for each exit gate

            intrctn.EXIT_GATES_SIGNAL_PATTERNS[
                each_exit_gate_name], _ = SignalPattern.get_or_create_strict(
                    signal_type="InteractionProcessCompletedSignal",
                    interaction=intrctn,
                    exit_gate=each_exit_gate_name)
            intrctn.EXIT_GATES_SIGNALS[
                each_exit_gate_name] = django.dispatch.dispatcher.Signal(
                    providing_args=["userdialog"])

        intrctn._anti_garbage_collector_callbacks_list = []
        # END ExitGate Signals Initialization

        ########################################################################################
        intrctn.post_init_hook()

        return intrctn
Example #7
0
 def __init__(self):
     # Create the kernel and learn AIML files
     self.kernel = aiml.Kernel()
     # self.kernel._verboseMode = False
     self._load_scripts()
     from components.signal_pattern_reflex.signal_pattern import SignalPattern
     sp, _ = SignalPattern.get_or_create_strict(signal_type="UserMessageSignal")
     # import ipdb; ipdb.set_trace()
     # this connect must work in runtime, otherwise if we disable skill in Agent Configs it will
     # work anyway...
     # how to solve this problem? - only routes of enabled skills must trigger
     # sp.connect(self.process_step, weak=True, parent_skill=self.__name__)
     sp.connect(self.process_step)
Example #8
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # get or create NewUserMessage signal

        # self.slot_filled_signal = django.dispatch.dispatcher.Signal(
        #     providing_args=["user_slot_process", "results"])

        # from components.signal_reflex_routes.models.signals import SlotFilledSignal
        # if not self.target_uri:
        #     print(self)
        #     import ipdb; ipdb.set_trace()

        from components.signal_pattern_reflex.signal import Signal
        self.slot_filled_signal = Signal(signal_type="SlotFilledSignal",
                                         user_domain=self.user_domain)
        from components.signal_pattern_reflex.signal_pattern import SignalPattern
        self.slot_filled_signal_pattern, _ = SignalPattern.get_or_create_strict(
            signal_type="SlotFilledSignal",
            user_domain=self.user_domain,
            slot=self.slot)
Example #9
0
    def send(self, **signal_data):
        if self.data:
            # print(self.data)
            # merge signal_data and self.data
            # import ipdb; ipdb.set_trace()
            signal_data.update(self.data)

        # find relevant signal patterns that match
        sps = SignalPattern.filter_from_signal(**signal_data)
        print(f"Send Signal: {signal_data}")
        count = len(sps)
        print(f"Number of matched patterns for the Signal: {count}")

        srrs = SignalPatternReflexRoute.objects(signal_pattern__in=sps)
        print(f"Number of ReflexRoutes for the SignalPatterns: {srrs.count()}")
        # import ipdb; ipdb.set_trace()

        try:
            for each_srr in srrs:
                each_srr.call_reflex(**signal_data)

        except Exception as e:
            # potentialy this occurs in 2 cases:
            # if we have exception in reflex functor or
            import mongoengine

            if e.__class__ == mongoengine.errors.DoesNotExist:
                # when  reflex was deleted during the looping
                # previous reflexes (on /start event)
                # ok
                print(each_srr.id)
                print("Missed reflexRoute. Skipping silently")
                print(e)
                return

            else:
                print("Exception!")
                print(e)
                # import ipdb; ipdb.set_trace()
                print(e)
                raise e
Example #10
0
    def restart_userdomain(self):
        """
        Clean data from user domain to allow scenarios to be restarted
        Returns:

        """
        # delete user processes:
        from components.user_processes.user_slot_process import UserSlotProcess
        UserSlotProcess.objects(user_domain=self).delete()
        from components.user_processes.user_interaction_process import UserInteractionProcess
        UserInteractionProcess.objects(user_domain=self).delete()

        # remove signal patterns and reflexes
        from components.signal_pattern_reflex.signal_pattern import SignalPattern
        sps = SignalPattern.objects(user_domain=self)
        if sps:
            from components.signal_pattern_reflex.signal_pattern_reflex_route import SignalPatternReflexRoute
            SignalPatternReflexRoute.objects(signal_pattern__in=sps).delete()
            sps.delete()
        from components.signal_pattern_reflex.reflex import Reflex
        # from components.signal_pattern_reflex.reflex import Reflex, ObjectMethodReflex, ReceptorReflex
        reflexes = Reflex.objects(user_domain=self)
        if reflexes:
            # import ipdb; ipdb.set_trace()
            SignalPatternReflexRoute.objects(reflex__in=reflexes).delete()
            reflexes.delete()
        # import ipdb; ipdb.set_trace()

        # ObjectMethodReflex.objects(user_domain=self).delete()
        # ReceptorReflex.objects(user_domain=self).delete()

        # delete dialog to avoid prehistory recepts:
        from components.user_processes.user_interaction_process import UserInteractionProcess
        self.dialog.utterances = []
        self.dialog.save()
        self.memory = {}
        self.agenda.reset()
        self.save()

        return True
Example #11
0
    def connect_to_dataflow(self, ic):
        """
        Connection to DataFlow triggers the interaction to create Signals according
        to Interactions Interface
        Args:
            ic:

        Returns:

        """
        self.ic = ic
        self.EXIT_GATES_SIGNALS = {}
        from components.signal_pattern_reflex.signal_pattern import SignalPattern
        from components.signal_pattern_reflex.signal import Signal
        self.EXIT_GATES_SIGNAL_PATTERNS = {}

        if not hasattr(self, 'EXIT_GATES_NAMES_LIST'):
            # TODO fix to support inheritance of ExitGates!
            # then import default Gates :
            self.EXIT_GATES_NAMES_LIST = self.base_EXIT_GATES_NAMES_LIST

        # now init signal objects for each exit gate:
        for each_exit_gate_name in self.EXIT_GATES_NAMES_LIST:
            # create a signal object for each exit gate
            self.EXIT_GATES_SIGNAL_PATTERNS[
                each_exit_gate_name], _ = SignalPattern.get_or_create_strict(
                signal_type="InteractionProcessCompletedSignal", interaction=self,
                exit_gate=each_exit_gate_name
            )
            self.EXIT_GATES_SIGNALS[each_exit_gate_name] = Signal(signal_type="InteractionProcessCompletedSignal", interaction=self,
                exit_gate=each_exit_gate_name)

        self._anti_garbage_collector_callbacks_list = []
        # END ExitGate Signals Initialization

        self.post_init_hook()
Example #12
0
slot_obj = {}
slot_obj.start = {}
slot_obj.on_user_response = {}
user_slot_process = {}
user_slot_process.on_user_response = {}

interaction_obj1 = {}
interaction_obj1.start = {}
interaction_obj2 = {}
interaction_obj2.on_slot_filled = {}
interaction_obj2.start = {}

#  Global Connections Ideal Specification:
# Use cases:
# UserMessage Signal Patterns
SignalPattern(signal_type="UserMessageSignal",
              user_domain="*").connect(receptor)
SignalPattern(signal_type="UserMessageSignal",
              user_domain=user_domain).connect(receptor)
SignalPattern(signal_type="UserMessageSignal",
              text__contains="песня",
              user_domain="*").connect(receptor)
SignalPattern(signal_type="UserMessageSignal",
              user_domain=user_domain).connect(slot_obj.on_user_response)
SignalPattern(signal_type="UserMessageSignal",
              user_domain=user_domain).connect(
                  user_slot_process.on_user_response)
SignalPattern(signal_type="UserMessageSignal",
              user_domain="*").connect(bad_words_receptor)

# Receptor Triggered patterns:
SignalPattern(signal_type="ReceptorTriggeredSignal",
Example #13
0
 def user_message_signal_pattern(self):
     from components.signal_pattern_reflex.signal_pattern import SignalPattern
     sp, _ = SignalPattern.get_or_create_strict(signal_type="UserMessageSignal", user_domain=self)
     return sp