Ejemplo n.º 1
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        global label_to_idx, intent_tracker

        logging.info("Action check intent invoked")

        conversation_tracker = tracker.events_after_latest_restart()
        for item in reversed(conversation_tracker):
            if item["event"] == "user":
                intent_code = label_to_idx[item["parse_data"]["intent"]["name"]]
                if intent_code in intent_tracker:
                    dispatcher.utter_message("As I mentioned before")
                else:
                    intent_tracker.add(intent_code)
            # Break because we only want the last user intent
            break
        
        return  []
    def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[EventType]:

        # Calculate Fatigue based on the conversation lenght
        conv_turns = 0
        # conv_turns = tracker.get_slot("conv_turns")
        # action_counter = 0
        user_event_list = []
        for events in tracker.events_after_latest_restart():

            if events["event"] == "user":
                user_event_list.append(events)
                conv_turns += 1

        # logger.debug(f"This is the tracker after restart:
        # {tracker.events_after_latest_restart()}")
        # logger.debug(f"There has been these events from
        # user so far: {user_event_list}")
        # logger.debug(f"There has been
        # {conv_turns} turns in this conversation so far!")

        # Calculate confusion based on jumping from one intent to another
        # Grouping the intents based on their similarity in context
        distanced_intent_list = [[
            "greet", "bye", "nicetomeetyou", "restart", "ask_builder",
            "ask_howbuilt", "ask_isbot", "ask_ishuman", "ask_languagesbot",
            "ask_whoisit", "ask_howdoing", "ask_howold", "ask_wherefrom",
            "ask_whatismyname", "ask_whoami", "ask_restaurant", "ask_time",
            "ask_weather", "telljoke", "handleinsult"
        ],
                                 [
                                     "whatisPAYbank", "product_description",
                                     "howtoapply", "application_requirements",
                                     "required_age", "cardlimit",
                                     "points_collect", "annualcost"
                                 ],
                                 [
                                     "transfer_money", "pay_cc",
                                     "ask_transfer_charge",
                                     "search_transactions", "check_balance",
                                     "check_earnings", "check_recipients",
                                     "inform"
                                 ]]

        # get the ranking of the last user message
        last_intent_ranking = user_event_list[-1].get("parse_data", []).get(
            "intent_ranking", [])

        # get the name of the matched intent for last user message
        last_intent_name = last_intent_ranking[0].get("name")

        # get the text of the last user message
        last_user_message = user_event_list[-1].get("text")

        # get the ranking of the second last user message
        second_last_intent_ranking = user_event_list[-2].get(
            "parse_data", []).get("intent_ranking", [])

        # get the name of the matched intent for second last user message
        second_last_intent_name = second_last_intent_ranking[0].get("name")

        # get the text of the second last user message
        second_last_user_message = user_event_list[-2].get("text")

        # logger.debug(f"Last intent name is: {last_intent_name}, and the \
        #  intent before last is: {second_last_intent_name}")

        for list in distanced_intent_list:
            if last_intent_name in list:
                index_1 = distanced_intent_list.index(list)
                logger.debug(f"{last_intent_name} is in group {index_1}.")
            else:
                index_1 = None

            if second_last_intent_name in list:
                index_2 = distanced_intent_list.index(list)
                logger.debug(
                    f"{second_last_intent_name} is in group {index_2}.")
            else:
                index_2 = None

        confusion_level = 0
        if index_1 is not None and index_2 is not None:
            if index_1 != index_2:
                confusion_level += 1
                logger.debug(f"The confusion level is: {confusion_level}")

        # if conv_turns <= 6:
        #     return [FollowupAction("action_repair_options")]
        # elif conv_turns > 6:
        #     dispatcher.utter_message(template="utter_fatigue")
        #     return [FollowupAction("action_listen")]
        # return[]

        intent_ranking = tracker.latest_message.get("intent_ranking", [])
        if len(intent_ranking) > 1:
            highest_ranked_intent_confidence = intent_ranking[0].get(
                "confidence")
            # highest_ranked_intent_name = intent_ranking[0].get("name")
            if highest_ranked_intent_confidence >= 0.75:
                if conv_turns <= 10:
                    # bot is not tired, and is somehow sure about the intent.
                    if confusion_level < 1:
                        # bot is not foncused
                        message_title = f"I'm Highly confident that you mean \
                            {last_intent_name}."

                    else:
                        # bot is confused
                        message_title = f"I'm Highly confident what you mean by: \
                            {last_user_message}. But before that you said: \
                             {second_last_user_message}. Switching between \
                             topics like this can confuse me in future. "

                else:
                    # bot is tired, and is somehow sure about the intent.
                    if confusion_level < 1:
                        # bot is not confused
                        message_title = f"I'm Highly confident what you mean by: \
                            {last_user_message}. But our conversation is \
                            getting long and I'm tired. Sorry."

                    else:
                        # bot is confused
                        message_title = f"I'm Highly confident what you mean by: \
                            {last_user_message}. But before that you said: \
                             {second_last_user_message}. Switching between \
                             topics like this can confuse me in future. \
                             Our conversation is also getting long \
                             and I'm tired. Sorry."

            else:
                if conv_turns <= 10:
                    # bot is not tired, and is not sure about the intent.
                    if confusion_level < 1:
                        # bot is not foncused
                        message_title = f"I'm not so sure about what you mean by: \
                            {last_user_message}."

                    else:
                        # bot is confused
                        message_title = f"I'm not so sure about what you mean by: \
                            {last_user_message}. But before that you said: \
                             {second_last_user_message}. Switching between \
                             these topics confused me."

                else:
                    # bot is tired, and is not sure about the intent.
                    if confusion_level < 1:
                        # bot is not confused
                        message_title = f"I'm not so sure about what you mean by: \
                            {last_user_message}. Our conversation is \
                            getting long and I'm tired. Maybe that's \
                            why I can't get you. Sorry."

                    else:
                        # bot is confused
                        message_title = f"I'm not so sure about what you mean by: \
                            {last_user_message}. But before that you said: \
                            {second_last_user_message}. Switching between \
                            these topics confused me. \
                            Our conversation is also getting long and I'm \
                            tired. Could be also why I can't get you. Sorry."

        dispatcher.utter_message(text=message_title)
        return [FollowupAction("action_listen")]
