예제 #1
0
    def update_node(self, req: Node) -> Optional[Node]:
        if req.get_properties() is not None:
            properties = dict(
                (x, y) for x, y in req.get_properties().items() if y != "")
            if len(properties) > 0:
                builder = QueryBuilder()
                builder.match_by_id(req.get_id(),
                                    "n").set_values(req.get_properties(),
                                                    "n").add("RETURN n")
                _ = self._exec_query(builder.get())

        if req.get_relationships() is not None:
            relationships = dict((x, y)
                                 for x, y in req.get_relationships().items()
                                 if len(y) > 0)
            if len(relationships) > 0:
                builder = QueryBuilder()
                builder.match_by_id(req.get_id(), "n")

                counter: int = 0
                for _, value in relationships.items():
                    builder.add(
                        f"MATCH (m{counter}) WHERE ID(m{counter}) IN [{','.join((str(rel) for rel in value))}] "
                    )
                    counter += 1
                counter = 0
                for key, _ in relationships.items():
                    builder.add(f"MERGE (n)-[r{counter}:{key}]-(m{counter})")
                    counter += 1
                builder.add("RETURN n")

                _ = self._exec_query(builder.get())

        result_node = self.get_node_by_id(req.get_id())[0]  # node from result
        return result_node
예제 #2
0
 def update(self, request: Node) -> Optional[Node]:
     if self._ontology.__contains__(request.get_type(
     )) and request.get_id() >= 0:  # The class of Node is in ontology
         return self.update_node(request)
     print(f"No such type in ontology: the {request.get_type()} is missing"
           )  # Error
     return None
예제 #3
0
    def delete_properties_relationships(self, req: Node) -> bool:
        response = False

        if req.get_properties() is not None:
            properties = dict(
                (x, y) for x, y in req.get_properties().items() if y != "")
            if len(properties) > 0:
                builder = QueryBuilder()
                builder.match_by_id(req.get_id(), "n")

                for key, _ in properties.items():
                    if key != "name":
                        builder.add(f"REMOVE n.{key}")
                builder.add("RETURN n")

                result = self._exec_query(builder.get())
                if result:
                    response = True

        if req.get_relationships() is not None:
            relationships = dict((x, y)
                                 for x, y in req.get_relationships().items()
                                 if len(y) > 0)
            if len(relationships) > 0:
                builder = QueryBuilder()
                builder.match_by_id(req.get_id(), "n")

                counter: int = 0
                for key, value in relationships.items():
                    builder.add(
                        f"MATCH (n)-[r{counter}:{key}]-(m{counter}) WHERE ID(m{counter}) IN {value}"
                    )
                    counter += 1
                counter -= 1
                builder.add(f"DELETE r{counter}")
                while counter > 0:
                    counter -= 1
                    builder.add(f",r{counter}")
                builder.add("RETURN n")

                result = self._exec_query(builder.get())
                if result:
                    response = True

        return response
예제 #4
0
    def react(ctx: rs.ContextWrapper):
        """
        Retrieves memory node with the name, or creates a new one
        outputs a polite response.
        """
        onto: Ontology = mem.get_ontology()
        sess: Session = mem.get_session()
        inferred_answer = ctx[prop_answer]
        pred = ctx[prop_predicate]
        subject_path: str = ctx[prop_subject]
        if not subject_path:
            return rs.Resign()
        subject_node: Node = ctx[subject_path]
        assert inferred_answer

        if pred == "NAME":
            # If name was asked, it must be because the node is not yet persistent
            assert subject_node.get_id() < 0
            subject_node.set_name(inferred_answer)
            persistent_subject_node = retrieve_or_create_node(subject_node)
            # TODO: Workaround - see #83 - if this state would write to interloc:all,
            #  it would promise an interloc:all:pushed signal. This would be
            #  picked up by persqa:new_interloc.
            subject_node.set_node(persistent_subject_node)
            sess.update(subject_node)
            ctx[interloc.prop_persisted] = subject_node
        elif pred in PREDICATE_SET:
            relationship_type = onto.get_type(ONTOLOGY_TYPE_FOR_PRED[pred])
            relationship_node = Node(metatype=relationship_type)
            relationship_node.set_name(inferred_answer)
            relationship_node = retrieve_or_create_node(relationship_node)
            if relationship_node is not None:
                subject_node.add_relationships(
                    {pred: {relationship_node.get_id()}})
                sess.update(subject_node)

        ctx[rawio.prop_out] = verbaliser.get_random_successful_answer(
            pred).format(name=subject_node.get_name(), obj=inferred_answer)
        ctx[prop_predicate] = None
예제 #5
0
 def delete(self, request: Node) -> bool:
     if request.get_id() >= 0:
         return self.delete_properties_relationships(request)
     return False
