예제 #1
0
    def test_list_matches_no_template(self):
        global total_str

        topic = PatternOneOrMoreWildCardNode("*")
        word1 = PatternWordNode("Hi")
        word2 = PatternWordNode("There")
        context = MatchContext(max_search_depth=100,
                               max_search_timeout=60,
                               template_node=PatternTemplateNode(
                                   TemplateWordNode("Hello")),
                               sentence="HELLO",
                               response="Hi there")
        context.add_match(Match(Match.TOPIC, topic, None))
        context.add_match(Match(Match.WORD, word1, "Hi"))
        context.add_match(Match(Match.WORD, word2, "There"))

        total_str = ""
        context.list_matches(self._client_context,
                             output_func=collector,
                             include_template=False)
        self.assertEquals(
            "\tMatches...	Asked: HELLO		1: Match=(Topic) Node=(ONEORMORE [*]) Matched=()		"
            "2: Match=(Word) Node=(WORD [Hi]) Matched=(Hi)		"
            "3: Match=(Word) Node=(WORD [There]) Matched=(There)	"
            "Match score 100.00", total_str)
예제 #2
0
 def test_match_no_word(self):
     topic = PatternOneOrMoreWildCardNode("*")
     match = Match(Match.TOPIC, topic, None)
     self.assertEqual(Match.TOPIC, match.matched_node_type)
     self.assertEqual(Match.TOPIC, match.matched_node_type)
     self.assertEqual([], match.matched_node_words)
     self.assertEqual("Match=(Topic) Node=(ONEORMORE [*]) Matched=()",
                      match.to_string(self._client_context))
예제 #3
0
    def test_match_word(self):
        topic = PatternOneOrMoreWildCardNode("*")
        match = Match(Match.TOPIC, topic, "Hello")

        self.assertEqual(Match.TOPIC, match.matched_node_type)
        self.assertTrue(match.matched_node_multi_word)
        self.assertTrue(match.matched_node_wildcard)
        self.assertEqual("ONEORMORE [*]", match.matched_node_str)
        self.assertEqual("Match=(Topic) Node=(ONEORMORE [*]) Matched=(Hello)",
                         match.to_string(self._client_context))
        self.assertEqual(["Hello"], match.matched_node_words)
예제 #4
0
    def test_to_json_word_node(self):
        word = PatternWordNode("Hello")
        match = Match(Match.WORD, word, "Hello")

        json_data = match.to_json()
        self.assertIsNotNone(json_data)
        self.assertEqual(json_data["type"], "Word")
        self.assertEqual(json_data["node"], "WORD [Hello]")
        self.assertEqual(json_data["words"], ["Hello"])
        self.assertEqual(json_data["multi_word"], False)
        self.assertEqual(json_data["wild_card"], False)
예제 #5
0
 def test_init_match_nodes_not_empty(self):
     context1 = MatchContext(max_search_depth=100,
                             max_search_timeout=60,
                             matched_nodes=[
                                 Match(Match.WORD, PatternWordNode("Hello"),
                                       "Hello"),
                                 Match(Match.WORD, PatternWordNode("There"),
                                       "There")
                             ])
     self.assertEqual(100, context1.max_search_depth)
     self.assertEqual(60, context1.max_search_timeout)
     self.assertEqual(2, len(context1.matched_nodes))
     self.assertIsInstance(context1.total_search_start, datetime.datetime)
예제 #6
0
    def test_get_set_matched_nodes(self):
        context = MatchContext(max_search_depth=100, max_search_timeout=60)

        context._matched_nodes = [
            Match(Match.WORD, PatternWordNode("Hello"), "Hello"),
            Match(Match.WORD, PatternWordNode("There"), "There")
        ]

        self.assertEqual(2, len(context.matched_nodes))

        matched = context.matched_nodes

        self.assertEqual(2, len(matched))