Ejemplo n.º 3
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        logging.info("Action last intent invoked")

        what = tracker.events_after_latest_restart()

        print(what)
	
        last_item=what[-5] 
        last_item=str(last_item)
        #print(last_item)
		
        substr0="name"       
        inilist0=[m.start() for m in re.finditer(r"name",last_item)]
        name_counter_lastelement=inilist0[0]
        last_item=last_item[name_counter_lastelement:]
        
        print(last_item)

        inilist4=[m.start() for m in re.finditer(r"confidence",last_item)]
        confidence_counter_lastelement=inilist4[0]
        last_item=last_item[:confidence_counter_lastelement]
        print(last_item)

        last_item=last_item[8:]
        last_item = last_item.partition("'")[0]
        print("  THE FINAL LAST_ITEM IS")
        print(last_item)
		
        if last_item=="follow_up":
            #print(*what,sep="\n\n\n")
            last_item=what[-9] 
            #print(last_item)
            last_item=str(last_item)
            #print(last_item)
            inilist0=[m.start() for m in re.finditer(r"name",last_item)]
            name_counter_lastelement=inilist0[0]
            last_item=last_item[name_counter_lastelement:]
       
            inilist4=[m.start() for m in re.finditer(r"confidence",last_item)]
            confidence_counter_lastelement=inilist4[0]
            last_item=last_item[:confidence_counter_lastelement]
        		
            last_item=last_item[8:]
            last_item = last_item.partition("'")[0]
            ini_str=last_item
            print("  THE INI_STR IS")
            print(ini_str)
            if ini_str=='site':
                dispatcher.utter_message("As I said earlier, the pain is in my right knee.")
            elif ini_str=="exacerbating_factors":
                dispatcher.utter_message("As mentioned before doctor, the pain is not subsiding, medicinal creams were also not helpfull.")
            elif ini_str=="associated_factors":
                dispatcher.utter_message("As I said earlier,I haven't noticed any symptoms. It starts when I walk alot.")
            elif ini_str=="character":
                dispatcher.utter_message("As I said earlier,The pain is really sharp and at times unbearable. I have to do hot compression in order to provide a little relief.")
            elif ini_str=="problem_start":
                dispatcher.utter_message("As I said earlier,The pain started almost a week back.")
            elif ini_str=="what_problem":
                dispatcher.utter_message("As I said earlier, my knee hurts. It's usually the right knee that always pains.")
            elif ini_str=="radiation":
                dispatcher.utter_message("As I said earlier,the pain is everywhere in my knee. It doesn't subsides or moves anywhere else.")
            elif ini_str=="severity":
                dispatcher.utter_message("As I said earlier,the pain is quite severe doctor. I am unable to walk even for five minutes once the pain starts. It escalates very quickly.")
            elif ini_str=="movements":
                dispatcher.utter_message("As I mentioned, I do a lot of running and other cardio exercises. I also lift heavy weights.")
            elif ini_str=="problem_before":
                dispatcher.utter_message("As I mentioned,I haven't experianced this pain ever before.")
            elif ini_str=="name":
                dispatcher.utter_message("As I mentioned,I am 22 years old and I have a very active and healthy lifestyle. I don't have any history of diseases or bone problems.")
            elif ini_str=="medications":
                dispatcher.utter_message("As I mentioned,I have paracetamol as pain killer at times since the pain is unbearable. When pain killers are not needed I apply some pain reducing cream.")
			
                   
        elif last_item=='site':
            dispatcher.utter_message("The pain is in my right knee.")
        elif last_item=="exacerbating_factors":
            dispatcher.utter_message("No doctor, the pain is nt reducing, I tried rubbing medicinal creams and even did hot compression yet no improvement.")
        elif last_item=="associated_factors":
            dispatcher.utter_message("I haven't noticed any symptoms. It starts anytime when I walk alot.")
        elif last_item=="character":
            dispatcher.utter_message("The pain is really sharp and at times unbearable. I have to do hot compression in order to provide a little relief.")
        elif last_item=="problem_start":
            dispatcher.utter_message("The pain started like almost a week back, I can't remember the exact date but I am sure that it hasn't been more than a week.")
        elif last_item=="what_problem":
            dispatcher.utter_message("Doctor my knee hurts. It's usually the right knee that always pains.")
        elif last_item=="radiation":
            dispatcher.utter_message("The pain is everywhere in my knee. It doesn't subsides or moves anywhere else.")
        elif last_item=="severity":
            dispatcher.utter_message("It's quite severe doctor. I am unable to walk even for five minutes once the pain starts. It escalates very quickly.")
        elif last_item=="movements":
            dispatcher.utter_message("I do a lot of running and other cardio exercises. I also lift heavy weights.")
        elif last_item=="problem_before":
            dispatcher.utter_message("No ! I haven't experianced this pain ever before.")
        elif last_item=="name":
            dispatcher.utter_message("I am 22 years old and I have a very active and healthy lifestyle. I don't have any history of diseases or bone problems.")
        elif last_item=="medications":
            dispatcher.utter_message("I have paracetamol as pain killer at times since the pain is unbearable. When pain killers are not needed I apply some pain reducing cream.")
        else:
            print(last_item)
				
        return []