def __init__(self, name, command, terminal_command, context):
        # Here we define this rule's spoken-form and special elements. Note that
        # nested_repetitions is the only one that contains Repetitions, and it
        # is not itself repeated. This is for performance purposes.
        spec = ("[<sequence>] "
                "[<nested_repetitions>] "
                "[<terminal_command>] "
                "[<final_command>]")
        extras = [
            Repetition(command, min=1, max=5, name="sequence"),
            Alternative([RuleRef(rule=character_rule)],
                        name="nested_repetitions"),
            ElementWrapper("terminal_command", terminal_command),
            RuleRef(rule=final_rule, name="final_command"),
        ]
        defaults = {
            "sequence": [],
            "nested_repetitions": None,
            "terminal_command": None,
            "final_command": None,
        }

        CompoundRule.__init__(self,
                              name=name,
                              spec=spec,
                              extras=extras,
                              defaults=defaults,
                              exported=True,
                              context=context)
示例#2
0
 def test_multiple_rules(self):
     """ Verify that the engine successfully mimics each rule in a
         grammar with multiple rules. """
     self.add_rule(CompoundRule(name="r1", spec="hello"))
     self.add_rule(CompoundRule(name="r2", spec="see you"))
     assert self.recognize_node("hello").words() == ["hello"]
     assert self.recognize_node("see you").words() == ["see", "you"]
    def __init__(self, mapping_rule):
        single = RuleRef(rule=mapping_rule)
        series = Repetition(single, min=1, max=16, name="series")

        compound_spec = "<series>"
        compound_extras = [series]
        CompoundRule.__init__(self, spec=compound_spec,
                              extras=compound_extras, exported=True)
示例#4
0
    def __init__(self, mapping_rule):
        single = RuleRef(rule=mapping_rule)
        series = Repetition(single, min=1, max=16, name="series")

        compound_spec = "<series>"
        compound_extras = [series]
        CompoundRule.__init__(self,
                              spec=compound_spec,
                              extras=compound_extras,
                              exported=True)
示例#5
0
    def __init__(self, mapping, extras=None, defaults=None):
        mapping_rule = MappingRule(mapping=mapping, extras=extras,
                                   defaults=defaults, exported=False)
        single = RuleRef(rule=mapping_rule)
        series = Repetition(single, min=1, max=16, name="series")

        compound_spec = "<series>"
        compound_extras = [series]
        CompoundRule.__init__(self, spec=compound_spec,
                              extras=compound_extras, exported=True)
    def __init__(self, mapping, extras=None, defaults=None):
        mapping_rule = MappingRule(mapping=mapping, extras=extras,
                                   defaults=defaults, exported=False)
        single = RuleRef(rule=mapping_rule)
        series = Repetition(single, min=1, max=16, name="series")

        compound_spec = "<series>"
        compound_extras = [series]
        CompoundRule.__init__(self, spec=compound_spec,
                              extras=compound_extras, exported=True)
 def __init__(self,
              window_movement,
              name=None,
              spec=None,
              extras=None,
              defaults=None,
              exported=None,
              context=None):
     # pylint: disable=too-many-arguments
     CompoundRule.__init__(self, name, spec, extras, defaults, exported,
                           context)
     self.window_movement = window_movement
示例#8
0
 def __init__(self, exported):
     extras = [
         Alternative(name="word",
                     children=[
                         RuleRef(AbbreviationRule(False)),
                         RuleRef(SpecialWordRule(False)),
                         Dictation()
                     ])
     ]
     CompoundRule.__init__(self,
                           name=get_unique_rule_name(),
                           extras=extras,
                           exported=exported)
示例#9
0
    def __init__(self,
                 name=None,
                 spec=None,
                 extras=None,
                 defaults=None,
                 exported=False,
                 context=None):

        CompoundRule.__init__(self,
                              name=name,
                              spec=spec,
                              extras=extras,
                              defaults=defaults,
                              exported=exported,
                              context=context)