예제 #7
0
    def setUp(self):

        self._client = TemplateGraphClient()
        self._client_context = self._client.create_client_context("testid")

        self._graph = self._client_context.bot.brain.aiml_parser.template_parser

        self.test_sentence = Sentence(self._client_context, "test sentence")

        test_node = PatternOneOrMoreWildCardNode("*")

        self.test_sentence._matched_context = MatchContext(
            max_search_depth=100, max_search_timeout=-1)
        self.test_sentence._matched_context._matched_nodes = [
            Match(Match.WORD, test_node, 'one'),
            Match(Match.WORD, test_node, 'two'),
            Match(Match.WORD, test_node, 'three'),
            Match(Match.WORD, test_node, 'four'),
            Match(Match.WORD, test_node, 'five'),
            Match(Match.WORD, test_node, 'six'),
            Match(Match.TOPIC, test_node, '*'),
            Match(Match.THAT, test_node, '*')
        ]

        conversation = self._client_context.bot.get_conversation(
            self._client_context)
        question = Question.create_from_sentence(self.test_sentence)
        conversation._questions.append(question)
예제 #8
0
파일: test_xml.py 프로젝트: lilnana00/3ddd
    def test_attrib_with_html(self):
        template = ET.fromstring("""
            <template>
                <a target="_new" href="http://www.google.com/search?q=&lt;star /&gt;"> Google Search </a>
            </template>
            """)

        conversation = Conversation(self._client_context)
        question = Question.create_from_text(
            self._client_context, "GOOGLE AIML",
            self._client_context.bot.sentence_splitter)
        question.current_sentence()._response = "OK"
        conversation.record_dialog(question)
        match = PatternOneOrMoreWildCardNode("*")
        context = MatchContext(max_search_depth=100, max_search_timeout=-1)
        context.add_match(Match(Match.WORD, match, "AIML"))
        question.current_sentence()._matched_context = context
        self._client_context.bot._conversation_mgr._conversations[
            "testid"] = conversation

        ast = self._graph.parse_template_expression(template)
        self.assertIsNotNone(ast)
        self.assertIsInstance(ast, TemplateNode)
        self.assertIsNotNone(ast.children)
        self.assertEqual(len(ast.children), 1)

        xml_node = ast.children[0]
        self.assertIsNotNone(xml_node)
        self.assertIsInstance(xml_node, TemplateXMLNode)

        attribs = xml_node.attribs
        self.assertEqual(2, len(attribs))

        self.assertIsInstance(attribs['target'], TemplateWordNode)
        target = attribs['target']
        self.assertEqual(len(target.children), 0)
        self.assertEqual("_new", target.word)

        self.assertIsInstance(attribs['href'], TemplateNode)
        href = attribs['href']
        self.assertEqual(len(href.children), 3)

        self.assertIsInstance(href.children[0], TemplateWordNode)
        self.assertEqual('http://www.google.com/search?q=',
                         href.children[0].word)

        self.assertIsInstance(href.children[1], TemplateNode)
        self.assertEqual(1, len(href.children[1].children))
        star = href.children[1].children[0]
        self.assertIsInstance(star, TemplateStarNode)

        self.assertIsInstance(href.children[2], TemplateWordNode)
        self.assertEqual('', href.children[2].word)

        result = xml_node.resolve(self._client_context)
        self.assertIsNotNone(result)
        self.assertEqual(
            result,
            '<a target="_new" href="http://www.google.com/search?q=AIML">Google Search</a>'
        )
예제 #9
0
    def test_resolve_no_defaults_inside_topic(self):
        root = TemplateNode()
        self.assertIsNotNone(root)
        self.assertIsNotNone(root.children)
        self.assertEqual(len(root.children), 0)

        node = TemplateTopicStarNode(index=1)
        self.assertIsNotNone(node)
        self.assertIsInstance(node.index, TemplateNode)

        root.append(node)
        self.assertEqual(len(root.children), 1)

        conversation = Conversation(self._client_context)

        question = Question.create_from_text(self._client_context,
                                             "Hello world")
        question.current_sentence()._response = "Hello matey"
        conversation.record_dialog(question)

        question = Question.create_from_text(self._client_context,
                                             "How are you")
        question.current_sentence()._response = "Very well thanks"
        conversation.record_dialog(question)

        match = PatternOneOrMoreWildCardNode("*")
        context = MatchContext(max_search_depth=100, max_search_timeout=-1)
        context.add_match(Match(Match.TOPIC, match, "Matched"))
        question.current_sentence()._matched_context = context
        conversation.record_dialog(question)

        self._client_context.bot._conversation_mgr._conversations[
            "testid"] = conversation

        self.assertEqual("Matched", node.resolve(self._client_context))
