コード例 #1
0
def reload_grammars():
    unload()
    global grammar
    grammar = Grammar("to rule them all")

    now = datetime.datetime.now()
    print "begun reloading at %s:%s" % (now.hour, now.minute)

    # reload module and re-add the rules imported from that module
    global GRAMMAR_IMPORTS
    for import_name in GRAMMAR_IMPORTS:
        try:
            reloader.reload(sys.modules[import_name])
            import_rule = getattr(__import__(import_name, fromlist=["rules"]), "rules")
            grammar.add_rule(import_rule)
            print "Loaded module %s successfully" % import_name
        except RuntimeError as runtime_error:
            "There was an error in file %s" % import_name
            print runtime_error, '\n', '\n'
        except NameError as nameerror:
            "Forgot something in file %s?" % import_name
            print nameerror, '\n', '\n'

    grammar.add_rule(get_reloader_rules()) # for the "reload grammar module" code in get_reloader_rules
    grammar.load()

    print "reloaded all modules"
def get_dragonfly_grammar(grammar, target, result_queue):
    global RULES
    RULES = {}

    parser = CFGParser.fromstring(grammar)
    dragonfly_rule_element = _get_dragonfly_rule_element(target, parser)

    dragonfly_grammar = Grammar("G")
    with result_queue.mutex:
        result_queue.queue.clear()

    class GrammarRule(Rule):
        def process_recognition(self, node):
            logger.info('Dragonfly node: %s', str(node))
            result = node.value()
            logger.info('Dragonfly result: %s', str(result))

            flattened_string = result
            if isinstance(result, list):
                flattened_string = " ".join(flatten(result))

            logger.info('Dragonfly flattened result: %s', str(flattened_string))

            if not result_queue.empty():
                logger.warn('There is already a message in the queue! %s', result_queue)
            result_queue.put_nowait(flattened_string)

            logger.debug("Dragonfly thread recognition Q [id=%s, qsize=%d]", id(result_queue), result_queue.qsize())

    rule = GrammarRule(element=dragonfly_rule_element, exported=True)
    dragonfly_grammar.add_rule(rule)

    return dragonfly_grammar
コード例 #3
0
def recognize(spec, choices_values, timeout):

    global RESULT
    RESULT = None

    grammar = Grammar("grammar")

    extras = []
    for name, choices in choices_values.iteritems():
        extras.append(Choice(name, dict((c,c) for c in choices)))

    Rule = type("Rule", (GrammarRule,),{"spec": spec, "extras": extras})
    grammar.add_rule(Rule())
    grammar.load()   

    future = time.time() + timeout
    while time.time() < future:
        if RESULT is not None:
            break

        pythoncom.PumpWaitingMessages()

        time.sleep(.1)

    grammar.unload()

    print "RESULT:", RESULT

    return RESULT
コード例 #4
0
    def test_no_hypothesis(self):
        """
        Check that if something that doesn't match any rule is mimicked, nothing
        gets recognised.
        """
        test1 = self.get_test_function()
        test2 = self.get_test_function()

        class TestRule(MappingRule):
            mapping = {
                "testing": Function(test1),
                "<dictation>": Function(test2)
            }
            extras = [Dictation("dictation")]

        g = Grammar("test")
        g.add_rule(TestRule())
        g.load()
        self.assertTrue(g.loaded)

        self.assert_mimic_failure(None)
        self.assert_test_function_called(test1, 0)
        self.assert_test_function_called(test2, 0)
        self.assert_mimic_failure("")
        self.assert_test_function_called(test1, 0)
        self.assert_test_function_called(test2, 0)
        self.assert_mimic_success("hello")
        self.assert_test_function_called(test1, 0)
        self.assert_test_function_called(test2, 1)
コード例 #5
0
ファイル: sikuli.py プロジェクト: seekM/caster
def refresh(_NEXUS):
    ''' should be able to add new scripts on the fly and then call this '''
    unload()
    global grammar
    grammar = Grammar("si/kuli")

    def refresh_sick_command():
        server_proxy.terminate()
        refresh(_NEXUS)

    mapping = {
        "launch sick IDE": Function(launch_IDE),
        "launch sick server": Function(launch_server),
        "refresh sick you Lee": Function(refresh_sick_command),
        "sick shot": Key("cs-2"),
    }

    rule = MergeRule(name="sik", mapping=mapping)
    gfilter.run_on(rule)
    grammar.add_rule(rule)
    grammar.load()
    # start server
    try:
        # if the server is already running, this should go off without a hitch
        start_server_proxy()
    except Exception:
        launch_server()
        seconds5 = 5
        control.nexus().timer.add_callback(server_proxy_timer_fn, seconds5)
コード例 #6
0
ファイル: sikuli.py プロジェクト: seekM/caster
def generate_commands(list_of_functions):
    global server_proxy
    global grammar
    mapping = {}
    for fname in list_of_functions:
        spec = " ".join(fname.split("_"))
        mapping[spec] = Function(execute, fname=fname)
    grammar.unload()
    grammar = Grammar("sikuli")
    grammar.add_rule(MappingRule(mapping=mapping, name="sikuli server"))
    grammar.load()
コード例 #7
0
ファイル: _git.py プロジェクト: calmofthestorm/aenea-grammars
def load():
    global git_grammar
    context = aenea.wrappers.AeneaContext(
        ProxyAppContext(
            match='regex',
            app_id='(?i)(?:(?:DOS|CMD).*)|(?:.*(?:TERM|SHELL).*)',
        ),
        AppContext(title='git'),
    )
    git_grammar = Grammar('git', context=context)
    git_grammar.add_rule(GitRule())
    git_grammar.load()
コード例 #8
0
ファイル: Dragonfly_stt.py プロジェクト: Manoharsai/pyrson
    def start(self, queue):
        #instantiating the grammar and rule
        grammar = Grammar("passthrough")
        rule = self.Passthrough()

        #attaching the event
        rule.textrecognition+=queue.put

        #adding and loading rule
        grammar.add_rule(rule)
        grammar.load()

        while 1:
            pythoncom.PumpWaitingMessages()
            time.sleep(.1)
コード例 #9
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()
コード例 #10
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()
コード例 #11
0
    def test_single_dictation(self):
        """
        Test that the engine can handle a dragonfly rule using a Dictation element.
        """
        test = self.get_test_function()

        class TestRule(MappingRule):
            mapping = {"<dictation>": Function(test)}
            extras = [Dictation("dictation")]

        g = Grammar("test")
        g.add_rule(TestRule())
        g.load()
        self.assertTrue(g.loaded)
        self.assert_mimic_success("hello")
        self.assert_test_function_called(test, 1)

        # Test that it works again
        self.assert_mimic_success("hello")
        self.assert_test_function_called(test, 2)

        # Test again with multiple words
        self.assert_mimic_success("hello world")
        self.assert_test_function_called(test, 3)
