Search code examples
pythonvoice-recognitionpython-dragonfly

Modal commands with Dragonfly


I'm using dragonfly2, and I want to create a grammar that, like vim, is modal. I want to be able to enable and disable grammars using commands.

For example, if I say link, I have an action that shows a list of possible links on screen with 2-letter labels, so I want the grammar to enable a mode that only accepts 2-letter words. In particular, after saying link, I don't want the grammar to accept any normal command, like another link.

Is this possible?


Solution

  • Ah ha! I just found this in someone else's grammar:

    class PythonEnabler(CompoundRule):
        spec = "Enable Python"                  # Spoken command to enable the Python grammar.
    
        def _process_recognition(self, node, extras):   # Callback when command is spoken.
            pythonBootstrap.disable()
            pythonGrammar.enable()
            print "Python grammar enabled"
    
    class PythonDisabler(CompoundRule):
        spec = "switch language"                  # spoken command to disable the Python grammar.
    
        def _process_recognition(self, node, extras):   # Callback when command is spoken.
            pythonGrammar.disable()
            pythonBootstrap.enable()
            print "Python grammar disabled"
    
    pythonBootstrap = Grammar("python bootstrap")                
    pythonBootstrap.add_rule(PythonEnabler())
    pythonBootstrap.load()
    
    pythonGrammar = Grammar("python grammar")
    pythonGrammar.add_rule(PythonTestRule())
    pythonGrammar.add_rule(PythonCommentsSyntax())
    pythonGrammar.add_rule(PythonControlStructures())
    pythonGrammar.add_rule(PythonDisabler())
    

    So basically, you can simply use some_grammar.disable() or some_grammar.enable!