Exemplo n.º 1
0
    def login(self, command, data):
        username = data.get("username", None)
        authToken = data.get("authToken", None)

        if username is not None and authToken is not None:
            col = mongo.get_column("users")
            col.insert_one({"username": username, "authToken": authToken})
Exemplo n.º 2
0
def new_dialogue(dialogueID,
                 topic,
                 content=None,
                 auth_token=None,
                 agents=None):
    """
    Track a new dialogue, generating a temporary session ID
    """
    if agents is None:
        agents = {}

    session_id = str(uuid.uuid4())

    dialogue = {
        "sessionID": session_id,
        "topic": topic.lower(),
        "content": content,
        "authToken": auth_token,
        "agents": agents
    }

    col = mongo.get_column("dialogues")
    result = col.find_one({"dialogueID": dialogueID})

    if result:
        dialogue_data = {"content": content, "agents": agents}
        col.update_one({"dialogueID": dialogueID},
                       {"$set": {
                           "dialogueData": dialogue_data
                       }})

    #col.insert_one(dialogue)

    return session_id
Exemplo n.º 3
0
def get_user(username):
    col = mongo.get_column("users")
    result = col.find_one({"username": username})

    if result is not None:
        return dict(result)
    else:
        return None
Exemplo n.º 4
0
    def save_dialogue(self):
        """
        Save the current dialogue state to mongo
        """
        dialogueID = self.dialogue["dialogueID"]

        col = mongo.get_column("dialogues")
        result = col.replace_one({"dialogueID": dialogueID},
                                 self.dialogue,
                                 upsert=True)
Exemplo n.º 5
0
def set_dialogue_id(session_id, dialogue_id):
    """
    Set the DGEP dialogue ID for the dialogue with the given session ID
    """
    col = mongo.get_column("dialogues")

    result = col.update_one({"sessionID": session_id},
                            {"$set": {
                                "dialogueID": dialogue_id
                            }})
Exemplo n.º 6
0
    def login(self, command, data):
        username = data.get("username", None)
        authToken = data.get("authToken", None)

        if username is not None and authToken is not None:
            query = {"username": username}
            col = mongo.get_column("users")
            result = col.find_one(query)

            if result is None:
                col.insert_one(data)
            else:
                col.update(query, {"$set": {"authToken": authToken}})
Exemplo n.º 7
0
    def handle_new(self, command, data):
        if "platform" in data:
            query = {"platform": data.get("platform")}
        else:
            query = {}

        to_return = []

        col = mongo.get_column("dialogue_topics")
        result = col.find(query, {"_id": False})

        if result:
            to_return = [r for r in result]

        return to_return
Exemplo n.º 8
0
    def create_content(self, command, data):
        """
        Create content in the DAF
        The "data" field should be in the form:
        {"type":str,"content":{}}
        """

        type = data.get("type", None)

        if type is not None and type not in _protected:
            col = mongo.get_column(type)
            content = data.get("content", {})
            col.insert_one(content)
            return {"status": "OK"}
        else:
            return {"status": "error", "message": "Invalid 'type'"}
Exemplo n.º 9
0
    def load_dialogue(self, dialogueID):
        """
        Load a dialogue with the given dialogueID

        :param dialogueID: the dialogue ID to load
        :type dialogueID: str
        :return: the loaded dialogue
        :rtype: dict
        """
        if dialogueID is None:
            self.dialogue = {}
        else:
            col = mongo.get_column("dialogues")
            result = col.find_one({"dialogueID": dialogueID})
            self.dialogue = result
        return self.dialogue
Exemplo n.º 10
0
    def handle_new(self, command, data):
        topic = data.get("topic", None)
        platform = data.get("platform", None)

        to_return = {}

        if topic is not None and platform is not None:
            col = mongo.get_column("dialogue_topics")
            col.insert_one(data)

            to_return["status"] = "OK"
        else:
            to_return["status"] = "error"
            to_return["message"] = "'topic' and 'platform' required"

        return to_return
Exemplo n.º 11
0
def init():
    # the internal listener is a little different; we can't decorate the handler class
    # because we only know the available platforms at runtime. So we do it manually,
    # directly accessing the daf decorator functions

    col = mongo.get_column("dialogue_topics")
    result = col.find({})

    if result:
        for r in result:
            if "platform" in r:
                destination = r["platform"] + "/response"
                daf.message_handler(destination,
                                    respond=False)(ResponseHandler)()
                destination = r["platform"] + "/dialogue_moves"
                daf.message_handler(destination,
                                    respond=False)(ResponseHandler)()
Exemplo n.º 12
0
def get_entry(dialogue_id, entry, parameters=None):
    """
    Get an entry from the dictionary for the given statement
    """

    content_id = dialogue.get_content_id(dialogue_id)

    to_return = []
    if parameters is None:
        parameters = []

    dictionary = {}
    auth_token = dialogue.get_auth_token(dialogue_id)

    result = mongo.get_column("dictionary").find({"contentID": content_id})

    if result:
        for r in result:
            for key, value in r.get("entries", {}).items():
                _term = term.get_term_specification(key)
                t = variable_manager.insert_values(auth_token, _term[0])
                dictionary[t] = {"variables": _term[2], "statements": value}

    if entry in dictionary:
        entry = dictionary[entry]

        variables = entry["variables"]
        mapping = dict(zip(variables, parameters))

        # give default values to parameters not assigned
        mapping.update({a: a for a in variables if a not in mapping})

        for statement in entry.get("statements", []):
            text = statement["text"]
            for key, value in mapping.items():
                text = text.replace("${}".format(key), value)

            text = variable_manager.insert_values(auth_token, text)

            to_return.append({
                "text": text,
                "properties": statement["properties"]
            })

    return to_return