예제 #10
0
    def test_node_with_star_no_match(self):
        root = TemplateNode()
        node = TemplateThatStarNode()
        root.append(node)

        conversation = Conversation(self._client_context)

        question = Question.create_from_text(self._client_context,
                                             "Hello world")
        question.current_sentence()._response = "Hello matey"
        conversation.record_dialog(question)

        question = Question.create_from_text(self._client_context,
                                             "How are you")
        question.current_sentence()._response = "Very well thanks"
        conversation.record_dialog(question)

        match = PatternOneOrMoreWildCardNode("*")
        context = MatchContext(max_search_depth=100, max_search_timeout=-1)
        context.add_match(Match(Match.TOPIC, match, None))
        question.current_sentence()._matched_context = context

        conversation.record_dialog(question)
        self._client_context.bot._conversation_mgr._conversations[
            "testid"] = conversation

        self.assertEqual("", root.resolve(self._client_context))
예제 #11
0
    def assert_just_conversation_storage(self,
                                         store,
                                         can_empty=True,
                                         test_load=True):

        if can_empty is True:
            store.empty()

        client = TestClient()
        client_context = client.create_client_context("user1")

        conversation = Conversation(client_context)

        question1 = Question.create_from_text(client_context, "Hello There")
        question1.sentence(0).response = "Hi"
        question1.sentence(0).matched_context = MatchContext(
            max_search_depth=99,
            max_search_timeout=99,
            matched_nodes=[
                Match(Match.WORD, PatternWordNode("Hello"), "Hello")
            ],
            template_node=None,
            sentence="HELLO",
            response="Hi There")

        conversation.record_dialog(question1)

        store.store_conversation(client_context, conversation)
예제 #12
0
    def test_from_json(self):

        json_data = {
            "type": Match.type_to_string(Match.WORD),
            "node": "WORD [Hello]",
            "words": ["Hello"],
            "multi_word": False,
            "wild_card": False
        }

        match = Match.from_json(json_data)
        self.assertIsNotNone(match)
        self.assertEqual(Match.WORD, match.matched_node_type)
        self.assertEqual(False, match._matched_node_multi_word)
        self.assertEqual(False, match._matched_node_wildcard)
        self.assertEqual("WORD [Hello]", match._matched_node_str)
        self.assertEqual(["Hello"], match._matched_node_words)
예제 #13
0
    def test_to_json(self):
        topic = PatternOneOrMoreWildCardNode("*")
        word1 = PatternWordNode("Hi")
        word2 = PatternWordNode("There")
        context = MatchContext(max_search_depth=100,
                               max_search_timeout=60,
                               template_node=PatternTemplateNode(
                                   TemplateWordNode("Hello")))
        context.add_match(Match(Match.TOPIC, topic, None))
        context.add_match(Match(Match.WORD, word1, "Hi"))
        context.add_match(Match(Match.WORD, word2, "There"))

        json_data = context.to_json()

        self.assertIsNotNone(json_data)
        self.assertEquals(json_data["max_search_depth"], 100)
        self.assertEquals(json_data["max_search_timeout"], 60)
        self.assertIsInstance(json_data["total_search_start"],
                              datetime.datetime)

        self.assertEquals(3, len(json_data["matched_nodes"]))
        self.assertEquals(
            json_data["matched_nodes"][0], {
                'multi_word': True,
                'node': 'ONEORMORE [*]',
                'type': 'Topic',
                'wild_card': True,
                'words': []
            })
        self.assertEquals(
            json_data["matched_nodes"][1], {
                'multi_word': False,
                'node': 'WORD [Hi]',
                'type': 'Word',
                'wild_card': False,
                'words': ["Hi"]
            })
        self.assertEquals(
            json_data["matched_nodes"][2], {
                'multi_word': False,
                'node': 'WORD [There]',
                'type': 'Word',
                'wild_card': False,
                'words': ["There"]
            })
예제 #14
0
    def test_to_json(self):

        topic = PatternOneOrMoreWildCardNode("*")
        word1 = PatternWordNode("Hi")
        word2 = PatternWordNode("There")
        context = MatchContext(max_search_depth=100,
                               max_search_timeout=60,
                               template_node=TemplateWordNode("Hello"))
        context.add_match(Match(Match.TOPIC, topic, None))
        context.add_match(Match(Match.WORD, word1, "Hi"))
        context.add_match(Match(Match.WORD, word2, "There"))

        sentence = Sentence(self._client_context,
                            "One Two Three",
                            matched_context=context)

        json_data = sentence.to_json()
        self.assertIsNotNone(json_data)
