Skip to content

Instantly share code, notes, and snippets.

@Versatilus
Created December 22, 2018 17:34
Show Gist options
  • Save Versatilus/4bcd8e69c22835dc0cd2d1da7507dc5e to your computer and use it in GitHub Desktop.
Save Versatilus/4bcd8e69c22835dc0cd2d1da7507dc5e to your computer and use it in GitHub Desktop.
Dragonfly Basics

The most common type of grammar is a MappingRule (or MergeRule in Caster). It is built from three variables:

  • a mapping dictionary
  • an extras list
  • and an optional defaults dictionary.

A mapping maps a specially formatted spoken phrase to some Action class, usually some combination of Key, Text, or Function.

A spoken phrase is usually some combination of the following:

  • literal spoken text
  • alternatives separated by | and grouped by ()
  • optional elements enclosed in []
  • and named extras enclosed in <>.

Somewhat counterintuitively, extras are a list of elements labeled by a name passed as the first argument of an initialized class. The most common types of extras are:

  • Choice - a dictionary of key/value pairs - values can be any valid Python type
  • IntegerRef - an integer range
  • Dictation - whatever text is spoken

Unsurprisingly, defaults is a dictionary of default values for extras. It's important to note, though, that an extras element doesn't require a default value. In that case, the rule is simply never matched unless a valid phrase is spoken.

extras are passed as keyword arguments to the appropriate action specified in mapping. Key and Text are both subclasses of DynStrActionBase and use the % string operator to combine those keyword arguments with the string they are initialized with, so all of the rules in the documentation apply.

For example:

from dragonfly import (Choice, Dictation, Function, Grammar, IntegerRef, Key,
                       MappingRule, Text)

def my_function(*args, **kwargs):
    print("Thank you for the %(n)d %(fruit)s. They're my favorite!" % kwargs)

class MyClass(MappingRule):
    mapping = {
        "(I would like | please give me) [<n>] [(package | packages) of] <fruit>":
            Function(my_function),
        "press the escape key <i> (time | times)":
            Key("escape:%(i)d"),
        "please say <words>":
            Text("%(words)s"),
    }
    extras = [
        Choice("fruit", {
            "strawberries": "berries",
            "tomatoes": "'maters"
        }),
        IntegerRef("n", 1, 10),
        IntegerRef("i", 0, 50),
        Dictation("words"),
    ]
    defaults = {"n": 1}

grammar = Grammar("Example 20181221")
grammar.add_rule(MyClass())
grammar.load()

def unload():
    global grammar
    if grammar:
        grammar.unload()
    grammar = None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment