Example #1
0
    async def run(
        self, dispatcher, tracker: Tracker, domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        
        school_id = extract_schoolid_from_tracker(tracker)
        logger.info("action_queryredis_csv") 
        if not school_id:
            dispatcher.utter_message(
                "Sorry 🤔 something is wrong.Please try again later."
            )
            return []
        context = tracker.get_slot("context")
        try:
            parent_button_list = get_parent_button(school_id)
        except ConnectionError as e:
            logger.error("Connection error to redis server Error Message{e}")
            dispatcher.utter_message(
                "Sorry 🤔 something is wrong.Please try again later."
            )
            return []
        

        parentbuttonlabel = list(parent_button_list.keys())
        parentbuttonpayload = list(parent_button_list.values())
        buttons = []
        if not parentbuttonlabel and not parentbuttonpayload:

            return [FollowupAction("action_bottom_top_menu")]

        # this loop generate button for parent i.e. button right after csv
        for button_label, button_id in zip(
            parentbuttonlabel, parentbuttonpayload
        ):
            payload = {
                "buttonid": button_id,
                "new_action": "action_queryredisid",
            }
            payload = json.dumps(payload)
            buttons.append(
                {"title": f"{button_label}", "payload": f"/router{payload}"}
            )

        # find previous context before current context "schoolinfo" from csv and take contol to action_help_menu for back button
        help_context = help_db[help_db["context"] == context]

        context = help_context.prev_context_leaf.values[0]

        backbuttonpayload = {
            "buttonid": None,
            "context": context,
            "new_action": "action_help_menu",
        }
        backbuttonpayload = json.dumps(backbuttonpayload)
        buttons.append(
            {"title": "Back", "payload": f"/router{backbuttonpayload}"}
        )
        dispatcher.utter_message(text="This is what I have", buttons=buttons)

        return [FollowupAction("action_listen")]
Example #2
0
def extract_url_from_tracker(tracker):
    events = tracker.current_state()["events"]
    for e in reversed(events):
        if e["event"] == "user":
            metadata = e["metadata"]
            try:
                logger.info(f"Rest Url{metadata['rest_url']} sent from frontend sucessfully.")
                return metadata["rest_url"]
            except KeyError as e:
                logger.error(f"Rest URL not sent from frontend ErrorMessage:{e}")
                return None
Example #3
0
def extract_schoolid_from_tracker(tracker):
    events = tracker.current_state()["events"]
   

    for e in reversed(events):
        if e["event"] == "user":
            metadata = e["metadata"]
            try:
                logger.info(f"schoolid {metadata['schoolId']} sent from frontend sucessfully.")
                return metadata["schoolId"]
            except KeyError as e:
                logger.error(f"SchoolId not sent from frontend ErrorMessage:{e}")
                return None
Example #4
0
def api_reader(url, params=None, httpmethod="get", data=None, tracker=None):
    headers = extract_headers_from_tracker(tracker)
    fullurl = extract_url_from_tracker(tracker) + "/" + url
    try:
        if httpmethod == "get":
            response = requests.get(fullurl, params=params, headers=headers)
        else:
            response = requests.post(fullurl, headers=headers, json=data)
        logger.success(
            f"api call on fullurl {response.request.url} done sucessfully"
        )
        return response.json()
    except Exception as e:
        logger.error(f"Api call on url {fullurl} Failed")
Example #5
0
def extract_headers_from_tracker(tracker):
    events = tracker.current_state()["events"]
    for e in reversed(events):
        if e["event"] == "user":
            metadata = e["metadata"]
            try:
                headers = {
                    key: metadata[key]
                    for key in ["Authorization", "Origin", "idToken"]
                }
                logger.info("Header is sent from frontend successfully.")
                return headers
            except KeyError:
                logger.error("Header not sent from frontend")
                return None
Example #6
0
    async def run(
        self, dispatcher, tracker: Tracker, domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
    
        logger.info("action_queryredisid")
        parentid = tracker.get_slot("buttonid")
        try:
            button_obj = read_obj(parentid)
        except ConnectionError:
            logger.error("Connection error to redis server Error Message{e}")
            dispatcher.utter_message("Sorry 🤔 something is wrong.Please try again later.")
        # button_obj = read_obj(parentid)  # Only None when we are in parent node
        
        if not button_obj:
            return [
                FollowupAction("action_router"),
                SlotSet("new_action", "action_queryredis_csv"),
                SlotSet("context", "School Info"),
            ]
        message_list = []

        if button_obj.get("answerTypes"):

            answer_type = ast.literal_eval(button_obj.get("answerTypes"))
            for p in answer_type:
                

                if p["type"] == "text":
                    message = p.get("text")
                    message = random.choice(message)
                    message_info = {"type": "text", "msg": message}

                    message_list.append(message_info)
                else:
                    message = p.get("uri")
                    message = random.choice(message)
                    message_info = {"type": "uri", "msg": message}
                    message_list.append(message_info)
                    
       

        backbutton_payload = {
            "buttonid": button_obj.get("parent"),
            "new_action": "action_queryredisid",
        }
        backbutton_payload = json.dumps(backbutton_payload)

        child_button_id = ast.literal_eval(button_obj.get("children"))
        if not child_button_id:
            for message in message_list:
                if message["type"] == "text":
                    text = message["msg"]
                    

                    dispatcher.utter_message(text=text)

                else:
                    attachment = message["msg"].rsplit("/", 1)[-1]
                    buttons_list = []
                    logger.info(f"attachment is {attachment} ")

                    payload = f"{message['msg']}"
                    payload = json.dumps(payload)
                    buttons_list.append(
                        {"title": attachment, "payload": f"{payload}/link",}
                    )
                    dispatcher.utter_message(
                        text="Please click the following link",
                        buttons=buttons_list,
                    )
            return [FollowupAction("action_top_menu_nlu")]
           

        buttons = []
        for childid in child_button_id:
            button_obj = read_obj(childid)
            button_label = button_obj.get("label")
            payload = {
                "buttonid": childid,
                "new_action": "action_queryredisid",
            }
            payload = json.dumps(payload)
            buttons.append(
                {"title": f"{button_label}", "payload": f"/router{payload}"}
            )
        buttons.append(
            {"title": "Back", "payload": f"/router{backbutton_payload}"}
        )
       

        for message in message_list:
            if message["type"] == "text":
                text = message["msg"]
                dispatcher.utter_message(text)
            else:
                attachment = message["msg"].rsplit("/", 1)[-1]

                logger.info(f"attachment is {attachment} ")
                buttons_list = []
                payload = f"{message['msg']}"
                payload = json.dumps(payload)

                buttons_list.append(
                    {"title": f"{attachment}", "payload": f"{payload}/link"}
                )
                dispatcher.utter_message(
                    text="Please click the following link",
                    buttons=buttons_list,
                )

        dispatcher.utter_message(text="Select from below", buttons=buttons)
        return []
Example #7
0
def search_query_fallback(query, schoolId):
    try:
        query_vector = t.encode(query)
        logger.info("Connected to Transformer as a service server")

    except Exception as e:
        logger.error(f"Cannot connect to taas server. ErrorMessage: {e}")
        return None

    try:

        script_query = {
            "script_score": {
                "query": {
                    "bool": {
                        "filter": [
                            # {"term": {"helpDeskIntent.keyword": helpDeskIntent}},
                            {
                                "term": {
                                    "schoolId": schoolId
                                }
                            },
                        ]
                    }
                },
                "script": {
                    "source":
                    "cosineSimilarity(params.query_vector, doc['question_vector']) + 1.0",
                    "params": {
                        "query_vector": query_vector
                    },
                },
            }
        }

        response = es.search(
            index=INDEXNAME,  # name of the index
            body={
                "size": 3,
                "query": script_query,
                "_source": {
                    "includes": [
                        "question",
                        "objectId",
                        "helpDeskIntent",
                        "label",
                    ]
                },
            },
        )
        logger.info("Connected to Elastic search")

    except Exception as e:
        logger.error(f"Cannot cannect to es server .ErrorMessage: {e}")
        return None

    try:
        if response["hits"]["max_score"] > 1.8:
            objectid = response["hits"]["hits"][0]["_source"]["objectId"]
            return objectid
        else:
            buttonids = []
            labels = []
            for p in response["hits"]["hits"]:
                buttonids.append(p["_source"]["objectId"])
                labels.append(p["_source"]["label"])
            buttonids = list(OrderedSet(buttonids))
            labels = list(OrderedSet(labels))
            return zip(buttonids, labels)

    except Exception as e:
        logger.error("ErrorMessage: {e}")
        return None