예제 #1
0
    def process_question(self, sentence, current_speaker):
        self.question_handler.set_current_speaker(current_speaker)

        # 'stmts' contains a list of statement describing the current
        # 'interrogative state' of the interactor.
        answer, stmts, situation_id = self.question_handler.process_sentence(
            sentence)

        if stmts:
            self.add_stmts(stmts)
        else:
            logger.info("No statements produced")

        if answer:
            emotions.satisfied()
            logger.info(
                level_marker(level=2, color="yellow") + "Found: \n" +
                colored_print(str(answer), None, "magenta"))
        else:
            emotions.sorry()
            logger.info(
                level_marker(level=2, color="yellow") +
                "Couldn't find anything!")

        if sentence.data_type == W_QUESTION:
            self.output_sentence.extend(
                self.sfactory.create_w_question_answer(
                    sentence, answer, self.question_handler._current_speaker,
                    self.question_handler.get_query_on_field()))

        if sentence.data_type == YES_NO_QUESTION:
            self.output_sentence.extend(
                self.sfactory.create_yes_no_answer(sentence, answer))

        return stmts, situation_id
예제 #2
0
    def process_question(self, sentence, current_speaker):
        self.question_handler.set_current_speaker(current_speaker)

        # 'stmts' contains a list of statement describing the current 
        # 'interrogative state' of the interactor.
        answer, stmts, situation_id = self.question_handler.process_sentence(sentence)

        if stmts:
            self.add_stmts(stmts)
        else:
            logger.info("No statements produced")

        if answer:
            emotions.satisfied()
            logger.info(
                level_marker(level=2, color="yellow") + "Found: \n" + colored_print(str(answer), None, "magenta"))
        else:
            emotions.sorry()
            logger.info(level_marker(level=2, color="yellow") + "Couldn't find anything!")

        if sentence.data_type == W_QUESTION:
            self.output_sentence.extend(self.sfactory.create_w_question_answer(sentence,
                                                                               answer,
                                                                               self.question_handler._current_speaker,
                                                                               self.question_handler.get_query_on_field()))

        if sentence.data_type == YES_NO_QUESTION:
            self.output_sentence.extend(self.sfactory.create_yes_no_answer(sentence, answer))

        return stmts, situation_id
예제 #3
0
    def __str__(self):
        res = level_marker() + pprint(self.data_type, SENTENCE_TYPE)
        res += pprint(self.aim, SENTENCE_AIM)  # 'aim' may be None

        if self.sn:
            sn = ""
            for s in self.sn:
                sn = str(s).replace("\n", "\n\t") + "\n"
                res += pprint(sn, SUBJECT)
        if self.sv:
            for s in self.sv:
                res += str(s).replace("\n", "\n\t") + "\n"

        #res += "This sentence is " + ("fully resolved." if self.resolved() else "not fully resolved.")

        if self.isvalid():
            res = pprint(res, SENTENCE)
        else:
            res = pprint(res, AGRAMMATICAL_SENTENCE)
        return res
예제 #4
0
    def __str__(self):
        res = level_marker() + pprint(self.data_type, SENTENCE_TYPE)
        res += pprint(self.aim, SENTENCE_AIM) # 'aim' may be None

        if self.sn:
            sn = ""
            for s in self.sn:
                sn = str(s).replace("\n", "\n\t") + "\n"
                res += pprint(sn, SUBJECT)
        if self.sv:
            for s in self.sv:
                res += str(s).replace("\n", "\n\t") + "\n"

        #res += "This sentence is " + ("fully resolved." if self.resolved() else "not fully resolved.")

        if self.isvalid():
            res = pprint(res, SENTENCE)
        else:
            res = pprint(res, AGRAMMATICAL_SENTENCE)
        return res