示例#10
0
    def test_natlink_compiler(self):
        from dragonfly.engines.backend_natlink.compiler import NatlinkCompiler
        extras = [
            Choice("food", {
                "(an | a juicy) apple": "good",
                "a [greasy] hamburger": "bad"
            })
        ]
        rule = CompoundRule('ExampleCustomRule', "I want to eat <food>",
                            extras)
        grammar = Grammar(name="mygrammar")
        grammar.add_rule(rule)

        c = NatlinkCompiler()
        (compiled_grammar, rule_names) = c.compile_grammar(grammar)

        assert rule_names == (None, "ExampleCustomRule")
        if PY2:
            assert compiled_grammar.encode(
                "hex"
            ) == "0000000000000000040000001c0000001c000000010000004578616d706c65437573746f6d52756c650000000500000000000000060000000000000002000000900000000c0000000100000049000000100000000200000077616e74000000000c00000003000000746f00000c00000004000000656174000c000000050000006100000010000000060000006772656173790000140000000700000068616d6275726765720000000c00000008000000616e000010000000090000006a75696379000000100000000a0000006170706c6500000003000000e0000000e00000000100000001000000010000000100000001000000030000000100000003000000020000000300000003000000030000000400000002000000010000000100000002000000010000000100000003000000050000000100000004000000030000000600000002000000040000000300000007000000020000000100000001000000010000000100000002000000030000000800000001000000010000000300000005000000030000000900000002000000010000000200000002000000030000000a000000020000000100000002000000020000000200000001000000"
        else:
            assert codecs.encode(
                compiled_grammar, "hex_codec"
            ) == b"0000000000000000040000001c0000001c000000010000004578616d706c65437573746f6d52756c650000000500000000000000060000000000000002000000900000000c0000000100000049000000100000000200000077616e74000000000c00000003000000746f00000c00000004000000656174000c00000005000000616e00000c000000060000006100000010000000070000006a7569637900000010000000080000006170706c6500000010000000090000006772656173790000140000000a00000068616d62757267657200000003000000e0000000e00000000100000001000000010000000100000001000000030000000100000003000000020000000300000003000000030000000400000002000000010000000100000002000000010000000100000001000000020000000300000005000000010000000100000003000000060000000300000007000000020000000100000002000000020000000300000008000000020000000100000001000000010000000300000006000000010000000400000003000000090000000200000004000000030000000a000000020000000100000002000000020000000200000001000000"
示例#11
0
    def test_rule_context(self):
        """ Verify that the engine works correctly with rule contexts. """
        context = TestContext(True)
        self.add_rule(
            CompoundRule(name="r1", spec="test context", context=context))
        self.grammar.load()

        # Test that the rule matches when in-context.
        results = self.recognize_node("test context").words()
        assert results == ["test", "context"]

        # Go out of context and test again.
        # Use the engine's mimic method because recognize_node won't return
        # RecognitionFailure like ElementTester.recognize does.
        context.active = False
        self.process_grammars_context()
        try:
            self.grammar.set_exclusiveness(True)
            self.assertRaises(MimicFailure, self.engine.mimic, "test context")
        finally:
            self.grammar.set_exclusiveness(False)

        # Test again after going back into context.
        context.active = True
        self.process_grammars_context()
        results = self.recognize_node("test context").words()
        assert results == ["test", "context"]
示例#12
0
    def test_grammar_context(self):
        """ Verify that the engine works correctly with grammar
            contexts."""
        # Recreate the RuleTestGrammar using a context and add a rule.
        context = TestContext(True)
        self.grammar = RuleTestGrammar(context=context)
        self.add_rule(CompoundRule(name="r1", spec="test context"))
        self.grammar.load()

        # Test that the rule matches when in-context.
        results = self.recognize_node("test context").words()
        assert results == ["test", "context"]

        # Go out of context and test again.
        context.active = False
        self.process_grammars_context()
        try:
            self.grammar.set_exclusiveness(True)
            self.assertRaises(MimicFailure, self.engine.mimic, "test context")
        finally:
            self.grammar.set_exclusiveness(False)

        # Test again after going back into context.
        context.active = True
        self.process_grammars_context()
        results = self.recognize_node("test context").words()
        assert results == ["test", "context"]
示例#13
0
 def __init__(self,
              commands,
              name=None,
              spec=None,
              extras=None,
              defaults=None,
              exported=None,
              context=None):
     CompoundRule.__init__(self,
                           name=name,
                           spec=spec,
                           extras=extras,
                           defaults=defaults,
                           exported=exported,
                           context=context)
     self.playback_array = []
     for command in commands:
         self.playback_array.append((command, 0.05))
示例#14
0
 def setUp(self):
     RuleTestCase.setUp(self)
     engine = get_engine()
     if engine.name == 'natlink':
         # Stop Dragon from dictating text for the duration of these
         # tests. This is required when testing for mimic failures.
         self.temp_grammar = Grammar("temp")
         self.temp_grammar.add_rule(CompoundRule(spec="exclusive rule"))
         self.temp_grammar.load()
         self.temp_grammar.set_exclusiveness(True)
示例#15
0
    def __init__(self, parameter):
        self.__parameter = parameter
        spec = None
        extras = []
        if parameter["type"] == "dictation":
            spec = "set " + parameter["name"] + " <value>"
            extras = [Dictation("value")]
        if parameter["type"] == "alternative":
            values = parameter["values"]
            if isinstance(values, dict):
                extras = [Choice("value", values)]
            if isinstance(values, list):
                extras = [Alternative(name="value", children=[Compound(spec=word, value=word) for word in values])]
            spec = "set " + parameter["name"] + " <value>"
        if parameter["type"] == "switch":
            spec = "enable " + parameter["name"]

        CompoundRule.__init__(self,
                              name=get_unique_rule_name(),
                              spec=spec,
                              extras=extras)