コード例 #12
0
ファイル: sample.py プロジェクト: paychex/Caster
    # The angle brackets <> meaning I'm using an extra, and the square brackets [] mean that I don't have to speak that word, it's optional.
    # Advice: if you use an optional extra, like I am with "text", you should set a default value  in the defaults section down below.
    # To trigger the following command, you would have to say the word "function" followed by a number between 1 and 1000.
    '[use] function <n> [<text>]':    Function(my_function, extra={'n', 'text'}),
	
     # Sometimes it's easier to have things as a list in a command as a choice that do different things.
     # That's what `<choice>` Is defined in `extras` allows you define that list. If you dictate `i choose custom grid` Then `CustomGrid` will be printed as text.
     # Items in the list are pairs. e.g `{"custom grid": "CustomGrid"}` The first item of a pair is the command "custom grid" and the second "CustomGrid" output text action.   
    "i choose <choice>":              Text("<choice>"),
        
    }

    extras = [
              IntegerRef("n", 1, 1000),
              Dictation("text"),
              Choice("choice",
                    {
                    "alarm": "alarm",
                    "custom grid": "CustomGrid", 
                    "element": "e"
                    }),
                ]
    defaults = {
                "n": 1,
                "text": "",
            }

# this stuff is required too-- where I have the word "sample" below, each grammar file should have external unique
grammar = Grammar('sample')
grammar.add_rule(MainRule())
grammar.load()
コード例 #13
0
        Key("colon, w, space"),
        "undo":
        Function(enable_command_mode) + Key("u"),
        "yank [(line|lines)]":
        Key("d, d"),
        "<text>":
        Function(illegal_command),
    },
    extras=[
        IntegerRef("n", 1, 100),
        Dictation("text"),
    ],
    defaults={"n": 1})

grammarCommand = Grammar("Vim command grammar", context=GlobalDynamicContext())
grammarCommand.add_rule(commandMode)
grammarCommand.load()
grammarCommand.disable()

insertMode = MappingRule(
    mapping={
        # Commands and keywords:
        "(command mode|press escape)": Function(enable_command_mode),
    },
    extras=[
        IntegerRef("n", 1, 100),
        Dictation("text"),
    ],
    defaults={"n": 1})

grammarInsert = Grammar("Vim insert grammar", context=GlobalDynamicContext())
コード例 #14
0

#---------------------------------------------------------------------------
# Paste rule.


class PasteRule(CompoundRule):

    spec = config.lang.paste_me
    extras = [Choice("target", config.targets.mapping)]

    def _process_recognition(self, node, extras):
        target = extras["target"]
        self._log.debug("%s: pasting target %s." % (self, target))
        Paste(target.target).execute()


#---------------------------------------------------------------------------
# Create and manage this module's grammar.

grammar = Grammar("bring me")
grammar.add_rule(BringRule())
grammar.add_rule(PasteRule())
grammar.load()


def unload():
    global grammar
    if grammar: grammar.unload()
    grammar = None
コード例 #15
0
    dynamicName = "Prefix" + prefix + "Rule"
    PrefixCompoundRule.__name__ = dynamicName
    PrefixCompoundRule.__qualname__ = dynamicName
    return PrefixCompoundRule


###############################################################
PrefixKeyRule = makePrefixedCompoundRule("", KeysOnlyRule)
PrefixLiteralRule = makePrefixedCompoundRule("literal", LiteralRule)
PrefixSayRule = makePrefixedCompoundRule("say", SayRule)
PrefixBringRule = makePrefixedCompoundRule("switch to", BringMeRule)
PrefixNumberRule = makePrefixedCompoundRule("number", NumberRule)

grammar = Grammar("Generic edit")
grammar.add_rule(PrefixKeyRule())  # Add the top-level rule.
grammar.add_rule(PrefixLiteralRule())
grammar.add_rule(PrefixSayRule())
grammar.add_rule(PrefixBringRule())

grammar.load()  # Load the grammar.


def unload():
    """Unload function which will be called at unload time."""
    global grammar
    if grammar:
        grammar.unload()
    grammar = None

コード例 #16
0
        # Protocols.
        "protocol H T T P": Text("http://"),
        "protocol H T T P S": Text("https://"),
        "protocol (git|G I T)": Text("git://"),
        "protocol F T P": Text("ftp://"),
        "protocol S S H": Text("ssh://"),
        },
    extras=[
        IntegerRef("n", 1, 100),
        Dictation("text"),
        ],
    defaults={
        "n": 1
    }
)

context = None
if config.get("aenea.enabled", False) == True:
    context = aenea.global_context
grammar = Grammar("Programming help", context=context)
grammar.add_rule(series_rule)
grammar.load()


# Unload function which will be called at unload time.
def unload():
    global grammar
    if grammar:
        grammar.unload()
    grammar = None
コード例 #17
0
        "clish command":
        T("clish -c \"\"") + K("left")
    }

    extras = [
        Integer("t", 1, 50),
        Dictation("text"),
        Dictation("text2"),
        IntegerRef("n", 1, 50000),
        Integer("w", 1, 10),
        # Integer("x", 0, 10),
        # Integer("y", 0, 10),
        # Integer("z", 0, 10)
    ]
    defaults = {"t": 1, "text": "", "text2": ""}


ubu_context = AppContext(executable='ubuntu')
moba_context = AppContext(executable='mobaxterm')
mintty_context = AppContext(executable='mintty')  # git bash, git for Windows
win_term_context = AppContext(executable='WindowsTerminal')
multi_context = ubu_context | moba_context | mintty_context | win_term_context
bash_common_grammar = Grammar('BashCommon', context=multi_context)
bash_common_grammar.add_rule(BashCommonMapping())
bash_common_grammar.load()


def unload():
    global bash_common_grammar
    bash_common_grammar = utils.unloadHelper(bash_common_grammar, __name__)
コード例 #18
0
class TestRules(RuleTestCase):
    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)

    def tearDown(self):
        RuleTestCase.tearDown(self)
        engine = get_engine()
        if engine.name == 'natlink':
            self.temp_grammar.set_exclusiveness(False)
            self.temp_grammar.unload()

    def process_grammars_context(self):
        engine = get_engine()
        if engine.name.startswith("sapi5"):
            engine.process_grammars_context()

    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 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))

        # 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.load()
            self.grammar.set_exclusiveness(True)
            self.assertRaises(MimicFailure, self.engine.mimic, "test context")
        finally:
            self.grammar.set_exclusiveness(False)
            self.grammar.unload()

        # 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"]

    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"]

    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.
        class TestRule(CompoundRule):
            def __init__(self, spec):
                CompoundRule.__init__(self, spec=spec)
                self.words = None

            def _process_recognition(self, node, extras):
                self.words = self.spec

        grammar1 = Grammar(name="Grammar1")
        grammar1.add_rule(TestRule(spec="grammar one"))
        grammar2 = Grammar(name="Grammar2")
        grammar2.add_rule(TestRule(spec="grammar two"))
        grammar3 = Grammar(name="Grammar3")
        grammar3.add_rule(TestRule(spec="grammar three"))
        grammar1.load()
        grammar2.load()
        grammar3.load()

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

        # Set grammar2 as exclusive and make some assertions.
        # Both exclusive grammars should be active.
        grammar2.set_exclusiveness(True)
        self.engine.mimic("grammar one")
        assert grammar1.rules[0].words == "grammar one"
        self.engine.mimic("grammar two")
        assert grammar2.rules[0].words == "grammar two"

        # Non-exclusive grammar 'grammar3' should not be active.
        self.assertRaises(MimicFailure, self.engine.mimic, "grammar three")

        # Set both grammars as no longer exclusive and make some assertions.
        grammar1.set_exclusiveness(False)
        grammar2.set_exclusiveness(False)
        if get_engine().name == 'natlink':
            self.temp_grammar.set_exclusiveness(False)
        self.engine.mimic("grammar one")
        assert grammar1.rules[0].words == "grammar one"
        self.engine.mimic("grammar two")
        assert grammar2.rules[0].words == "grammar two"
        self.engine.mimic("grammar three")
        assert grammar3.rules[0].words == "grammar three"