예제 #15
0
 def test_match_context_pop_push(self):
     topic = PatternOneOrMoreWildCardNode("*")
     context = MatchContext(max_search_depth=100, max_search_timeout=60)
     self.assertEqual(0, len(context.matched_nodes))
     context.add_match(Match(Match.TOPIC, topic, None))
     self.assertEqual(1, len(context.matched_nodes))
     context.add_match(Match(Match.TOPIC, topic, None))
     self.assertEqual(2, len(context.matched_nodes))
     context.add_match(Match(Match.TOPIC, topic, None))
     self.assertEqual(3, len(context.matched_nodes))
     context.pop_match()
     self.assertEqual(2, len(context.matched_nodes))
     context.pop_match()
     self.assertEqual(1, len(context.matched_nodes))
     context.pop_match()
     self.assertEqual(0, len(context.matched_nodes))
     context.pop_match()
     self.assertEqual(0, len(context.matched_nodes))
예제 #16
0
    def test_set_get_matched_nodes(self):
        context1 = MatchContext(max_search_depth=100,
                                max_search_timeout=60,
                                matched_nodes=[])

        self.assertEquals([], context1.matched_nodes)

        context1.set_matched_nodes(
            [Match(Match.WORD, PatternWordNode("Hello"), "Hello")])

        self.assertEquals(1, len(context1.matched_nodes))
예제 #17
0
    def test_match_context_star(self):
        word = PatternOneOrMoreWildCardNode("*")
        topic = PatternOneOrMoreWildCardNode("*")
        that = PatternOneOrMoreWildCardNode("*")

        context = MatchContext(max_search_depth=100, max_search_timeout=60)

        context.add_match(Match(Match.WORD, word, "Hello"))
        context.add_match(Match(Match.TOPIC, topic, "Hello Topic"))
        context.add_match(Match(Match.THAT, that, "Hello That"))
        self.assertEqual(3, len(context.matched_nodes))

        self.assertEqual("Hello", context.star(self._client_context, 1))
        self.assertIsNone(context.star(self._client_context, 2))
        self.assertEqual("Hello Topic",
                         context.topicstar(self._client_context, 1))
        self.assertIsNone(context.topicstar(self._client_context, 2))
        self.assertEqual("Hello That",
                         context.thatstar(self._client_context, 1))
        self.assertIsNone(context.thatstar(self._client_context, 2))
    def from_json(json_data):
        match_context = MatchContext(0, 0)

        match_context._max_search_depth = json_data["max_search_depth"]
        match_context._max_search_timeout = json_data["max_search_timeout"]
        match_context._total_search_start = json_data["total_search_start"]
        match_context._sentence = json_data["sentence"]
        match_context._response = json_data["response"]

        for match_data in json_data["matched_nodes"]:
            match_context._matched_nodes.append(Match.from_json(match_data))

        return match_context
예제 #19
0
    def from_json(json_data):
        match_context = MatchContext(0, 0)

        match_context.max_search_depth = json_data["max_search_depth"]
        match_context.max_search_timeout = json_data["max_search_timeout"]
        match_context.total_search_start = datetime.datetime.strptime(
            json_data["total_search_start"], "%d/%m/%Y, %H:%M:%S")
        match_context.sentence = json_data["sentence"]
        match_context.response = json_data["response"]

        for match_data in json_data["matched_nodes"]:
            match_context.matched_nodes.append(Match.from_json(match_data))

        return match_context
예제 #20
0
    def _read_matches_from_db(self, client_context, matched_context, matchid):
        matchnodedaos = self._storage_engine.session.query(MatchNodeDAO). \
            filter(MatchNodeDAO.matchid == matchid)

        for matchnodedao in matchnodedaos:
            YLogger.debug(client_context, "Loading match node %s", matchnodedao)

            match = Match(None, None, None)
            match._matched_node_type = Match.string_to_type(matchnodedao.matchtype)
            match._matched_node_str = matchnodedao.matchnode
            match._matched_node_words = client_context.brain.tokenizer.texts_to_words(matchnodedao.matchstr)
            match._matched_node_multi_word = matchnodedao.multiword

            matched_context.matched_nodes.append(match)