예제 #5
0
    def __str__(self):

        res = level_marker()

        if self._conjunction != 'AND':
            res += pprint(self._conjunction, CONJUNCTION)

        if self._quantifier != 'ONE':
            res += pprint(self._quantifier, QUANTIFIER)

        if self._resolved:
            res += pprint(self.id, ID)
            res = pprint(res, RESOLVED)

        else:


            if self.det:
                res += pprint(" ".join(self.det), DETERMINER)

            for k in self.adj:
                if k[1]:
                    res += pprint(" ".join(k[1]), ADJECTIVE_QUALIFIER)
                res += pprint(k[0], ADJECTIVE)

            if self.noun:
                res += pprint(", ".join(self.noun), NOUN)

            if self.noun_cmpl:
                for s in self.noun_cmpl:
                    res += pprint(str(s).replace("\n", "\n\t"), NOUN_CMPLT)

            if self.relative:
                for rel in self.relative:
                    res += pprint(str(rel).replace("\n", "\n\t"), RELATIVE_GRP)

        return pprint(res, NOMINAL_GROUP)
예제 #6
0
    def __str__(self):

        res = level_marker()

        if self._conjunction != 'AND':
            res += pprint(self._conjunction, CONJUNCTION)

        if self._quantifier != 'ONE':
            res += pprint(self._quantifier, QUANTIFIER)

        if self._resolved:
            res += pprint(self.id, ID)
            res = pprint(res, RESOLVED)

        else:

            if self.det:
                res += pprint(" ".join(self.det), DETERMINER)

            for k in self.adj:
                if k[1]:
                    res += pprint(" ".join(k[1]), ADJECTIVE_QUALIFIER)
                res += pprint(k[0], ADJECTIVE)

            if self.noun:
                res += pprint(", ".join(self.noun), NOUN)

            if self.noun_cmpl:
                for s in self.noun_cmpl:
                    res += pprint(str(s).replace("\n", "\n\t"), NOUN_CMPLT)

            if self.relative:
                for rel in self.relative:
                    res += pprint(str(rel).replace("\n", "\n\t"), RELATIVE_GRP)

        return pprint(res, NOMINAL_GROUP)