コード例 #19
0
        'bottom': Key("escape, s-g"),
        '(passed | past)': Key("a-left"),
        'future': Key("a-right"),

        #  Searching
        'braille <text>':
        Key("escape, slash") + Text("%(text)s") + Key("enter"),
        '<n> Noah': Key("%(n)d, n"),
        '[<n>] rev': Key("%(n)d, N"),

        #  page actions
        'scope': Key('f'),
        'scoping': Key('escape, f'),
        'show page atoms': Key("g,s"),
    },
    extras=[
        IntegerRef('n', 1, 99),
        Dictation('text'),
    ],
    defaults={"n": 1})

grammar.add_rule(window_rule)
grammar.load()


# Unload function which will be called by natlink at unload time.
def unload():
    global grammar
    if grammar: grammar.unload()
    grammar = None
コード例 #20
0
#  within a mapping spec and "%(text)s" within the associated action.

example_rule = MappingRule(
    name="example",    # The name of the rule.
    mapping={          # The mapping dict: spec -> action.
             "save [file]":            Key("c-s"),
             "save and close":         Key("c-s, a-f/20, x/20"),
             "save [file] as":         Key("a-f, a"),
             "save [file] as <text>":  Key("a-f, a/20") + Text("%(text)s"),
             "find <text>":            Key("c-f/20") + Text("%(text)s\n"),
            },
    extras=[           # Special elements in the specs of the mapping.
            Dictation("text"),
           ],
    )

# Add the action rule to the grammar instance.
grammar.add_rule(example_rule)


#---------------------------------------------------------------------------
# Load the grammar instance and define how to unload it.

grammar.load()

# Unload function which will be called by natlink at unload time.
def unload():
    global grammar
    if grammar: grammar.unload()
    grammar = None
コード例 #21
0
ファイル: _outlook.py プロジェクト: kb100/dragonfly-scripts
        "next": Key("tab"),
        "previous": Key("s-tab"),
        "[<n>] increase text size": Key("c-rangle:%(n)d"),
        "[<n>] decrease text size": Key("c-langle:%(n)d"),
        "[<n>] scroll up": Key("pageup:%(n)d"),
        "[<n>] scroll down": Key("pagedown:%(n)d"),
        "bold [text|that]": Key("c-b"),
        "(italic|italicize) [text|that]": Key("c-i"),
        "(strike|strikethrough) [text|that]": Key("cs-x"),
        "underline": Key("c-u"),

    },
    extras=[
        LetterSequenceRef('letter_sequence'),
        Dictation("text"),
        ShortIntegerRef('n', 1, 101, default=1)
    ],
)
context = AppContext(executable="outlook")
outlook_grammar = Grammar("outlook", context=context)
outlook_grammar.add_rule(rules)
outlook_grammar.load()

EXPORT_GRAMMARS = [outlook_grammar]


def unload():
    global outlook_grammar
    if outlook_grammar: outlook_grammar.unload()
    outlook_grammar = None
コード例 #22
0
        "disable <module> mode":
        Function(disable_module),
        "disable [all] dynamic modes":
        Function(disable_all_modules),
    },
    extras=[
        IntegerRef("n", 1, 100),
        Dictation("text"),
        Choice("module", moduleMapping),
        Choice("module2", moduleMapping),
        Choice("module3", moduleMapping),
    ],
    defaults={"n": 1})

grammar = Grammar("Dynamic manager", context=None)
grammar.add_rule(series_rule)
grammar.load()

notify()  # Notify that Dragonfly is ready with a sound.


def unload():
    """Unload function which will be called at unload time."""
    # Unload the dynamically loaded modules.
    global moduleMapping
    for module in moduleMapping.values():
        module.unload()

    global grammar
    if grammar:
        grammar.unload()
コード例 #23
0
        # "new (thing | tab)": Key("c-t"),
        # "new window": Key("c-n"),
        # "reopen tab": Key("cs-t"),
        # "(next | nex) (tab | ab) [<n>]": Key("c-pgdown:%(n)d"),
        # "(previous | preev) tab [<n>]": Key("c-pgup:%(n)d"),
        # "show tab <tab>": Key("c-%(tab)d"),
        "switch <text>": Key("c-k/25") + Text("%(text)s") + Key("enter"),

        # "open <w> [<x>] [<y>] [<z>]": Key("cs-space/" + click_by_voice_delay) + Function(printNumber) + Key("enter"),  # click by voice
        # "open focus <w> [<x>] [<y>] [<z>]": Key("cs-space/" + click_by_voice_delay) + Function(printNumberFocus) + Key("enter"),  # click by voice
    }
    extras = [
        Integer("n", 1, 50),
        Integer("number", 1, 9999),
        Dictation("text"),
    ]
    defaults = {
        "n": 1,
    }


context = AppContext(executable="slack")
slack_grammar = Grammar("Slack Grammar", context=context)
slack_grammar.add_rule(SlackMapping())
slack_grammar.load()


def unload():
    global slack_grammar
    slack_grammar = utils.unloadHelper(slack_grammar, __name__)
コード例 #24
0
  extras = [
    IntegerRef("n", 1, 10),
    Dictation("room"),
    ]

  defaults = {
    "n": 1,
    }

class ChatRule(MappingRule):
  mapping = {
    "at <user>":     Text("@%(user)s "),
    "send":          Key("enter"),
  }

  extras = [
    Choice("user", config.usernames.map),
  ]


context = AppContext(executable="hipchat")
terminator_grammar = Grammar("hipchat_general", context=context)
terminator_grammar.add_rule(NavigationRule())
terminator_grammar.add_rule(ChatRule())
terminator_grammar.load()

# Unload function which will be called by natlink at unload time.
def unload():
  global terminator_grammar
  if grammar: grammar.unload()
  grammar = None
コード例 #25
0
ファイル: _hmc.py プロジェクト: carver7/caster
def hmc_confirm(value, nexus):
    nexus.comm.get_com("hmc").do_action(value)
    
def hmc_settings_complete(nexus):
    nexus.comm.get_com("hmc").complete()
    