예제 #21
0
    def test_read_write_matches_in_db(self):
        config = SQLStorageConfiguration()
        engine = SQLStorageEngine(config)
        engine.initialise()
        store = SQLConversationStore(engine)

        store.empty()

        client = TestClient()
        client_context = client.create_client_context("user1")

        matched_context1 = MatchContext(100,
                                        100,
                                        sentence="Hello",
                                        response="Hi There")
        matched_context1.matched_nodes.append(
            Match(Match.WORD, PatternWordNode("Hello"), "Hello"))

        store._write_matches_to_db(client_context, matched_context1, 1)

        store.commit()

        matched_context2 = MatchContext(0, 0)

        store._read_matches_from_db(client_context, matched_context2, 1)

        self.assertEqual(1, len(matched_context2.matched_nodes))
        self.assertEqual(Match.WORD,
                         matched_context2.matched_nodes[0].matched_node_type)
        self.assertEqual("WORD [Hello]",
                         matched_context2.matched_nodes[0].matched_node_str)
        self.assertFalse(
            matched_context2.matched_nodes[0].matched_node_multi_word)
        self.assertFalse(
            matched_context2.matched_nodes[0].matched_node_wildcard)
        self.assertEqual(
            1, len(matched_context2.matched_nodes[0].matched_node_words))
        self.assertEqual(["Hello"],
                         matched_context2.matched_nodes[0].matched_node_words)

        store.empty()
예제 #22
0
    def match_children(self, client_context, children, child_type, words, word_no, context, match_type, depth):

        tabs = self.get_tabs(client_context, depth)

        for child in children:

            result = child.equals(client_context, words, word_no)
            if result.matched is True:
                word_no = result.word_no
                YLogger.debug(client_context, "%s%s matched %s", tabs, child_type, result.matched_phrase)

                match_node = Match(match_type, child, result.matched_phrase)
                context.add_match(match_node)

                match = child.consume(client_context, context, words, word_no + 1, match_type, depth+1)
                if match is not None:
                    YLogger.debug(client_context, "%sMatched %s child, success!", tabs, child_type)
                    return match, word_no
                else:
                    context.pop_match()

        return None, word_no
예제 #23
0
    def _write_matches_to_db(self, client_context, matched_context, matchid):
        match_count = 1
        for match in matched_context.matched_nodes:
            matchnodedao = self._storage_engine.session.query(MatchNodeDAO). \
                filter(MatchNodeDAO.matchid == matchid,
                       MatchNodeDAO.matchcount == match_count).first()

            if matchnodedao is None:
                matchnodedao = MatchNodeDAO(matchid=matchid,
                                            matchcount=match_count,
                                            matchtype=Match.type_to_string(match.matched_node_type),
                                            matchnode=match.matched_node_str,
                                            matchstr=match.joined_words(client_context),
                                            wildcard=match.matched_node_wildcard,
                                            multiword=match.matched_node_multi_word)

                self._storage_engine.session.add(matchnodedao)
                YLogger.debug(client_context, "Writing matched node %s", matchnodedao)

            else:
                YLogger.debug(client_context, "Matched node already exists, %s", matchnodedao)

            match_count += 1
예제 #24
0
 def test_string_to_type(self):
     self.assertEquals(0, Match.string_to_type("Word"))
     self.assertEquals(2, Match.string_to_type("Topic"))
     self.assertEquals(3, Match.string_to_type("That"))
     self.assertEquals(-1, Match.string_to_type("Other"))