예제 #6
0
def create_default_nodes():
    onto: Ontology = ravestate_ontology.get_ontology()
    sess = ravestate_ontology.get_session()

    organization_type = onto.get_type("Organization")
    city_type = onto.get_type("City")
    person_type = onto.get_type("Person")
    robot_type = onto.get_type("Robot")
    hobby_type = onto.get_type("Hobby")

    student_team_node = Node(metatype=organization_type)
    student_team_node.set_properties({"name": "roboy student team"})

    munich_node = Node(metatype=city_type)
    munich_node.set_properties({"name": "munich"})

    roboy_junior_node = Node(metatype=robot_type)
    roboy_junior_node.set_properties({
        "name":
        "roboy",
        "abilities":
        "talking to people,reading wikipedia,reading reddit",
        "skills":
        "tell jokes,tell fun facts about famous people and places,recognize you next time we meet,"
        "remember your name and our conversation",
        "speed_kmh":
        0,
        "full_name":
        "roboy junior",
        "birthdate":
        "08.03.2013",
        "conversation_id":
        "#bitch_boy",
        "sex":
        "male",
        "age":
        5
    })

    raf_node = Node(metatype=person_type)
    raf_node.set_properties({
        "name": "rafael",
        "full_name": "rafael hostettler"
    })

    lucy_node = Node(metatype=person_type)
    lucy_node.set_properties({"name": "lucy", "age": 6, "sex": "female"})

    reddit_node = Node(metatype=hobby_type)
    reddit_node.set_properties({"name": "reading reddit"})

    roboy_node = Node(metatype=robot_type)
    roboy_node.set_properties({
        "name":
        "roboy two",
        "skills":
        "telling jokes,telling fun facts,telling you about the famous people and places,doing the math",
        "abilities":
        "talk to people,recognize objects,show emotions,move my body,shake a hand,"
        "party like there is no tomorrow,surf the internet,answer your questions",
        "speed_kmh":
        0,
        "birthdate":
        "12.04.2018",
        "full_name":
        "roboy 2.0",
        "conversation_id":
        "#bitch_boy",
        "future":
        "become a robot rights advocate,help people and robots become friends,"
        "find the answer to the question of life the universe and everything,"
        "visit mars and other planets,become a music star,become a michelin star chef,"
        "get a robo pet,become as good as my father",
        "sex":
        "male",
        "age":
        "0"
    })

    tricycle_node = Node(metatype=hobby_type)
    tricycle_node.set_properties({"name": "riding a tricycle"})

    nodes = (student_team_node, munich_node, roboy_junior_node, raf_node,
             lucy_node, reddit_node, roboy_node, tricycle_node)

    for node in nodes:
        sess.create(node)

    roboy_junior_node.add_relationships({"HAS_HOBBY": {reddit_node.get_id()}})
    roboy_junior_node.add_relationships(
        {"MEMBER_OF": {student_team_node.get_id()}})
    roboy_junior_node.add_relationships({"CHILD_OF": {raf_node.get_id()}})
    roboy_junior_node.add_relationships({"LIVE_IN": {munich_node.get_id()}})
    raf_node.add_relationships(
        {"FRIEND_OF": {roboy_node.get_id(),
                       roboy_junior_node.get_id()}})
    raf_node.add_relationships({"WORK_FOR": {student_team_node.get_id()}})
    lucy_node.add_relationships(
        {"FRIEND_OF": {roboy_node.get_id(),
                       roboy_junior_node.get_id()}})
    roboy_node.add_relationships({"FROM": {munich_node.get_id()}})
    roboy_node.add_relationships({"SIBLING_OF": {roboy_junior_node.get_id()}})
    roboy_node.add_relationships(
        {"HAS_HOBBY": {tricycle_node.get_id(),
                       reddit_node.get_id()}})
    roboy_node.add_relationships({"MEMBER_OF": {student_team_node.get_id()}})
    roboy_node.add_relationships({"CHILD_OF": {raf_node.get_id()}})
    roboy_node.add_relationships({"LIVE_IN": {munich_node.get_id()}})

    for node in nodes:
        sess.update(node)
예제 #7
0
파일: __init__.py 프로젝트: Roboy/ravestate
        def recognize_faces(ctx: rs.ContextWrapper):
            """
            Activates with each incoming face data served by face oracle. Responsible for synchronizing the node of
            person in vision with the anonymous interlocutor node. Uses face oracle filter to organize the incoming data
            and find out the right person.
            """

            face_filter: FaceOracleFilter = ctx[prop_face_filter]
            faces: Faces = ctx[prop_subscribe_faces]

            # Push faces to face filter
            best_guess_changed = face_filter.push_message(faces)
            if best_guess_changed:
                current_best_guess: Person = face_filter.current_best_guess

                onto: Ontology = mem.get_ontology()
                sess: Session = mem.get_session()

                person_node = Node(metatype=onto.get_type("Person"))

                best_guess_id = current_best_guess.id
                face_vector = current_best_guess.face_vector
                if current_best_guess.is_known:

                    person_node_query = sess.retrieve(node_id=best_guess_id)
                    if person_node_query:
                        person_node = person_node_query[0]
                    else:
                        err_msg = "Person with id %s is not found in memory." % best_guess_id
                        logger.error(err_msg)
                        return
                else:
                    person_node.set_properties({
                        'face_vector':
                        face_vector,
                        'name':
                        interloc.ANON_INTERLOC_ID
                    })

                push = False

                # Check if there is any interlocutor. If necessary and pop the current node and push person node
                # instead.
                if any(ctx.enum(interloc.prop_all)):
                    interloc_node: Node = ctx[
                        f'interloc:all:{interloc.ANON_INTERLOC_ID}']

                    # If interloc and the person nodes are not same pop and push person node.
                    if not (interloc_node.get_id() == person_node.get_id()
                            ) or interloc_node.get_id() < 0:
                        # Remove the current interloc
                        logger.info('Popping current interlocutor')
                        popped_node = ctx.pop(
                            f'interloc:all:{interloc.ANON_INTERLOC_ID}')
                        assert popped_node == True
                        push = True
                    else:
                        # Update the face vector of the person already familiar with
                        save_face(ctx, interloc_node.get_id(),
                                  current_best_guess.face_vector)
                else:
                    push = True
                if push:
                    # Push the new interlocutor
                    ctx.push(parent_property_or_path=interloc.prop_all,
                             child=rs.Property(name=interloc.ANON_INTERLOC_ID,
                                               default_value=person_node))
                    logger.info(
                        f"Pushed node with id {person_node.id} to interloc:all"
                    )