class HMCRule(MappingRule):
    mapping = {
        "kill homunculus":              R(Function(kill, nexus=_NEXUS), rdescript="Kill Helper Window"),
        "complete":                     R(Function(complete, nexus=_NEXUS), rdescript="Complete Input")
    }
grammar = Grammar("hmc", context=AppContext(title=settings.HOMUNCULUS_VERSION))
grammar.add_rule(HMCRule())
grammar.load()

class HMCHistoryRule(MappingRule):
    mapping = {
        # specific to macro recorder
        "check <n>":                    R(Function(hmc_checkbox, nexus=_NEXUS), rdescript="Check Checkbox"),
        "check from <n> to <n2>":       R(Function(hmc_recording_check_range, nexus=_NEXUS), rdescript="Check Range"),
        "exclude <n>":                  R(Function(hmc_recording_exclude, nexus=_NEXUS), rdescript="Uncheck Checkbox"),
        "[make] repeatable":            R(Function(hmc_recording_repeatable, nexus=_NEXUS), rdescript="Make Macro Repeatable")
    }   
    extras = [
              IntegerRefST("n", 1, 25),
              IntegerRefST("n2", 1, 25),
             ]
grammar_history = Grammar("hmc history", context=AppContext(title=settings.HMC_TITLE_RECORDING))
コード例 #26
0
ファイル: unity.py プロジェクト: Autofire/CodeWyrm-Grammars
def build_grammar(context):
	#grammar = cs.build_grammar(context, "unity")
	grammar = Grammar("unity", context=(context))
	grammar.add_rule(fluid.build_rule(RuleRef(rule=keyword_rule)))
	return grammar
コード例 #27
0
ファイル: legiongrid.py プロジェクト: RadixSeven/caster
        "refresh":                          R(Function(navigation.mouse_alternates, mode="legion"), rdescript="Legion: Refresh"),
        "exit | escape | cancel":           R(Function(kill), rdescript="Exit Legion"),


        }
    extras = [
              Choice("action", {
                              "kick": 0,
                              "psychic": 1,
                              "light": 2,
                             }
                    ),
              IntegerRef("n", 0, 1000),
              
             ]
    defaults = {
            "action":-1,
            }

#---------------------------------------------------------------------------

context = AppContext(title="legiongrid")
grammar = Grammar("legiongrid", context=context)
grammar.add_rule(GridControlRule())
grammar.load()

def unload():
    global grammar
    if grammar: grammar.unload()
    grammar = None
コード例 #28
0
)
#----------------------------------------------------------
# terminal
#----------------------------------------------------------
terminal = MappingRule(
    name="terminal",
    mapping={
        "show (terminal|term)": Key("c-backtick"),
        "new terminal": Key("cs-backtick"),
    },
    extras=[
        Dictation("text"),
    ],
)

grammar.add_rule(general)
grammar.add_rule(editing)
grammar.add_rule(navigation)
grammar.add_rule(search)
grammar.add_rule(cursor)
grammar.add_rule(editing)
grammar.add_rule(editor_management)
grammar.add_rule(file_management)
grammar.add_rule(display)
grammar.add_rule(debug)
grammar.add_rule(terminal)

grammar.load()


def unload():
コード例 #29
0
def noop(text=None):
    pass


class DictationOffRule(MappingRule):
    mapping = {
        "<text>": Function(noop),
    }
    extras = [
        Dictation("text"),
    ]
    defaults = {}


dictationOffGrammar = Grammar("Dictation off")
dictationOffGrammar.add_rule(DictationOffRule())
dictationOffGrammar.load()
dictationOffGrammar.disable()

dictation_enabled = True


def dictation_off():
    global dictation_enabled
    if dictation_enabled:
        print "Dictation now OFF."
        dictation_enabled = False
        dictationOffGrammar.enable()
    else:
        print "Dictation already off."
コード例 #30
0
def rule_changer(enable, name):
    _NEXUS.merger.global_rule_changer(name=name, enable=enable, save=True)
    if name == CORE["pronunciation"]:
        _NEXUS.merger.selfmod_rule_changer(name2="alias", enable=enable, save=True)

class MainRule(MergeRule):
    
	mapping = {
        "configure math fly": 
            Function(utilities.load_config, config_name="settings.toml"),

        "<enable> <name>": Function(rule_changer),

        "reboot dragon": Function(utilities.reboot),

        "rebuild math fly": Function(build),

	}
	extras=[
		generate_ccr_choices(_NEXUS),
        Choice("enable", {
            "enable": True,
            "disable": False
        }),
	]

grammar = Grammar('general')
main_rule = MainRule()
grammar.add_rule(main_rule)
grammar.load()
コード例 #31
0
ファイル: _python.py プロジェクト: sparkvilla/code_by_voice
        # pandas
        "pandas": Text("pd"),
        "pandas head": Text(".head()"),

        # numpy
        "numpy": Text("np"),

        # matplotlib
        "show plot": Text("plt.show()"),
    }


# The main Python grammar rules are activated here
pythonBootstrap = Grammar("python bootstrap")
pythonBootstrap.add_rule(PythonEnabler())
pythonBootstrap.load()

pythonGrammar = Grammar("python grammar")
pythonGrammar.add_rule(PythonControlStructures())
pythonGrammar.add_rule(PythonUsefulCommands())
pythonGrammar.add_rule(PythonDisabler())
pythonGrammar.load()
pythonGrammar.disable()


# Unload function which will be called by natlink at unload time.
def unload():
    global pythonGrammar
    if pythonGrammar: pythonGrammar.unload()
    pythonGrammar = None
コード例 #32
0
def build_grammar(context):
    grammar = Grammar("unreal", context=(context))
    grammar.add_rule(language_rule)
    return grammar
コード例 #33
0
from dragonfly import (Grammar, MappingRule, IntegerRef, Key)


class GlobalMovementRule(MappingRule):
    mapping = {
        'up [<n>]': Key('up:%(n)d'),
        'down [<n>]': Key('down:%(n)d'),
        'left [<n>]': Key('left:%(n)d'),
        'right [<n>]': Key('right:%(n)d'),
        'home': Key('home'),
        'end': Key('end'),
        'enter [<n>]': Key('enter:%(n)d'),
    }
    extras = [IntegerRef('n', 1, 9999)]
    defaults = {'n': 1}


grammar = Grammar('Global Mappings')
grammar.add_rule(GlobalMovementRule())
grammar.load()


def unload():
    global grammar
    if grammar: grammar.unload()
    grammar = None