Exemplo n.º 13
0
    def export_content(self, command, data):
        """
        Export content from the DAF
        The "data" field should be in the form:
        {"type":str,"query":{}}
        where "query" is a mongodb style query
        """

        if "type" in data:
            col = mongo.get_column(data["type"])
            query = data.get("query", {})

            if type(query) is dict:
                result = col.find(query, {"_id": False})

                if result:
                    return {"content": list(result)}

        return {}
Exemplo n.º 14
0
    def __init__(self, *args, **kwargs):
        self.dialogue_id = kwargs["dialogue_id"]
        self.speaker = kwargs["speaker"]

        self.argument_model = {}

        self.history = kwargs["history"]

        # if self.speaker is not None:
        #     col = mongo.get_column("dialogues")
        #     result = col.find_one({"dialogueID": self.dialogue_id})
        #
        #     if result is not None and self.speaker in result["agents"]:
        #         self.argument_model = result["agents"][self.speaker]["knowledge"]

        col = mongo.get_column("argument_models")
        result = col.find_one({"contentID": "abc"})

        self.argument_model = result["model"]
        self.rule_regex = re.compile(r"(\[(?:[^\[\]]+)\])[ ]*(.*)")
        self.theory = self.build_theory()
Exemplo n.º 15
0
    def handle_interaction(self, command, data):
        """
        Command handler for interactions; mostly sends on to DGEP
        but if in test mode then the "vars" field might be present, which
        we need to strip off and handle
        """
        if os.getenv("testvars", "False") == "True":
            col = mongo.get_column("test_variables")
            for var_name, spec in data.get("vars", {}).items():
                value = spec.get("value", "")
                result = col.find_one({"name": var_name}, {"_id": False})
                if result:
                    if spec.get("append", False) == True:
                        current_value = result["value"]
                        if type(current_value) is list:
                            value = current_value + [value]
                        else:
                            value = [current_value, value]

                query = {"name": var_name}
                update = {"$set": {"value": value}}
                col.update_one(query, update, upsert=True)

        return data  # sends data to DGEP
Exemplo n.º 16
0
def get_dialogue(dialogue_id):
    """
    Get the dialogue with the given ID
    """
    col = mongo.get_column("dialogues")
    return col.find_one({"dialogueID": dialogue_id})
Exemplo n.º 17
0
    def logout(self, command, data):
        username = data.get("username")

        if username is not None:
            col = mongo.get_column("users")
            col.delete_one({"username": username})
Exemplo n.º 18
0
    def handle_new(self, command, data):
        """
        Handle "new" commands
        """
        dialogueID = data.get("dialogueID", None)
        username = data.get("username", None)
        topic = data.get("topic", None)
        participants = data.get("participants", None)

        col = mongo.get_column("users")
        user_data = col.find_one({"username": username})

        if user_data is None:
            return {"error": "user is not authorised"}

        if dialogueID is not None and username is not None and topic is not None and participants is not None:
            authToken = user_data.get("authToken", None)
            topic = topic.lower()

            # get the "lead" agent: should be the first in the list
            agent = None

            for p in participants:
                if p["player"].lower() == "agent":
                    agent = p["name"].lower()
                    break

            if authToken is None or agent is None:
                return {"error": "User is not authorised"}

            participants_new = []
            participants_data = {"user": None, "agents": []}
            agent_count = 0

            i = 1
            for p in participants:
                participants_new.append({
                    "name": p["name"],
                    "participantID": i
                })
                i = i + 1

                player = p.get("player", "").lower()
                if player == "user":
                    participants_data["user"] = p.get("name", "User")
                elif player == "agent":
                    agent_count = agent_count + 1
                    participants_data["agents"].append(
                        p.get("name", "Agent{}".format(str(agent_count))))

            self.dialogue = {
                "platform": "WOOL",
                "dialogueID": dialogueID,
                "authToken": authToken,
                "dialogueData": {
                    "participants": participants_data,
                    "terminal_moves": []
                }
            }

            values = []

            for params in data.get("utteranceParams", []):
                if params.get("participant", "").lower() == agent:
                    values = params.get("parameters",
                                        {}).get("content_mandatory_values", [])
                    values.extend(
                        params.get("parameters",
                                   {}).get("content_avoid_values", []))
                    break

            # concrete_topic = self.get_topic(topic, participants)

            concrete_topic = self.get_potential_dialogues(agent, topic, values)

            if len(concrete_topic) == 0:
                return {}
            else:
                concrete_topic = concrete_topic[0]

            if concrete_topic is None:
                return {}

            move_data = self.start_dialogue(concrete_topic, agent)

            if move_data is None:
                return {}

            self.dialogue["dialogueData"]["moveData"] = move_data
            self.save_dialogue()

            response = {
                "dialogueID": dialogueID,
                "moves":
                self.dialogue["dialogueData"]["moveData"].get("moves", {}),
                "participants": participants_new,
                "clearvars": []
            }

            return response

        return {}