예제 #25
0
    def test_to_json(self):
        client = TestClient()
        client_context = ClientContext(client, "testid")
        client_context.bot = Bot(BotConfiguration(), client)
        client_context.bot.configuration.conversations._max_histories = 3
        client_context.brain = client_context.bot.brain

        conversation1 = Conversation(client_context)
        conversation1.properties["convo1"] = "value1"
        matched_context = MatchContext(100, 100)
        matched_context.matched_nodes.append(Match(Match.WORD, PatternWordNode("Hello"), "Hello"))
        sentence = Sentence(client_context, text="Hi", response="Hello there", matched_context=matched_context)

        question1 = Question.create_from_sentence(sentence)
        question1.properties['quest1'] = "value2"
        conversation1.record_dialog(question1)

        json_data = conversation1.to_json()
        self.assertIsNotNone(json_data)

        self.assertEqual("testclient", json_data['client_context']['clientid'])
        self.assertEqual("testid", json_data['client_context']['userid'])
        self.assertEqual("bot", json_data['client_context']['botid'])
        self.assertEqual("brain", json_data['client_context']['brainid'])
        self.assertEqual(0, json_data['client_context']['depth'])

        conversation2 = Conversation.from_json(client_context, json_data)

        self.assertEqual(conversation1._client_context.client.id, conversation2._client_context.client.id)
        self.assertEqual(conversation1._client_context.userid, conversation2._client_context.userid)
        self.assertEqual(conversation1._client_context.bot.id, conversation2._client_context.bot.id)
        self.assertEqual(conversation1._client_context.brain.id, conversation2._client_context.brain.id)
        self.assertEqual(conversation1._client_context._question_start_time,
                          conversation2._client_context._question_start_time)
        self.assertEqual(conversation1._client_context._question_depth, conversation2._client_context._question_depth)
        self.assertEqual(conversation1._client_context._id, conversation2._client_context._id)

        self.assertEqual(conversation1.properties, conversation2.properties)
        self.assertEqual(conversation1.max_histories, conversation2.max_histories)

        self.assertNotEquals(0, len(conversation1.questions))
        self.assertNotEquals(0, len(conversation2.questions))
        self.assertEqual(len(conversation1.questions), len(conversation2.questions))

        for i in range(len(conversation2.questions)):
            q1 = conversation1.questions[i]
            q2 = conversation2.questions[i]

            self.assertEqual(q1.srai, q2.srai)
            self.assertEqual(q1._current_sentence_no, q2._current_sentence_no)

            self.assertEqual(q1.properties, q2.properties)

            self.assertNotEquals(0, len(q1.sentences))
            self.assertNotEquals(0, len(q2.sentences))
            self.assertEqual(len(q1.sentences), len(q2.sentences))

            for j in range(len(q2.sentences)):
                s1 = q1.sentences[j]
                s2 = q2.sentences[j]

                self.assertEqual(s1.words, s2.words)
                self.assertEqual(s1.response, s2.response)
                self.assertEqual(s1.positivity, s2.positivity)
                self.assertEqual(s1.subjectivity, s2.subjectivity)

                mc1 = s1.matched_context
                mc2 = s2.matched_context

                self.assertEquals(mc1.template_node, mc2.template_node)
                self.assertEquals(mc1.max_search_depth, mc2.max_search_depth)
                self.assertEquals(mc1.max_search_timeout, mc2.max_search_timeout)
                time1 = mc1._total_search_start.strftime("%d/%m/%Y, %H:%M:%S")
                time2 = mc2._total_search_start.strftime("%d/%m/%Y, %H:%M:%S")
                self.assertEquals(time1, time2)

                self.assertNotEquals(0, len(mc1.matched_nodes))
                self.assertNotEquals(0, len(mc2.matched_nodes))
                self.assertEquals(len(mc1.matched_nodes), len(mc2.matched_nodes))

                for k in range(len(mc1.matched_nodes)):
                    mn1 = mc1.matched_nodes[k]
                    mn2 = mc2.matched_nodes[k]

                    self.assertEquals(mn1._matched_node_str, mn2._matched_node_str)
                    self.assertEquals(mn1._matched_node_type, mn2._matched_node_type)
                    self.assertEquals(mn1._matched_node_multi_word, mn2._matched_node_multi_word)
                    self.assertEquals(mn1._matched_node_wildcard, mn2._matched_node_wildcard)
                    self.assertEquals(mn1._matched_node_words, mn2._matched_node_words)