コード例 #34
0
class SwitchMode:
    def __init__(self, modeSwitcher):
        self.mode = "regular"

        if (SPEECHREC_ENABLED == True and IS_WINDOWS == True):
            # Create a grammar which contains and loads the command rule.
            self.grammar = Grammar(
                "Switch grammar"
            )  # Create a grammar to contain the command    rule.
            twitchRule = TwitchModeRule()
            twitchRule.setModeSwitch(modeSwitcher)
            self.grammar.add_rule(
                twitchRule)  # Add the command rule to the grammar.
            youtubeRule = YoutubeModeRule()
            youtubeRule.setModeSwitch(modeSwitcher)
            self.grammar.add_rule(
                youtubeRule)  # Add the command rule to the grammar.
            browseRule = BrowseModeRule()
            browseRule.setModeSwitch(modeSwitcher)
            self.grammar.add_rule(
                browseRule)  # Add the command rule to the grammar.
            heroesRule = HeroesModeRule()
            heroesRule.setModeSwitch(modeSwitcher)
            self.grammar.add_rule(
                heroesRule)  # Add the command rule to the grammar.
            testingRule = TestingModeRule()
            testingRule.setModeSwitch(modeSwitcher)
            self.grammar.add_rule(
                testingRule)  # Add the command rule to the grammar.
            excelLogModeRule = ExcelLogModeRule()
            excelLogModeRule.setModeSwitch(modeSwitcher)
            self.grammar.add_rule(
                excelLogModeRule)  # Add the command rule to the grammar.

            excelModeRule = ExcelModeRule()
            excelModeRule.setModeSwitch(modeSwitcher)
            self.grammar.add_rule(
                excelModeRule)  # Add the command rule to the grammar.

    def start(self):
        self.grammar.load()
        toggle_speechrec()

    def handle_input(self, dataDicts):
        if (SPEECHREC_ENABLED == True):
            if (IS_WINDOWS == True):
                pythoncom.PumpWaitingMessages()
                sleep(.1)
            else:
                print(
                    "No speech recognition is available on other platforms than windows, exiting mode switching"
                )
                self.exit()
        else:
            print(
                "NO SPEECH RECOGNITION ENABLED - CANNOT SWITCH BETWEEN MODES")
            sleep(.5)

    def exit(self):
        self.grammar.unload()
        toggle_speechrec()
コード例 #35
0
        IntegerRef("pos4", 1, 10),
        IntegerRef("pos5", 1, 10),
        IntegerRef("pos6", 1, 10),
        IntegerRef("pos7", 1, 10),
        IntegerRef("pos8", 1, 10),
        IntegerRef("pos9", 1, 10),
        Dictation("text"),
        Choice("action", actions),
    ],
    defaults={
        "pos1": None
    }
)
global_context = None  # Context is None, so grammar will be globally active.
grammar1 = Grammar("Grid init", context=global_context)
grammar1.add_rule(init_rule)
grammar1.load()


navigate_rule = MappingRule(
    mapping={
        "<pos1> [<pos2>] [<pos3>] [<pos4>] [<pos5>] [<pos6>] [<pos7>] [<pos8>] [<pos9>] [<action>]": Function(mouse_pos),  # @IgnorePep8
        "[left] click": Function(left_click),
        "right click": Function(right_click),
        "double click": Function(double_click),
        "control click": Function(control_click),
        "shift click": Function(shift_click),
        "mark": Function(mouse_mark),
        "drag": Function(mouse_drag),
        "(close|cancel|stop|abort) [[mouse] grid]": Function(hide_grids),  # @IgnorePep8
        "go": Function(go),
コード例 #36
0
from dragonfly import Grammar, CompoundRule, Key, Text, Mouse


# Voice command rule combining spoken form and recognition processing.
class ExampleRule(CompoundRule):
    spec = "do something computer"  # Spoken form of command.

    def _process_recognition(self, node,
                             extras):  # Callback when command is spoken.
        print "I am become death, destroyer of worlds."


class ClickRule(CompoundRule):
    spec = "touch"

    def _process_recognition(self, node, extras):
        action = Mouse("left")
        action.execute()


# Create a grammar which contains and loads the command rule.
grammar = Grammar(
    "example grammar")  # Create a grammar to contain the command rule.
grammar.add_rule(ExampleRule())  # Add the command rule to the grammar.
grammar.add_rule(ClickRule())
grammar.load()
コード例 #37
0
from dragonfly import MappingRule, Text, Grammar


class Aliases(MappingRule):
    mapping = {
        "Rumpelstiltskin": Text("placeholder alias"),
    }


example_grammar = Grammar("alias grammar")
example_grammar.add_rule(Aliases())

example_grammar.load()


def unload():
    global example_grammar
    if example_grammar:
        print "unloading " + __name__ + "..."
        example_grammar.unload()
    example_grammar = None
コード例 #38
0
ファイル: fman.py プロジェクト: mrob95/caster
    }

    extras = [
        IntegerRefST("num", 1, 4),
        Choice(
            "fav", {
                "advent": "adv",
                "(docks | documents)": "docs",
                "(downs | download)": "downs",
                "git caster": "gcast",
                "mike": "mike",
                "user caster": "ucast",
                "uni [work]": "uni",
            }),
    ]
    defaults = {
        "num": 1,
    }


context = AppContext(executable="fman", title="fman")
grammar = Grammar("fman", context=context)
if settings.SETTINGS["apps"]["fman"]:
    if settings.SETTINGS["miscellaneous"]["rdp_mode"]:
        control.nexus().merger.add_global_rule(fmanRule())
    else:
        rule = fmanRule()
        gfilter.run_on(rule)
        grammar.add_rule(fmanRule(name="fman"))
        grammar.load()
コード例 #39
0
ファイル: _testBasicGrammar.py プロジェクト: merrillh/aenea
from dragonfly import Grammar, CompoundRule

# Voice command rule combining spoken form and recognition processing.
class ExampleRule(CompoundRule):
    spec = "do something computer"                  # Spoken form of command.
    def _process_recognition(self, node, extras):   # Callback when command is spoken.
        print "Voice command spoken."

# Create a grammar which contains and loads the command rule.
grammar = Grammar("example grammar")                # Create a grammar to contain the command rule.
grammar.add_rule(ExampleRule())                     # Add the command rule to the grammar.
grammar.load()                                      # Load the grammar.
コード例 #40
0
ファイル: notepadplusplus.py プロジェクト: seekM/caster
            R(Mouse("right") + Key("down:6/5, right/5, down:5/5, enter"),
              rdescript="Notepad++: Remove Style"),
        "preview in browser":
            R(Key("cas-r"), rdescript="Notepad++: Preview In Browser"),

        # requires function list plug-in:
        "function list":
            R(Key("cas-l"), rdescript="Notepad++: Function List"),
    }
    extras = [
        Dictation("text"),
        IntegerRefST("n", 1, 100),
        IntegerRefST("n2", 1, 10),
    ]
    defaults = {"n": 1}


#---------------------------------------------------------------------------

context = AppContext(executable="notepad++")
grammar = Grammar("Notepad++", context=context)

if settings.SETTINGS["apps"]["notepadplusplus"]:
    if settings.SETTINGS["miscellaneous"]["rdp_mode"]:
        control.nexus().merger.add_global_rule(NPPRule())
    else:
        rule = NPPRule(name="notepad plus plus")
        gfilter.run_on(rule)
        grammar.add_rule(rule)
        grammar.load()