예제 #7
0
    def process_sentence(self, sentence):
        """This processes a w_question or yes_no_question sentence"""
        self._sentence = sentence
        #StatementBuilder
        builder = StatementBuilder(self._current_speaker)
        self._statements, situation_id = builder.process_sentence(
            self._sentence)
        logger.info(
            level_marker(level=2, color="yellow") +
            "Generated statements based on the sentence components: " +
            colored_print(str(self._statements), None, "magenta"))

        #Case the question is a y_n_question : check the fact in the ontology
        if sentence.data_type == YES_NO_QUESTION:
            self._statements = self._set_situation_id(self._statements)
            logger.info(
                level_marker(level=2, color="yellow") +
                "Generated statements for this question: " +
                colored_print(str(self._statements), None, "magenta"))
            #Processing :Do you know something?
            if self.process_on_knowing_concept:
                #self._statements = [agent knows object]
                for s in self._statements:
                    self._answer = True

                    if "knows" in s:
                        [agent, object] = s.split(" knows ")

                        onto_lookup = []
                        logger.debug(
                            level_marker(level=2, color="yellow") +
                            "Looking up for " + object + " in " + agent +
                            "'s model")
                        onto_lookup = ResourcePool(
                        ).ontology_server.lookupForAgent(
                            ResourcePool().get_model_mapping(agent), object)

                        self._answer = self._answer and (True if onto_lookup
                                                         else False)

                self.process_on_knowing_concept = False
            else:
                logger.debug(
                    level_marker(level=2, color="yellow") +
                    "Checking in the ontology: " +
                    colored_print(str(self._statements), None, "magenta"))
                self._answer = ResourcePool().ontology_server.check(
                    self._statements)

        #Case the question is a w_question : find the concept the concept that answers the question
        if sentence.data_type == W_QUESTION:
            #
            self._query_on_field = self._set_query_on_field(sentence)
            statements_with_bound_tokens = self._remove_statements_with_no_unbound_tokens(
                self._statements)

            #Agent from which the ontology model is queried
            agent = self._default_agent

            self._answer = []

            #For all the possible subjects of a same question
            if not self._sentence.sn:
                statements_to_query = [
                    self._extend_statement_from_sentence_aim(
                        statements_with_bound_tokens)
                ]

            else:
                statements_to_query = [
                    self._extend_statement_from_sentence_aim(
                        statements_with_bound_tokens, sn)
                    for sn in self._sentence.sn
                ]

            for statements in statements_to_query:
                if self.process_on_knowing_concept:
                    #Get agent in a statement such as [agent knows object]
                    for s in statements:
                        if "knows" in s:
                            [agent, object] = s.split(" knows ")
                            break

                    #No need of statements such as [S knows O]
                    [statements.remove(s) for s in statements if "knows" in s]
                    self.process_on_knowing_concept = False

                if statements:
                    logger.info(
                        level_marker(level=2, color="yellow") +
                        "Generated statements for this question: " +
                        colored_print(str(self._statements), None, "magenta"))

                    answers = []
                    if self._process_on_location:

                        prepositions_list = ResourcePool(
                        ).preposition_rdf_object_property.copy()
                        roles = dict([(preposition, prepositions_list[preposition][0]) \
                                      for preposition in prepositions_list.keys() \
                                      if 'objectFoundInLocation' in prepositions_list[preposition]])

                        #Case of ojectFound in location
                        stmts = []
                        prepositions_already_used = []
                        for role in roles:
                            if roles[role] in prepositions_already_used:
                                continue

                            stmts = [
                                s.replace('objectFoundInLocation', roles[role])
                                for s in statements
                            ]

                            logger.debug(
                                level_marker(level=2, color="yellow") +
                                "Searching in " + agent + " model: " +
                                colored_print(str(stmts), None, "magenta"))
                            answers = ResourcePool(
                            ).ontology_server.findForAgent(
                                ResourcePool().get_model_mapping(agent),
                                '?concept', stmts)

                            prepositions_already_used.append(roles[role])

                            if answers:
                                ResourcePool().mark_active(answers)
                                self._answer.append([[role], answers])

                        #Case of object found in location + direction
                        stmts = [
                            s.replace('objectFoundInLocation', 'isAt')
                            for s in statements
                        ]
                        for role in ResourcePool().direction_words:
                            logger.debug(
                                level_marker(level=2, color="yellow") +
                                "Searching in " + agent + " model: " +
                                colored_print(
                                    str(stmts + [
                                        '?concept is' + role.capitalize() +
                                        'Of ?obj', '?concept rdf:type Location'
                                    ]), None, "magenta"))
                            answers = ResourcePool(
                            ).ontology_server.findForAgent(
                                ResourcePool().get_model_mapping(agent),
                                '?obj', stmts + [
                                    '?concept is' + role.capitalize() +
                                    'Of ?obj', '?concept rdf:type Location'
                                ])

                            if answers:
                                ResourcePool().mark_active(answers)
                                self._answer.append([[role], answers])

                    else:
                        logger.debug(
                            level_marker(level=2, color="yellow") +
                            "Searching in " + agent + " model: " +
                            colored_print(str(statements), None, "magenta"))
                        answers = ResourcePool().ontology_server.findForAgent(
                            ResourcePool().get_model_mapping(agent),
                            '?concept', statements)

                        if answers:
                            ResourcePool().mark_active(answers)
                            self._answer.append([[], answers])
                else:
                    pass

                self._statements.extend(statements)

        stmts, sit_id = self._build_situation_statements()
        return self._answer, stmts, sit_id
