Rules

This section describes the following classes:

Rule class

class ImportedRule(name)[source]
class Rule(name=None, element=None, context=None, imported=False, exported=True)[source]

Rule class for implementing complete or partial voice-commands.

This rule class represents a voice-command or part of a voice- command. It contains a root element, which defines the language construct of this rule.

Constructor arguments:
  • name (str) – name of this rule. If None, a unique name will automatically be generated.

  • element (Element) – root element for this rule

  • context (Context, default: None) – context within which to be active. If None, the rule will always be active when its grammar is active.

  • imported (boolean, default: False) – if true, this rule is imported from outside its grammar

  • exported (boolean, default: True) – if true, this rule is a complete top-level rule which can be spoken by the user. This should be True for voice-commands that the user can speak.

The self._log logger objects should be used in methods of derived classes for logging purposes. It is a standard logger object from the logger module in the Python standard library.

property active

This rule’s active state. (Read-only)

property context

This rule’s context, under which it will be active and receive recognitions if it is also enabled and its grammar is active.

disable()[source]

Disable this rule so that it is never active to receive recognitions, regardless of whether its context matches or not.

property element

This rule’s root element. (Read-only)

enable()[source]

Enable this rule so that it is active to receive recognitions when its context matches.

property enabled

This rule’s enabled state. An enabled rule is active when its context matches, a disabled rule is never active regardless of context. (Read-only)

property exported

This rule’s exported status. See Exported rules for more info. (Read-only)

property grammar

This rule’s grammar object. (Set once)

property imported

This rule’s imported status. See Imported rules for more info. (Read-only)

property name

This rule’s name. (Read-only)

process_begin(executable, title, handle)[source]

Start of phrase callback.

This method is called when the speech recognition engine detects that the user has begun to speak a phrase. It is called by the rule’s containing grammar if the grammar and this rule are active.

The default implementation of this method checks whether this rule’s context matches, and if it does this method calls _process_begin().

Arguments:
  • executable – the full path to the module whose window is currently in the foreground

  • title – window title of the foreground window

  • handle – window handle to the foreground window

process_recognition(node)[source]

Rule recognition callback.

This method is called when the user has spoken words matching this rule’s contents. This method is called only once for each recognition, and only for the matching top-level rule.

The default implementation of this method does nothing.

Note

This is generally the method which developers should override in derived rule classes to give them custom functionality when a top-level rule is recognized.

set_context(context)[source]

Set the context for this rule, under which it will be active and receive recognitions if it is also enabled and its grammar is active.

Use of this method overwrites any previous context.

Contexts can be modified at any time, but will only be checked when process_begin() is called.

Parameters:

context (Context|None) – context within which to be active. If None, the rule will be active when its grammar is.

value(node)[source]

Start of phrase callback.

This method is called to obtain the semantic value associated with a particular recognition. It could be called from another rule’s value() if that rule references this rule. If also be called from this rule’s process_recognition() if that method has been overridden to do so in a derived class.

The default implementation of this method returns the value of this rule’s root element.

Note

This is generally the method which developers should override in derived rule classes to change the default semantic value of a recognized rule.

BasicRule class

The BasicRule class is designed to make it easy to create a rule from an element tree, rather than building one indirectly via compound element specs.

This rule class has the following parameters to customize its behavior:

  • name (str) – the rule’s name

  • element (Element) – root element for this rule

  • exported – whether the rule is exported

  • context – context in which the rule will be active

Each of these parameters can be passed as a (keyword) arguments to the constructor, or defined as a class attribute in a derived class.

Note

The BasicRule class has only limited support for the “extras” and “defaults” functionality of the dragonfly.grammar.rule_compound.CompoundRule and dragonfly.grammar.rule_mapping.MappingRule classes. By default, the extras dictionary passed to _process_recognition() will only contain an entry for the root element of the rule.

Example usage

The BasicRule class can be used to define a voice-command as follows:

from dragonfly import (BasicRule, Repetition, Alternative, Literal, Text,
                       Grammar)

class ExampleRule(BasicRule):
    # Define a rule element that accepts 1 to 5 (exclusive) repetitions
    # of either 'test one', 'test two' or 'test three'. These commands
    # type their respective numbers in succession using the Text action.
    element = Repetition(
        Alternative((
            Literal("test one", value=Text("1")),
            Literal("test two", value=Text("2")),
            Literal("test three", value=Text("3")),
        )),
        1, 5
    )

# Create a grammar with the example rule and load it.
rule = ExampleRule()
grammar = Grammar("BasicRule Example")
grammar.add_rule(rule)
grammar.load()

The above BasicRule example can be defined without sub-classing:

rule = BasicRule(
    element=Repetition(
        Alternative((
            Literal("test one", value=Text("1")),
            Literal("test two", value=Text("2")),
            Literal("test three", value=Text("3")),
        )),
        1, 5)
)

Class reference

class BasicRule(name=None, element=None, exported=None, context=None)[source]

Rule class for implementing complete or partial voice-commands defined using an element.

Constructor arguments:
  • name (str) – the rule’s name

  • element (Element) – root element for this rule

  • exported (boolean) – whether the rule is exported

  • context (Context) – context in which the rule will be active