コード例 #41
0
        "cap rubber set up remote aliases <text>": Text("RUBBER_ENV=") + Function(lib.format.lowercase_text) + Text(" cap rubber:setup_remote_aliases"),
        "cap rubber set up D N S aliases <text>": Text("RUBBER_ENV=") + Function(lib.format.lowercase_text) + Text(" cap rubber:setup_dns_aliases"),
        "cap rubber add role to <text>": Text("RUBBER_ENV=") + Function(lib.format.lowercase_text) + Text(" cap rubber:roles:add ROLES= ALIAS=") + Function(lib.format.lowercase_text),
        "cap rubber create staging <text>": Text("RUBBER_ENV=") + Function(lib.format.lowercase_text) + Text(" cap rubber:create_staging"),
        "cap rubber destroy staging <text>": Text("RUBBER_ENV=") + Function(lib.format.lowercase_text) + Text(" cap rubber:destroy_staging"),
        "cap rubber monit start": Text("cap rubber:monit:start RUBBER_ENV="),
        "cap rubber monit stop": Text("cap rubber:monit:stop RUBBER_ENV="),
        "cap rubber (postgres|PostgreSQL) start": Text("cap rubber:postgresql:start RUBBER_ENV="),
        "cap rubber (postgres|PostgreSQL) stop": Text("cap rubber:postgresql:stop RUBBER_ENV="),
        }
)

class MyCommandsRule(MappingRule):
    mapping = config.cmd.map

    extras = [
        Dictation("text"),
    ]

global_context = None  # Context is None, so grammar will be globally active.
terminator_grammar = Grammar("Capistrano commands", context=global_context)  # Create this module's grammar.
terminator_grammar.add_rule(MyCommandsRule())  # Add the top-level rule.
terminator_grammar.load()  # Load the grammar.


def unload():
    """Unload function which will be called at unload time."""
    global terminator_grammar
    if grammar:
        grammar.unload()
    grammar = None
コード例 #42
0
ファイル: pycharm.py プロジェクト: drocco007/vox_commands
# (*) Extra keys are used to prevent the system menu from triggering...


commit_context=LinuxAppContext(executable='pycharm', title='Commit Changes')
commit_rule=MappingRule(
    name='commit rule',
    mapping={
        'commit': Key('c-enter'),

        '[Show] diff': Key('s-tab, c-d')
    },
    context=commit_context
)


# Add the action rule to the grammar instance.
grammar.add_rule(example_rule)
grammar.add_rule(commit_rule)


#---------------------------------------------------------------------------
# Load the grammar instance and define how to unload it.

grammar.load()

# Unload function which will be called by natlink at unload time.
def unload():
    global grammar
    if grammar: grammar.unload()
    grammar = None
コード例 #43
0
ファイル: _caster.py プロジェクト: Solar-Plexus/caster
                    }),
              Choice("volume_mode",
                    {"mute": "mute", "up":"up", "down":"down"
                     }),
              generate_ccr_choices.__func__(_NEXUS),
              generate_sm_ccr_choices.__func__(_NEXUS),
              IntegerRefST("monitor", 1, 10)
             ]
    defaults = {"n": 1, "nnv": 1,
               "text": "", "volume_mode": "setsysvolume",
               "enable":-1
               }


grammar = Grammar('general')
grammar.add_rule(MainRule())
grammar.add_rule(Again(_NEXUS))
grammar.add_rule(VanillaAlias(name="vanilla alias"))
grammar.load()

_NEXUS.merger.update_config()
_NEXUS.merger.merge(Inf.BOOT)

if settings.SETTINGS["miscellaneous"]["status_window_enabled"]:
    print("\nWARNING: Status Window is an experimental feature, and there is a known freezing glitch with it.\n")
    utilities.launch_status()

print("*- Starting " + settings.SOFTWARE_NAME + " -*")


if settings.WSR:
コード例 #44
0
class LockRule(CompoundRule):

    spec = config.lang.lock_screen

    def _process_recognition(self, node, extras):
        self._log.debug("%s: locking screen." % self)

        # Put the microphone to sleep.
        natlink.setMicState("sleeping")

        # Lock screen.
        success = ctypes.windll.user32.LockWorkStation()
        if not success:
            self._log.error("%s: failed to lock screen." % self)


# ---------------------------------------------------------------------------
# Create and manage this module's grammar.

grammar = Grammar("lock screen")
grammar.add_rule(LockRule())
grammar.load()


def unload():
    global grammar
    if grammar:
        grammar.unload()
    grammar = None
コード例 #45
0
ファイル: _caster.py プロジェクト: RadixSeven/caster
              Choice("enable_disable",
                    {"enable": 1, "disable": 0
                    }),
              Choice("volume_mode",
                    {"mute": "mute", "up":"up", "down":"down"
                     }),
              generate_CCR_choices.__func__()
             ]
    defaults = {"n": 1, "nnv": 1,
               "text": "", "volume_mode": "setsysvolume",
               "enable":-1
               }


grammar = Grammar('general')
grammar.add_rule(MainRule())
grammar.load()

def unload():
    global grammar
    if grammar: grammar.unload()
    grammar = None
    ccr.unload()
    sikuli.unload()

if settings.SETTINGS["miscellaneous"]["status_window_enabled"]:
    utilities.report("\nWARNING: Status Window is an experimental feature, and there is a known freezing glitch with it.\n")
utilities.report("*- Starting " + settings.SOFTWARE_NAME + " -*")


if __name__ == "__main__":
コード例 #46
0
ファイル: adium.py プロジェクト: dopey/aenea-fork
from dragonfly import (Grammar, Dictation, Context, MappingRule, Pause)
from proxy_nicknames import Key, Text, Events, AppRegexContext

from raul import SelfChoice, processDictation, NUMBERS as numbers

from _mac import *

import aenea

adium_context = aenea.global_context & AppRegexContext(name="Adium")
grammar = Grammar("adium", context=adium_context)

class AlfredCommand(MappingRule):
    mapping = {
        "search": Events("key->code=44&modifier=command"),
        "[<text>]": Events("text->%(text)s")
    }
    extras = [Dictation("text")]
    defaults = {"text":"", "n":1}

grammar.add_rule(AlfredCommand())

grammar.load()

def unload():
  global grammar
  if grammar: grammar.unload()
  grammar = None

コード例 #47
0
    for j in xrange(extras["n"]):
      for sequence, count in macros.get(extras["m"], []):
        for i in xrange(count):
          time.sleep(KEYSTROKE_DELAY)
          for action in sequence:
            action.execute()

class MacroBegin(CompoundRule):
  spec = "begin macro <n>"
  extras = [IntegerRef("n", 0, 100)]

  def _process_recognition(self, node, extras):
    global active_macro
    if active_macro is None:
      active_macro = extras["n"]
      macros[extras["n"]] = []

grammar = Grammar("voiceofarmok", context=df_context)
grammar.add_rule(RepeatRule())
grammar.add_rule(MacroBegin())
grammar.add_rule(MacroEnd())
grammar.add_rule(MacroPlay())

grammar.load()

def unload():
  global grammar
  if grammar:
    grammar.unload()
  grammar = None