예제 #8
0
    def process_sentence(self, sentence):
        """This processes a w_question or yes_no_question sentence"""
        self._sentence = sentence
        #StatementBuilder
        builder = StatementBuilder(self._current_speaker)
        self._statements, situation_id = builder.process_sentence(self._sentence)
        logger.info(level_marker(level=2,
                                 color="yellow") + "Generated statements based on the sentence components: " + colored_print(
            str(self._statements), None, "magenta"))

        #Case the question is a y_n_question : check the fact in the ontology
        if sentence.data_type == YES_NO_QUESTION:
            self._statements = self._set_situation_id(self._statements)
            logger.info(
                level_marker(level=2, color="yellow") + "Generated statements for this question: " + colored_print(
                    str(self._statements), None, "magenta"))
            #Processing :Do you know something?
            if self.process_on_knowing_concept:
                #self._statements = [agent knows object]
                for s in self._statements:
                    self._answer = True

                    if "knows" in s:
                        [agent, object] = s.split(" knows ")

                        onto_lookup = []
                        try:
                            logger.debug(level_marker(level=2,
                                                      color="yellow") + "Looking up for " + object + " in " + agent + "'s model")
                            onto_lookup = ResourcePool().ontology_server.lookupForAgent(agent, object)
                        except AttributeError:
                            pass

                        self._answer = self._answer and (True if onto_lookup else False)

                self.process_on_knowing_concept = False
            else:
                try:
                    logger.debug(level_marker(level=2, color="yellow") + "Checking in the ontology: " + colored_print(
                        str(self._statements), None, "magenta"))
                    self._answer = ResourcePool().ontology_server.check(self._statements)
                except AttributeError: #the ontology server is not started of doesn't know the method
                    pass

        #Case the question is a w_question : find the concept the concept that answers the question
        if sentence.data_type == W_QUESTION:
            #
            self._query_on_field = self._set_query_on_field(sentence)
            statements_with_bound_tokens = self._remove_statements_with_no_unbound_tokens(self._statements)

            #Agent from which the ontology model is queried
            agent = self._default_agent

            self._answer = []

            #For all the possible subjects of a same question
            if not self._sentence.sn:
                statements_to_query = [self._extend_statement_from_sentence_aim(statements_with_bound_tokens)]

            else:
                statements_to_query = [self._extend_statement_from_sentence_aim(statements_with_bound_tokens, sn) for sn
                                       in self._sentence.sn]

            for statements in statements_to_query:
                if self.process_on_knowing_concept:
                    #Get agent in a statement such as [agent knows object]
                    for s in statements:
                        if "knows" in s:
                            [agent, object] = s.split(" knows ")
                            break

                    #No need of statements such as [S knows O]
                    [statements.remove(s) for s in statements if "knows" in s]
                    self.process_on_knowing_concept = False

                if statements:
                    logger.info(level_marker(level=2,
                                             color="yellow") + "Generated statements for this question: " + colored_print(
                        str(self._statements), None, "magenta"))

                    answers = []
                    if self._process_on_location:

                        prepositions_list = ResourcePool().preposition_rdf_object_property.copy()
                        roles = dict([(preposition, prepositions_list[preposition][0]) \
                                      for preposition in prepositions_list.keys() \
                                      if 'objectFoundInLocation' in prepositions_list[preposition]])

                        #Case of ojectFound in location
                        stmts = []
                        prepositions_already_used = []
                        for role in roles:
                            if roles[role] in prepositions_already_used:
                                continue

                            stmts = [s.replace('objectFoundInLocation', roles[role]) for s in statements]
                            try:
                                logger.debug(level_marker(level=2,
                                                          color="yellow") + "Searching in " + agent + " model: " + colored_print(
                                    str(stmts), None, "magenta"))
                                answers = ResourcePool().ontology_server.findForAgent(agent, '?concept', stmts)
                            except AttributeError: #the ontology server is not started of doesn't know the method
                                pass

                            prepositions_already_used.append(roles[role])

                            if answers:
                                ResourcePool().mark_active(answers)
                                self._answer.append([[role], answers])

                        #Case of object found in location + direction
                        stmts = [s.replace('objectFoundInLocation', 'isAt') for s in statements]
                        for role in ResourcePool().direction_words:
                            try:
                                logger.debug(level_marker(level=2,
                                                          color="yellow") + "Searching in " + agent + " model: " + colored_print(
                                    str(stmts + ['?concept is' + role.capitalize() + 'Of ?obj',
                                                 '?concept rdf:type Location']), None, "magenta"))
                                answers = ResourcePool().ontology_server.findForAgent(agent, '?obj', stmts + [
                                    '?concept is' + role.capitalize() + 'Of ?obj', '?concept rdf:type Location'])
                            except AttributeError: #the ontology server is not started of doesn't know the method
                                pass

                            if answers:
                                ResourcePool().mark_active(answers)
                                self._answer.append([[role], answers])

                    else:
                        try:
                            logger.debug(level_marker(level=2,
                                                      color="yellow") + "Searching in " + agent + " model: " + colored_print(
                                str(statements), None, "magenta"))
                            answers = ResourcePool().ontology_server.findForAgent(agent, '?concept', statements)
                        except AttributeError: #the ontology server is not started of doesn't know the method
                            pass

                        if answers:
                            ResourcePool().mark_active(answers)
                            self._answer.append([[], answers])
                else:
                    pass

                self._statements.extend(statements)

        stmts, sit_id = self._build_situation_statements()
        return self._answer, stmts, sit_id