context = None
process_recognition(node)[source]

Process a recognition of this rule.

This method is called by the containing Grammar when this rule is recognized. This method collects information about the recognition and then calls self._process_recognition.

  • node – The root node of the recognition parse tree.

value(node)[source]

Start of phrase callback.

This method is called to obtain the semantic value associated with a particular recognition. It could be called from another rule’s value() if that rule references this rule. If also be called from this rule’s process_recognition() if that method has been overridden to do so in a derived class.

The default implementation of this method returns the value of this rule’s root element.

Note

This is generally the method which developers should override in derived rule classes to change the default semantic value of a recognized rule.

CompoundRule class

The CompoundRule class is designed to make it very easy to create a rule based on a single compound spec.

This rule class has the following parameters to customize its behavior:

  • spec – compound specification for the rule’s root element

  • extras – extras elements referenced from the compound spec

  • defaults – default values for the extras

  • exported – whether the rule is exported

  • context – context in which the rule will be active

Each of these parameters can be passed as a (keyword) arguments to the constructor, or defined as a class attribute in a derived class.

Example usage

The CompoundRule class can be used to define a voice-command as follows:

class ExampleRule(CompoundRule):

    spec = "I want to eat <food>"
    extras = [Choice("food", {
                              "(an | a juicy) apple": "good",
                              "a [greasy] hamburger": "bad",
                             }
                    )
             ]

    def _process_recognition(self, node, extras):
        good_or_bad = extras["food"]
        print "That is a %s idea!" % good_or_bad

rule = ExampleRule()
grammar.add_rule(rule)

Class reference

class CompoundRule(name=None, spec=None, extras=None, defaults=None, exported=None, context=None)[source]

Rule class based on the compound element.

Constructor arguments:
  • name (str) – the rule’s name

  • spec (str) – compound specification for the rule’s root element

  • extras (sequence) – extras elements referenced from the compound spec

  • defaults (dict) – default values for the extras

  • exported (boolean) – whether the rule is exported

  • context (Context) – context in which the rule will be active

context = None
process_recognition(node)[source]

Process a recognition of this rule.

This method is called by the containing Grammar when this rule is recognized. This method collects information about the recognition and then calls self._process_recognition.

  • node – The root node of the recognition parse tree.

MappingRule class

The MappingRule class is designed to make it very easy to create a rule based on a mapping of spoken-forms to semantic values.

This class has the following parameters to customize its behavior:

  • mapping – mapping of spoken-forms to semantic values

  • extras – extras elements referenced from the compound spec

  • defaults – default values for the extras

  • exported – whether the rule is exported

  • context – context in which the rule will be active

Each of these parameters can be passed as a (keyword) arguments to the constructor, or defined as a class attribute in a derived class.

Example usage

The MappingRule class can be used to define a voice-command as follows:

class ExampleRule(MappingRule):

    mapping  = {
                "[feed] address [bar]":                Key("a-d"),
                "subscribe [[to] [this] feed]":        Key("a-u"),
                "paste [feed] address":                Key("a-d, c-v, enter"),
                "feeds | feed (list | window | win)":  Key("a-d, tab:2, s-tab"),
                "down [<n>] (feed | feeds)":           Key("a-d, tab:2, s-tab, down:%(n)d"),
                "up [<n>] (feed | feeds)":             Key("a-d, tab:2, s-tab, up:%(n)d"),
                "open [item]":                         Key("a-d, tab:2, c-s"),
                "newer [<n>]":                         Key("a-d, tab:2, up:%(n)d"),
                "older [<n>]":                         Key("a-d, tab:2, down:%(n)d"),
                "mark all [as] read":                  Key("cs-r"),
                "mark all [as] unread":                Key("cs-u"),
                "search [bar]":                        Key("a-s"),
                "search [for] <text>":                 Key("a-s") + Text("%(text)s\n"),
               }
    extras   = [
                Integer("n", 1, 20),
                Dictation("text"),
               ]
    defaults = {
                "n": 1,
               }

rule = ExampleRule()
grammar.add_rule(rule)

Class reference

class MappingRule(name=None, mapping=None, extras=None, defaults=None, exported=None, context=None)[source]

Rule class based on a mapping of spoken-forms to semantic values.

Constructor arguments:
  • name (str) – the rule’s name

  • mapping (dict) – mapping of spoken-forms to semantic values

  • extras (sequence) – extras elements referenced from the spoken-forms in mapping

  • defaults (dict) – default values for the extras

  • exported (boolean) – whether the rule is exported

  • context (Context) – context in which the rule will be active

context = None
process_recognition(node)[source]

Process a recognition of this rule.

This method is called by the containing Grammar when this rule is recognized. This method collects information about the recognition and then calls MappingRule._process_recognition.

  • node – The root node of the recognition parse tree.

property specs

Each spoken-form in the rule. :rtype: list

value(node)[source]

Start of phrase callback.

This method is called to obtain the semantic value associated with a particular recognition. It could be called from another rule’s value() if that rule references this rule. If also be called from this rule’s process_recognition() if that method has been overridden to do so in a derived class.

The default implementation of this method returns the value of this rule’s root element.

Note

This is generally the method which developers should override in derived rule classes to change the default semantic value of a recognized rule.