コード例 #48
0
ファイル: _globals.py プロジェクト: B-Rich/code-by-voice
rules = MappingRule(
	name = "general",
	mapping = { 
		"slap": Key("enter"),
		"Max when": Key("w-up"),
		"left when": Key("w-left"),
		"right when": Key("w-right"),
		"min win": Key("w-down"),
    "switch apps": Key("alt:down, tab"),
		"switch app": Key("a-tab"),
    "termi": Key("w-b/10, s-tab/10, enter"),
    "foxy": Key("w-b/10, s-tab/10, right:1/10, enter"),
    "foxy reload": Key("w-b/10, s-tab/10, right:1/10, enter/10, f5"),
    "Jimmy": Key("w-b/10, s-tab/10, right:2/10, enter"), 
    "Heidi": Key("w-b/10, s-tab/10, right:3/10, enter"),
    "chrome": Key("w-b/10, s-tab/10, right:4/10, enter"),
    "chrome reload": Key("w-b/10, s-tab/10, right:4/10, enter/10, f5"),
    "bashing": Key("w-b/10, s-tab/10, right:5/10, enter"),
    "code mode": Mimic("\\no-caps-on") + Mimic("\\no-space-on"),
	}
)

grammar = Grammar("general")
grammar.add_rule(rules)
grammar.load()

def unload():
  global grammar
  if grammar: grammar.unload()
  grammar = None
コード例 #49
0
ファイル: emacs.py プロジェクト: jeffshantz/dragonfly-modules
    extras = [
            IntegerRef('n',0,9999),
            Dictation('text')
            ]

    defaults = {
            'n': 1
            }

class EmacsPythonMappings(MappingRule):
    """Emacs mappings for python coding"""
    mapping = {
        'python class': Key('a-colon')+Text('(python-skeleton-class)')+Key('enter'),
        'python (function|method)': Text('def ():')+Key('left:3'),
        'python if': Text('if :')+Key('left'),
    }

context = AppContext(executable="emacs")
grammar = Grammar("GNU Emacs", context=context)
grammar.add_rule(EmacsIdentifiers())
grammar.add_rule(EmacsSymbols())
grammar.add_rule(EmacsGroupingSymbols())
grammar.add_rule(EmacsGlobalMappings())
grammar.add_rule(EmacsPythonMappings())
grammar.load()

def unload():
    global grammar
    if grammar: grammar.unload()
    grammar = None
コード例 #50
0
    mapping = {
        "calibrate <corner> corner":
            R(Function(calibrate)),
        "<chess_letter> <chess_number> <chess_letter2> <chess_number2>":
            R(Function(move)),
        "flip board":
            R(Function(flip))
    }

    extras = [
        Choice("corner", {
            "left top": True,
            "top left": True,
            "right bottom": False,
            "bottom right": False,
        }),
        Choice("chess_letter", LETTERS),
        Choice("chess_letter2", LETTERS),
        Choice("chess_number", NUMBERS),
        Choice("chess_number2", NUMBERS),
    ]

    defaults = {}


# ---------------------------------------------------------------------------
grammar = Grammar(name="chess input")
grammar.add_rule(ChessInputRule())
grammar.load()
コード例 #51
0
ファイル: dragon.py プロジェクト: RadixSeven/caster
        'com off':                      R(Playback([(["command", "mode", "off"], 0.0)]), rdescript="Dragon: Command Mode (Off)"),
        'scratch':                      R(Playback([(["scratch", "that"], 0.0)]), rdescript="Dragon: 'Scratch That'"),
        "reboot dragon":                R(Function(utilities.reboot), rdescript="Reboot Dragon Naturallyspeaking"),
        "fix dragon double":            R(Function(fix_dragon_double), rdescript="Fix Dragon Double Letter"),
        "add word to vocabulary":       R(Function(vocabulary_processing.add_vocab), rdescript="Vocabulary Management: Add"),
        "delete word from vocabulary":  R(Function(vocabulary_processing.del_vocab), rdescript="Vocabulary Management: Delete"),
        "left point":                   R(Playback([(["MouseGrid"], 0.1), (["four", "four"], 0.1), (["click"], 0.0)]), rdescript="Mouse: Left Point"),
        "right point":                  R(Playback([(["MouseGrid"], 0.1), (["six", "six"], 0.1), (["click"], 0.0)]), rdescript="Mouse: Right Point"),
        "center point":                 R(Playback([(["MouseGrid"], 0.1), (["click"], 0.0)]), rdescript="Mouse: Center Point"),
        }
    extras = [
              Dictation("text"),
              Dictation("mim"),
              IntegerRef("n", 1, 1000),
              
             ]
    defaults = {"n": 1, "mim":""}

#---------------------------------------------------------------------------

grammar = None

if not settings.WSR:
    grammar = Grammar("Dragon Naturallyspeaking")
    grammar.add_rule(CommandRule())
    grammar.load()

def unload():
    global grammar
    if grammar: grammar.unload()
    grammar = None
コード例 #52
0
class SwitchMode:

	def __init__(self, modeSwitcher):
		self.mode = "regular"
				
		# Create a grammar which contains and loads the command rule.
		self.grammar = Grammar("Switch grammar")                # Create a grammar to contain the command    rule.
		twitchRule = TwitchModeRule()
		twitchRule.setModeSwitch( modeSwitcher )
		self.grammar.add_rule(twitchRule)                     	# Add the command rule to the grammar.
		youtubeRule = YoutubeModeRule()
		youtubeRule.setModeSwitch( modeSwitcher )		
		self.grammar.add_rule(youtubeRule)                     	# Add the command rule to the grammar.
		browseRule = BrowseModeRule()
		browseRule.setModeSwitch( modeSwitcher )
		self.grammar.add_rule(browseRule)                     	# Add the command rule to the grammar.
		heroesRule = HeroesModeRule()
		heroesRule.setModeSwitch( modeSwitcher )
		self.grammar.add_rule(heroesRule)                     	# Add the command rule to the grammar.
		testingRule = TestingModeRule()
		testingRule.setModeSwitch( modeSwitcher )
		self.grammar.add_rule(testingRule)                     	# Add the command rule to the grammar.
		excelLogModeRule = ExcelLogModeRule()
		excelLogModeRule.setModeSwitch( modeSwitcher )
		self.grammar.add_rule(excelLogModeRule)                  # Add the command rule to the grammar.		
		
		excelModeRule = ExcelModeRule()
		excelModeRule.setModeSwitch( modeSwitcher )
		self.grammar.add_rule(excelModeRule)                  # Add the command rule to the grammar.		

		

	def start( self ):
		self.grammar.load()	
		mute_sound()
		toggle_speechrec()
		
		
	def handle_input( self, dataDicts ):
		pythoncom.PumpWaitingMessages()
		sleep(.1)
		
	def exit( self ):
		self.grammar.unload()		
		toggle_speechrec()
		turn_on_sound()