예제 #26
0
    def consume(self, client_context, context, words, word_no, match_type,
                depth):

        tabs = self.get_tabs(client_context, depth)

        if context.search_time_exceeded() is True:
            YLogger.error(client_context,
                          "%sMax search time [%d]secs exceeded", tabs,
                          context.max_search_timeout)
            return None

        if context.search_depth_exceeded(depth) is True:
            YLogger.error(client_context, "%sMax search depth [%d] exceeded",
                          tabs, context.max_search_depth)
            return None

        if word_no >= words.num_words():
            return None

        word = words.word(word_no)
        YLogger.debug(client_context, "%sWildcard %s matched %s", tabs,
                      self._wildcard, word)
        context_match = Match(match_type, self, word)
        context.add_match(context_match)
        matches_added = 1

        match = self.check_child_is_wildcard(tabs, client_context, context,
                                             words, word_no, match_type, depth)
        if match is not None:
            return match

        if self._topic is not None:
            match = self._topic.consume(client_context, context, words,
                                        word_no + 1, Match.TOPIC, depth + 1)
            if match is not None:
                YLogger.debug(client_context, "%sMatched topic, success!",
                              tabs)
                return match

            if words.word(word_no) == PatternNode.TOPIC:
                YLogger.debug(
                    client_context,
                    "%s Looking for a %s, none given, no match found!", tabs,
                    PatternNode.TOPIC)
                return None

        if self._that is not None:
            match = self._that.consume(client_context, context, words,
                                       word_no + 1, Match.THAT, depth + 1)
            if match is not None:
                YLogger.debug(client_context, "%sMatched that, success!", tabs)
                return match

            if words.word(word_no) == PatternNode.THAT:
                YLogger.debug(
                    client_context,
                    "%s Looking for a %s, none given, no match found!", tabs,
                    PatternNode.THAT)
                return None

        word_no += 1
        if word_no >= words.num_words():
            YLogger.debug(client_context, "%sNo more words", tabs)
            return super(PatternOneOrMoreWildCardNode,
                         self).consume(client_context, context, words, word_no,
                                       match_type, depth + 1)

        word = words.word(word_no)

        if self._priority_words or self._children:

            ################################################################################################################
            # Priority nodes
            for child in self._priority_words:

                result = child.equals(client_context, words, word_no)
                if result.matched is True:
                    word_no = result.word_no
                    YLogger.debug(client_context,
                                  "%sWildcard child matched %s", tabs,
                                  result.matched_phrase)

                    context_match2 = Match(Match.WORD, child,
                                           result.matched_phrase)

                    context.add_match(context_match2)
                    matches_added += 1

                    match = child.consume(client_context, context, words,
                                          word_no + 1, match_type, depth + 1)
                    if match is not None:
                        return match

            ################################################################################################################
            # Children nodes
            for child in self._children:

                result = child.equals(client_context, words, word_no)
                if result.matched is True:
                    word_no = result.word_no
                    YLogger.debug(client_context,
                                  "%sWildcard child matched %s", tabs,
                                  result.matched_phrase)

                    context_match2 = Match(Match.WORD, child,
                                           result.matched_phrase)

                    context.add_match(context_match2)
                    matches_added += 1

                    match = child.consume(client_context, context, words,
                                          word_no + 1, match_type, depth + 1)
                    if match is not None:
                        return match

            if self.invalid_topic_or_that(tabs, client_context, word, context,
                                          matches_added) is True:
                return None

            YLogger.debug(client_context, "%sWildcard %s matched %s", tabs,
                          self._wildcard, word)
            context_match.add_word(word)

            word_no += 1
            if word_no >= words.num_words():
                context.pop_matches(matches_added)
                return None

            word = words.word(word_no)

        YLogger.debug(client_context,
                      "%sNo children, consume words until next break point",
                      tabs)

        while word_no < words.num_words() - 1:
            match = super(PatternOneOrMoreWildCardNode,
                          self).consume(client_context, context, words,
                                        word_no, match_type, depth + 1)
            if match is not None:
                return match

            if self.invalid_topic_or_that(tabs, client_context, word, context,
                                          matches_added) is True:
                return None

            YLogger.debug(client_context, "%sWildcard %s matched %s", tabs,
                          self._wildcard, word)
            context_match.add_word(word)

            word_no += 1
            word = words.word(word_no)

        YLogger.debug(client_context, "%sWildcard %s matched %s", tabs,
                      self._wildcard, word)
        context_match.add_word(word)

        if word_no == words.num_words() - 1:
            match = super(PatternOneOrMoreWildCardNode,
                          self).consume(client_context, context, words,
                                        word_no + 1, match_type, depth + 1)
        else:
            match = super(PatternOneOrMoreWildCardNode,
                          self).consume(client_context, context, words,
                                        word_no, match_type, depth + 1)

        if match is not None:
            return match

        context.pop_matches(matches_added)
        return None
예제 #27
0
 def test_type_to_string(self):
     self.assertEqual("Word", Match.type_to_string(Match.WORD))
     self.assertEqual("Topic", Match.type_to_string(Match.TOPIC))
     self.assertEqual("That", Match.type_to_string(Match.THAT))
     self.assertEqual("Unknown", Match.type_to_string(999))