示例#16
0
    def test_list_grammars(self):
        """ Verify that the 'list_grammars' RPC method works correctly. """
        # Load a Grammar with three rules and check that the RPC returns the
        # correct data for them.
        g = Grammar("list_grammars_test")
        g.add_rule(CompoundRule(name="compound", spec="testing",
                                exported=True))
        g.add_rule(
            MappingRule(name="mapping",
                        mapping={
                            "command a": ActionBase(),
                            "command b": ActionBase()
                        }))
        g.add_rule(
            Rule(name="base", element=Literal("hello world"), exported=False))
        g.load()

        response = self.send_request("list_grammars", [])
        expected_grammar_data = {
            "name":
            g.name,
            "enabled":
            True,
            "active":
            True,
            "rules": [{
                "name": "compound",
                "specs": ["testing"],
                "exported": True,
                "active": True
            }, {
                "name": "mapping",
                "specs": ["command a", "command b"],
                "exported": True,
                "active": True
            }, {
                "name": "base",
                "specs": ["hello world"],
                "exported": False,
                "active": True
            }]
        }
        # Check that the loaded grammar appears in the result. It might not
        # be the only grammar and that is acceptable because dragonfly's
        # tests can be run while user grammars are loaded.
        try:
            self.assertIn("result", response)
            self.assertIn(expected_grammar_data, response["result"])
        finally:
            g.unload()
示例#17
0
    def test_exclusive_grammars(self):
        """ Verify that the engine supports exclusive grammars. """
        # This is here as grammar exclusivity is context related.
        # Set up two grammars to test with.
        grammar1 = self.grammar
        grammar1.add_rule(CompoundRule(spec="grammar one"))
        grammar2 = RuleTestGrammar(name="Grammar2")
        grammar2.add_rule(CompoundRule(spec="grammar two"))
        grammar1.load()
        grammar2.load()

        # Set grammar1 as exclusive and make some assertions.
        grammar1.set_exclusiveness(True)
        results = grammar1.recognize_node("grammar one").words()
        assert results == ["grammar", "one"]
        self.assertRaises(MimicFailure, self.engine.mimic, "grammar two")

        # Set grammar1 as no longer exclusive and make some assertions.
        grammar1.set_exclusiveness(False)
        results = grammar1.recognize_node("grammar one").words()
        assert results == ["grammar", "one"]
        results = grammar2.recognize_node("grammar two").words()
        assert results == ["grammar", "two"]
示例#18
0
    def test_mimic(self):
        """ Verify that the 'mimic' RPC method works correctly. """
        g = Grammar("mimic_test")
        g.add_rule(
            CompoundRule(name="compound",
                         spec="testing mimicry",
                         exported=True))
        g.load()

        # Set the grammar as exclusive.
        # The sapi5shared engine apparently requires this for mimic() to
        # work, making the method kind of useless. This does not apply to
        # sapi5inproc.
        g.set_exclusiveness(True)

        response = self.send_request("mimic", ["testing mimicry"])
        try:
            self.assertIn("result", response)
            self.assertEqual(response["result"], True)
        finally:
            g.set_exclusiveness(False)
            g.unload()
示例#19
0
    def test_recognition_history_methods(self):
        """ Verify that the recognition history RPC methods work correctly.
        """
        # Load a grammar for testing that recognitions are saved.
        g = Grammar("history_test")
        g.add_rule(
            CompoundRule(name="compound", spec="test history", exported=True))
        g.load()
        g.set_exclusiveness(True)
        try:
            # Test 'register_history()'.
            response = self.send_request("register_history", [])
            self.assertIn("result", response)

            # Test that the method raises an error if used when the observer
            # is already registered.
            self.assertRaises(RuntimeError, self.send_request,
                              "register_history", [])

            # Send a mimic and check that it is returned by the
            # 'get_recognition_history()' method.
            self.send_request("mimic", ["test history"])
            response = self.send_request("get_recognition_history", [])
            self.assertIn("result", response)
            self.assertListEqual(response["result"], [["test", "history"]])

            # Test 'unregister_observer()'.
            response = self.send_request("unregister_history", [])
            self.assertIn("result", response)

            # Test that the method raises an error if used when the observer
            # is not registered.
            self.assertRaises(RuntimeError, self.send_request,
                              "unregister_history", [])
        finally:
            g.set_exclusiveness(False)
            g.unload()
示例#20
0
 def __init__(self, exported):
     extras = [Choice("special_word", special_words)]
     CompoundRule.__init__(self,
                           name=get_unique_rule_name(),
                           extras=extras,
                           exported=exported)