コード例 #53
0
ファイル: stopgap.py プロジェクト: jamesgecko/aenea
    x = extras["xcoord"]
    y = extras["ycoord"]
    xres, yres = config.SCREEN_RESOLUTION
    x = xres * int(x) / 10
    y = yres * int(y) / 10
    Mouse("[%s, %s]" % (x, y)).execute()

class LaunchBrowser(MappingRule):
  mapping = {
      "chrome browsing":Key("h-f"),
      "chrome login":Key("h-a"),
      "chrome social":Key("h-s"),
      "chrome google":Key("h-g"),
      "chrome secure":Key("h-b"),
    }

grammar.add_rule(LaunchBrowser())
grammar.add_rule(QuadCommand())
grammar.add_rule(MouseClick())

#---------------------------------------------------------------------------
# Load the grammar instance and define how to unload it.

grammar.load()

# Unload function which will be called by natlink at unload time.
def unload():
  global grammar
  if grammar: grammar.unload()
  grammar = None
コード例 #54
0
        }
    extras = [
        Dictation("dict"),
        Dictation("dict2"),
        IntegerRef("1to9", 1, 10),
        NumberRef("int"),
        NumberRef("int2"),
        Choice(
            "zoom", {
                "75": "7",
                "100": "1",
                "page width": "p",
                "text width": "t",
                "whole page": "w",
            }),
    ]


#---------------------------------------------------------------------------

context = AppContext(executable="uedit32")
grammar = Grammar("UltraEdit", context=context)
grammar.add_rule(CommandRule())
grammar.load()


def unload():
    global grammar
    if grammar: grammar.unload()
    grammar = None
コード例 #55
0
ファイル: notepad_foodgroups.py プロジェクト: Erotemic/local
              "an orange":                    "fruit",
              "a hamburger":                  "meat",
              "a [juicy] steak":              "meat",
             }
    extras = [
              Choice("time", time),
              Choice("food", food),
              Dictation("opinion"),
             ]

    def _process_recognition(self, node, extras):
        days_ago  = extras["time"]
        foodgroup = extras["food"]
        print "You ate %s %d days ago." % (foodgroup, days_ago)
        if "opinion" in extras:
            print "You thought it was %s." % (extras["opinion"])

grammar.add_rule(FoodGroupRule())


#---------------------------------------------------------------------------
# Load the grammar instance and define how to unload it.

grammar.load()

# Unload function which will be called by natlink at unload time.
def unload():
    global grammar
    if grammar: grammar.unload()
    grammar = None
コード例 #56
0
rules = MappingRule(
    mapping={
        "new (header|template) preamble": Function(template_preamble),
        "rubber (environment|E N V)": Text("rubber_env."),
        "rubber (environment|E N V) variable": Text("RUBBER_ENV"),
        "host internal IP":
        Text("rubber_instances[rubber_env.host].internal_ip"),
        "define namespace <text>": Text("namespace :%(text)s do"),
    },
    extras=[
        Dictation("text"),
    ],
)

grammar = Grammar("Rubber grammar", context=GlobalDynamicContext())
grammar.add_rule(rules)
grammar.load()
grammar.disable()


def dynamic_enable():
    global grammar
    if grammar.enabled:
        return False
    else:
        grammar.enable()
        return True


def dynamic_disable():
    global grammar
コード例 #57
0
ファイル: vim.py プロジェクト: dopey/aenea-fork
class MacroRule(CompoundRule):
    spec = ("macro <alphanumeric> [<n>]")
    extras = [Alternative(alphanumeric, name="alphanumeric"), IntegerRef("n", 1, 100)]
    defaults = {"n":1}

    def _process_recognition(self, node, extras):
        words = node.words()
        print words

        times = Events('key->key=%d' % extras['n'])
        action = Events('key->key=2&modifier=shift')
        symbol = extras['alphanumeric'][0][0]

        (times + action + symbol + save).execute()

grammar.add_rule(VimMovement())
grammar.add_rule(VimTextManipulation())
grammar.add_rule(VimCommand())
grammar.add_rule(VimVisual())
grammar.add_rule(VimBuffer())
grammar.add_rule(FindRule())
grammar.add_rule(ClipRule())
grammar.add_rule(ReplaceRule())
grammar.add_rule(RepeatRule())
grammar.add_rule(MacroRule())
grammar.add_rule(SearchRule())
grammar.add_rule(SnipRule())

grammar.load()

def unload():
コード例 #58
0
from dragonfly import (Grammar, Function)

from caster.lib import utilities, settings
from caster.lib.dfplus.merge import gfilter
from caster.lib.dfplus.merge.mergerule import MergeRule
from caster.lib.dfplus.state.short import R


class WindowsSpeechRecognitionRule(MergeRule):

    mapping = {
        "reboot windows speech recognition":
        R(Function(utilities.reboot, wsr=True),
          rdescript="Reboot Windows Speech Recognition"),
    }
    extras = []
    defaults = {}


#---------------------------------------------------------------------------

grammar = Grammar("Windows Speech Recognition")

if settings.WSR and settings.SETTINGS["apps"]["wsr"]:
    rule = WindowsSpeechRecognitionRule(name="Windows Speech Recognition")
    gfilter.run_on(rule)
    grammar.add_rule(rule)
    grammar.load()
コード例 #59
0
#In order to make this work, you need Windows Speech Recognition and dragonfly.
#Dragonfly has a bunch of pre-requisites as well that you can find on their Github page. 

from dragonfly import Grammar, MappingRule, Text, Dictation
import pythoncom
import time

test_com = MappingRule(\
name="test",\
mapping = {"write <text>": Text("%(text)s")},\
extras=[Dictation("text"),],)

grammar = Grammar("test grammar")
grammar.add_rule(test_com)
grammar.load()

#Keeps the program running to execute the commands
while True:
    pythoncom.PumpWaitingMessages()
    time.sleep(0.1)
    
コード例 #60
0
        Text("\""),
        "escape single quotes":
        Text("\ ") + Key("left") + Text("\'") + Text("\ ") + Key("left") +
        Text("\'"),
        "escape line":
        Text("\ ") + Key("left") + Text("n"),
        "escape tab":
        Text("\ ") + Key("left") + Text("t"),
        "escape carriage return":
        Text("\ ") + Key("left") + Text("r"),
    }


# The main C# grammar rules are activated here
csBootstrap = Grammar("C sharp bootstrap")
csBootstrap.add_rule(CSEnabler())
csBootstrap.load()

csGrammar = Grammar("C sharp grammar")
csGrammar.add_rule(CSTestRule())
csGrammar.add_rule(CSCommentsSyntax())
csGrammar.add_rule(CSDataTypes())
csGrammar.add_rule(CSComparisonOperators())
csGrammar.add_rule(CSBooleanOperators())
csGrammar.add_rule(CSControlStructures())
csGrammar.add_rule(CSUsefulMethods())
csGrammar.add_rule(CSArithmeticOperators())
csGrammar.add_rule(CSAssignmentOperators())
csGrammar.add_rule(CSMiscellaneousStuff())
csGrammar.add_rule(CSAccessModifiers())
csGrammar.add_rule(CSEscapeSequences())