示例#21
0
文件: recording.py 项目: j127/caster
 def __init__(self, commands, name=None, spec=None, extras=None,
     defaults=None, exported=None, context=None):
     CompoundRule.__init__(self, name=name, spec=spec, extras=extras, defaults=defaults, exported=exported, context=context)
     self.playback_array = []
     for command in commands:
         self.playback_array.append((command, 0.05))
示例#22
0
 def __init__(self, alternatives, name=None, defaults=None, exported=None, context=None):
     CompoundRule.__init__(self, name=name, spec="<sequence>",
                           extras=[Repetition(Alternative(alternatives), min=1, max=16, name="sequence")],
                           defaults=defaults, exported=exported, context=context)
    def test_recognition_observer(self):
        """
        Test that the engine's recognition observer manager works correctly.
        """
        on_begin_test = self.get_test_function()
        on_recognition_test = self.get_test_function()
        on_failure_test = self.get_test_function()
        on_next_rule_part_test = self.get_test_function()

        # Set up a custom observer using test methods
        class TestObserver(RecognitionObserver):
            on_begin = on_begin_test
            on_next_rule_part = on_next_rule_part_test
            on_recognition = on_recognition_test
            on_failure = on_failure_test

        # Set up a TestObserver instance and a grammar with multiple rules to use
        observer = TestObserver()
        observer.register()
        grammar = Grammar("test")
        grammar.add_rule(CompoundRule("rule1", "hello world"))
        grammar.add_rule(
            CompoundRule("rule2",
                         "say <dictation>",
                         extras=[Dictation("dictation")]))
        grammar.load()
        self.assertTrue(grammar.loaded)

        # Test that each method is called properly
        self.assert_mimic_success("hello world")

        # on_begin is called during each mimic. on_recognition should be called
        # once per successful and complete recognition. Both on_failure and
        # on_next_rule_part shouldn't have been called yet.
        self.assert_test_function_called(on_begin_test, 1)
        self.assert_test_function_called(on_recognition_test, 1)
        self.assert_test_function_called(on_failure_test, 0)
        self.assert_test_function_called(on_next_rule_part_test, 0)

        # Test with a dictation rule
        self.assert_mimic_success("say")

        # Recognition begins again, is incomplete and no failure yet.
        self.assert_test_function_called(on_begin_test, 2)
        self.assert_test_function_called(on_recognition_test, 1)
        self.assert_test_function_called(on_failure_test, 0)

        # on_next_rule_part should be called because there are more rule parts
        self.assert_test_function_called(on_next_rule_part_test, 1)

        # Test the next part of the dictation rule
        self.assert_mimic_success("testing testing")

        # Recognition begins again, is complete, and no failure yet.
        self.assert_test_function_called(on_begin_test, 3)
        self.assert_test_function_called(on_recognition_test, 2)
        self.assert_test_function_called(on_failure_test, 0)

        # on_next_rule_part shouldn't have been called because this is the last part
        # and on_recognition will be called instead
        self.assert_test_function_called(on_next_rule_part_test, 1)

        # Recognition begins again and failure occurs.
        self.assert_mimic_failure("testing")
        self.assert_test_function_called(on_begin_test, 4)
        self.assert_test_function_called(on_next_rule_part_test,
                                         1)  # no change
        self.assert_test_function_called(on_failure_test, 1)
        self.assert_test_function_called(on_recognition_test, 2)

        # Test that using None or "" also calls the on_failure method
        self.assert_mimic_failure(None)
        self.assert_test_function_called(on_failure_test, 2)
        self.assert_mimic_failure("")
        self.assert_test_function_called(on_failure_test, 3)
        self.assert_test_function_called(on_next_rule_part_test,
                                         1)  # no change

        # Unregister the observer
        observer.unregister()
示例#24
0
 def __init__(self, exported):
     extras = [Choice("abbreviation", abbreviation_map)]
     CompoundRule.__init__(self,
                           name=get_unique_rule_name(),
                           extras=extras,
                           exported=exported)
示例#25
0
 def __init__(self, command_name, executable, configuration, parameter_rules):
     self.__executable = executable
     self.__configuration = configuration
     self.__parameter_rules = parameter_rules
     configuration_name = configuration["name"] if not configuration["name"] == "default" else ""
     CompoundRule.__init__(self, spec=command_name + " " + configuration_name)
 def __init__(self):
     CompoundRule.__init__(self, extras=[Choice("program", programs)])
示例#27
0
 def __init__( self, choices, callback=False ):
     print( choices )
     self.extras = [Choice( "quickcommand", choices)]
     self.spec = "<quickcommand>"
     self.callback = callback
     CompoundRule.__init__(self)
示例#28
0
 def __init__(self, spec):
     CompoundRule.__init__(self, spec=spec)
     self.words = None