Element classes¶
Fundamental element classes¶
Dragonfly grammars are built up out of a small set of fundamental building blocks. These building blocks are implemented by the following element classes:
ElementBase
– the base class from which all other element classes are derivedSequence
– sequence of child elements which must all match in the order givenAlternative
– list of possibilities of which only one will be matchedOptional
– wrapper around a child element which makes the child element optionalRepetition
– repetition of a child elementLiteral
– literal word which must be said exactly by the speaker as givenRuleRef
– reference to adragonfly.grammar.rule_base.Rule
object; this element allows a rule to include (i.e. reference) another ruleListRef
– reference to adragonfly.grammar.list.List
objectImpossible
– a special element that cannot be recognizedEmpty
– a special element that is always recognized
The following element classes are built up out of the fundamental classes listed above:
Dictation
– free-form dictation; this element matches any words the speaker says, and includes facilities for formatting the spoken words with correct spacing and capitalizationModifier
– modifies the output of another element by applying a function to it following recognitionDictListRef
– reference to adragonfly.DictList
object; this element is similar to thedragonfly.ListRef
element, except that it returns the value associated with the spoken words instead of the spoken words themselvesRuleWrap
– an element class used to wrap a Dragonfly element into a new private rule to be referenced by the same element or otherRuleRef
elements
See the following documentation sections for additional information and usage examples:
Compound element classes¶
The following special element classes exist as convenient ways of constructing basic element types from string specifications:
Compound
– a special element which parses a string spec to create a hierarchy of basic elements.
Choice
– a special element taking achoice
dictionary argument, interpreting keys asCompound
string specifications and values for what to return when compound specs are successfully decoded during the recognition process.The
choice
argument may also be a list or tuple of strings, in which case the strings are also interpreted asCompound
strings specifications. However, the values returned when compound specs are successfully decoded during the recognition process are the recognized words. Note: these values will be matching part(s) of the compound specs.
ElementBase class¶
-
class
ElementBase
(name=None, default=None)[source]¶ Base class for all other element classes.
- Constructor argument:
- name (str, default: None) – the name of this element; can be used when interpreting complex recognition for retrieving elements by name.
- default (object, default: None) – the default value used if this element is optional and wasn’t spoken
-
_copy_sequence
(sequence, name, item_types=None)[source]¶ Utility function for derived classes that checks that a given object is a sequence, copies its contents into a new tuple, and checks that each item is of a given type.
-
_get_children
()[source]¶ Returns an iterable of this element’s children.
This method is used by the
children()
property, and should be overloaded by any derived classes to give the correct children element.By default, this method returns an empty tuple.
-
children
¶ Iterable of child elements. (Read-only)
-
dependencies
(memo)[source]¶ Returns an iterable containing the dependencies of this element and of this element’s children.
The dependencies are the objects that are necessary for this element. These include lists and other rules.
-
element_tree_string
()[source]¶ Returns a formatted multi-line string representing this element and its children.
-
gstring
()[source]¶ Returns a formatted grammar string of the contents of this element and its children.
The grammar string is of a format similar to that used by Natlink to define its grammars.
-
value
(node)[source]¶ Determine the semantic value of this element given the recognition results stored in the node.
- Argument:
- node –
a
dragonfly.grammar.state.Node
instance representing this element within the recognition parse tree
- node –
a
The default behavior of this method is to return an iterable containing the recognized words matched by this element (i.e. node.words()).
Sequence class¶
-
class
Sequence
(children=(), name=None, default=None)[source]¶ Element class representing a sequence of child elements which must all match a recognition in the correct order.
- Constructor arguments:
- children (iterable, default: ()) – the child elements of this element
- name (str, default: None) – the name of this element
- default (object, default: None) – the default value used if this element is optional and wasn’t spoken
For a recognition to match, all child elements must match the recognition in the order that they were given in the children constructor argument.
Example usage:
>>> from dragonfly.test import ElementTester >>> seq = Sequence([Literal("hello"), Literal("world")]) >>> test_seq = ElementTester(seq) >>> test_seq.recognize("hello world") ['hello', 'world'] >>> test_seq.recognize("hello universe") RecognitionFailure
-
children
¶ Iterable of child elements. (Read-only)
-
dependencies
(memo)[source]¶ Returns an iterable containing the dependencies of this element and of this element’s children.
The dependencies are the objects that are necessary for this element. These include lists and other rules.
Alternative class¶
-
class
Alternative
(children=(), name=None, default=None)[source]¶ Element class representing several child elements of which only one will match.
- Constructor arguments:
- children (iterable, default: ()) – the child elements of this element
- name (str, default: None) – the name of this element
- default (object, default: None) – the default value used if this element is optional and wasn’t spoken
For a recognition to match, at least one of the child elements must match the recognition. The first matching child is used. Child elements are searched in the order they are given in the children constructor argument.
-
children
¶ Iterable of child elements. (Read-only)
-
dependencies
(memo)[source]¶ Returns an iterable containing the dependencies of this element and of this element’s children.
The dependencies are the objects that are necessary for this element. These include lists and other rules.
-
gstring
()[source]¶ Returns a formatted grammar string of the contents of this element and its children.
The grammar string is of a format similar to that used by Natlink to define its grammars.
-
value
(node)[source]¶ The value of an
Alternative
is the value of its child that matched the recognition.
Optional class¶
-
class
Optional
(child, name=None, default=None)[source]¶ Element class representing an optional child element.
- Constructor arguments:
- child (ElementBase) – the child element of this element
- name (str, default: None) – the name of this element
- default (object, default: None) – the default value used if this element is optional and wasn’t spoken
Recognitions always match this element. If the child element does match the recognition, then that result is used. Otherwise, this element itself does match but the child is not processed.
-
children
¶ Iterable of child elements. (Read-only)
-
dependencies
(memo)[source]¶ Returns an iterable containing the dependencies of this element and of this element’s children.
The dependencies are the objects that are necessary for this element. These include lists and other rules.
Repetition class¶
-
class
Repetition
(child, min=1, max=None, name=None, default=None, optimize=True)[source]¶ Element class representing a repetition of one child element.
- Constructor arguments:
- child (ElementBase) – the child element of this element
- min (int, default: 1) – the minimum number of times that the child element must be recognized; may be 0
- max (int, default: None) – the maximum number of times that the child element must be recognized; if None, the child element must be recognized exactly min times (i.e. max = min + 1)
- name (str, default: None) – the name of this element
- default (object, default: None) – the default value used if this element is optional and wasn’t spoken
- optimize (bool, default: True) – whether the engine’s compiler should compile the element optimally
For a recognition to match, at least one of the child elements must match the recognition. The first matching child is used. Child elements are searched in the order they are given in the children constructor argument.
If the optimize argument is set to True, the compiler will ignore the min and max limits to reduce grammar complexity. If the number of repetitions recognized is more than the max value, the rule will fail to match.
-
children
¶ Iterable of child elements. (Read-only)
-
decode
(state)¶ Attempt to decode the recognition stored in the given state.
-
dependencies
(memo)[source]¶ Returns an iterable containing the dependencies of this element and of this element’s children.
The dependencies are the objects that are necessary for this element. These include lists and other rules.
-
get_repetitions
(node)[source]¶ Returns a list containing the nodes associated with each repetition of this element’s child element.
- Argument:
- node (Node) – the parse tree node associated with this repetition element; necessary for searching for child elements within the parse tree
-
gstring
()¶ Returns a formatted grammar string of the contents of this element and its children.
The grammar string is of a format similar to that used by Natlink to define its grammars.
-
value
(node)[source]¶ The value of a
Repetition
is a list containing the values of its child.The length of this list is equal to the number of times that the child element was recognized.
Literal class¶
-
class
Literal
(text, name=None, value=None, default=None, quote_start_str='"', quote_end_str='"', strip_quote_strs=True)[source]¶ Element class representing one or more literal words which must be said exactly by the speaker as given.
Quoted words can be used to potentially improve accuracy. This currently only has an effect if using the Natlink SR engine back-end.
- Constructor arguments:
- text (str) – the words to be said by the speaker
- name (str, default: None) – the name of this element
- value (object, default: the recognized words) – value returned when this element is successfully decoded
- default (object, default: None) – the default value used if this element is optional and wasn’t spoken
- quote_start_str (str, default: “) – the string used for specifying the start of quoted words.
- quote_end_str (str, default: “) – the string used for specifying the end of quoted words.
- strip_quote_strs (bool, default: True) – whether the start and end quote strings should be stripped from this element’s word lists.
-
children
¶ Iterable of child elements. (Read-only)
-
dependencies
(memo)[source]¶ Returns an iterable containing the dependencies of this element and of this element’s children.
The dependencies are the objects that are necessary for this element. These include lists and other rules.
-
gstring
()[source]¶ Returns a formatted grammar string of the contents of this element and its children.
The grammar string is of a format similar to that used by Natlink to define its grammars.
-
value
(node)[source]¶ Determine the semantic value of this element given the recognition results stored in the node.
- Argument:
- node –
a
dragonfly.grammar.state.Node
instance representing this element within the recognition parse tree
- node –
a
The default behavior of this method is to return an iterable containing the recognized words matched by this element (i.e. node.words()).
-
words
¶ The words to be said by the speaker.
RuleRef class¶
-
class
RuleRef
(rule, name=None, default=None)[source]¶ Element class representing a reference to another Dragonfly rule.
- Constructor arguments:
- rule (Rule) – the Dragonfly rule to reference
- name (str, default: None) – the name of this element
- default (object, default: None) – the default value used if this element is optional and wasn’t spoken
-
children
¶ Iterable of child elements. (Read-only)
-
dependencies
(memo)[source]¶ Returns an iterable containing the dependencies of this element and of this element’s children.
The dependencies are the objects that are necessary for this element. These include lists and other rules.
-
gstring
()[source]¶ Returns a formatted grammar string of the contents of this element and its children.
The grammar string is of a format similar to that used by Natlink to define its grammars.
-
value
(node)[source]¶ Determine the semantic value of this element given the recognition results stored in the node.
- Argument:
- node –
a
dragonfly.grammar.state.Node
instance representing this element within the recognition parse tree
- node –
a
The default behavior of this method is to return an iterable containing the recognized words matched by this element (i.e. node.words()).
ListRef class¶
-
class
ListRef
(name, list, key=None, default=None)[source]¶ Element class representing a reference to a Dragonfly List.
- Constructor arguments:
- name (str, default: None) – the name of this element
- list (ListBase) – the Dragonfly List to reference
- key (object, default: None) – key to differentiate between list references at runtime
- default (object, default: None) – the default value used if this element is optional and wasn’t spoken
-
children
¶ Iterable of child elements. (Read-only)
-
dependencies
(memo)[source]¶ Returns an iterable containing the dependencies of this element and of this element’s children.
The dependencies are the objects that are necessary for this element. These include lists and other rules.
-
gstring
()[source]¶ Returns a formatted grammar string of the contents of this element and its children.
The grammar string is of a format similar to that used by Natlink to define its grammars.
-
value
(node)[source]¶ Determine the semantic value of this element given the recognition results stored in the node.
- Argument:
- node –
a
dragonfly.grammar.state.Node
instance representing this element within the recognition parse tree
- node –
a
The default behavior of this method is to return an iterable containing the recognized words matched by this element (i.e. node.words()).
DictListRef class¶
-
class
DictListRef
(name, dict, key=None, default=None)[source]¶ Element class representing a reference to a Dragonfly DictList.
- Constructor arguments:
- name (str, default: None) – the name of this element
- dict (DictList) – the Dragonfly DictList to reference
- key (object, default: None) – key to differentiate between list references at runtime
- default (object, default: None) – the default value used if this element is optional and wasn’t spoken
-
children
¶ Iterable of child elements. (Read-only)
-
decode
(state)¶ Attempt to decode the recognition stored in the given state.
-
dependencies
(memo)¶ Returns an iterable containing the dependencies of this element and of this element’s children.
The dependencies are the objects that are necessary for this element. These include lists and other rules.
-
gstring
()¶ Returns a formatted grammar string of the contents of this element and its children.
The grammar string is of a format similar to that used by Natlink to define its grammars.
-
value
(node)[source]¶ Determine the semantic value of this element given the recognition results stored in the node.
- Argument:
- node –
a
dragonfly.grammar.state.Node
instance representing this element within the recognition parse tree
- node –
a
The default behavior of this method is to return an iterable containing the recognized words matched by this element (i.e. node.words()).
Impossible class¶
-
class
Impossible
(name=None)[source]¶ Element class representing speech that cannot be recognized.
- Constructor arguments:
- name (str, default: None) – the name of this element
Using an
Impossible
element in a Dragonfly rule makes it impossible to recognize via speech or mimicry.-
children
¶ Iterable of child elements. (Read-only)
-
dependencies
(memo)¶ Returns an iterable containing the dependencies of this element and of this element’s children.
The dependencies are the objects that are necessary for this element. These include lists and other rules.
-
gstring
()[source]¶ Returns a formatted grammar string of the contents of this element and its children.
The grammar string is of a format similar to that used by Natlink to define its grammars.
-
value
(node)[source]¶ Determine the semantic value of this element given the recognition results stored in the node.
- Argument:
- node –
a
dragonfly.grammar.state.Node
instance representing this element within the recognition parse tree
- node –
a
The default behavior of this method is to return an iterable containing the recognized words matched by this element (i.e. node.words()).
Empty class¶
-
class
Empty
(name=None, value=True, default=None)[source]¶ Element class representing something that is always recognized.
- Constructor arguments:
- name (str, default: None) – the name of this element
- value (object, default: True) – value returned when this element is successfully decoded (always)
Empty elements are equivalent to children of
Optional
elements.-
children
¶ Iterable of child elements. (Read-only)
-
dependencies
(memo)¶ Returns an iterable containing the dependencies of this element and of this element’s children.
The dependencies are the objects that are necessary for this element. These include lists and other rules.
-
gstring
()[source]¶ Returns a formatted grammar string of the contents of this element and its children.
The grammar string is of a format similar to that used by Natlink to define its grammars.
-
value
(node)[source]¶ Determine the semantic value of this element given the recognition results stored in the node.
- Argument:
- node –
a
dragonfly.grammar.state.Node
instance representing this element within the recognition parse tree
- node –
a
The default behavior of this method is to return an iterable containing the recognized words matched by this element (i.e. node.words()).
Dictation class¶
-
class
Dictation
(name=None, format=True, default=None)[source]¶ Element class representing free dictation.
- Constructor arguments:
- name (str, default: None) – the name of this element
- format (bool, default: True) –
whether the value returned should be a
DictationContainerBase
object. If False, then the returned value is a list of the recognized words - default (object, default: None) – the default value used if this element is optional and wasn’t spoken
Returns a string-like
DictationContainerBase
object containing the recognised words. By default this is formatted as a lowercase sentence. Alternative formatting can be applied by calling string methods like replace or upper on aDictation
object, or by passing an arbitrary formatting function (taking and returning a string) to the apply method.Camel case text can be produced using the camel method. For example:
str_func = lambda s: s.upper() Dictation("formattedtext").apply(str_func) Dictation("snake_text").lower().replace(" ", "_") Dictation("camelText").camel()
-
children
¶ Iterable of child elements. (Read-only)
-
dependencies
(memo)¶ Returns an iterable containing the dependencies of this element and of this element’s children.
The dependencies are the objects that are necessary for this element. These include lists and other rules.
-
gstring
()[source]¶ Returns a formatted grammar string of the contents of this element and its children.
The grammar string is of a format similar to that used by Natlink to define its grammars.
-
value
(node)[source]¶ Determine the semantic value of this element given the recognition results stored in the node.
- Argument:
- node –
a
dragonfly.grammar.state.Node
instance representing this element within the recognition parse tree
- node –
a
The default behavior of this method is to return an iterable containing the recognized words matched by this element (i.e. node.words()).
Modifier class¶
-
class
Modifier
(element, modifier=None)[source]¶ Element allowing direct modification of the output of another element at recognition time.
- Constructor arguments:
- element (Element) – The element to be recognised, e.g.
Dictation
orRepetition
, with appropriate arguments passed. - modifier (function) – A function to be applied to the value of this element when it is recognised.
- element (Element) – The element to be recognised, e.g.
Examples:
# Recognises an integer, returns the integer plus one Modifier(IntegerRef("plus1", 1, 20), lambda n: n+1) # Recognises a series of integers, returns them separated by # commas as a string int_rep = Repetition(IntegerRef("", 0, 10), min=1, max=5, name="num_seq") Modifier(int_rep, lambda r: ", ".join(map(str, r)))
-
children
¶ Iterable of child elements. (Read-only)
-
decode
(state)¶ Attempt to decode the recognition stored in the given state.
-
dependencies
(memo)¶ Returns an iterable containing the dependencies of this element and of this element’s children.
The dependencies are the objects that are necessary for this element. These include lists and other rules.
-
gstring
()¶ Returns a formatted grammar string of the contents of this element and its children.
The grammar string is of a format similar to that used by Natlink to define its grammars.
-
value
(node)[source]¶ The value of an
Alternative
is the value of its child that matched the recognition.
RuleWrap class¶
-
class
RuleWrap
(name, element, default=None)[source]¶ Element class to wrap a Dragonfly element into a new private rule to be referenced by this element or others.
RuleWrap
is a sub-class ofRuleRef
, soRuleWrap
elements can be used in the same way asRuleRef
elements.- Constructor arguments:
- name (str, default: None) – the name of this element
- element (Element) – the Dragonfly element to be wrapped
- default (object, default: None) – the default value used if this element is optional and wasn’t spoken
Examples:
# For saying and processing a Choice element two times. letter = RuleWrap("letter1", Choice("", { "alpha": "a", "bravo": "b", "charlie": "c" })) letter_extras = [ letter, RuleRef(letter.rule, "letter2"), RuleRef(letter.rule, "letter3") ]
-
children
¶ Iterable of child elements. (Read-only)
-
decode
(state)¶ Attempt to decode the recognition stored in the given state.
-
dependencies
(memo)¶ Returns an iterable containing the dependencies of this element and of this element’s children.
The dependencies are the objects that are necessary for this element. These include lists and other rules.
-
gstring
()¶ Returns a formatted grammar string of the contents of this element and its children.
The grammar string is of a format similar to that used by Natlink to define its grammars.
-
value
(node)¶ Determine the semantic value of this element given the recognition results stored in the node.
- Argument:
- node –
a
dragonfly.grammar.state.Node
instance representing this element within the recognition parse tree
- node –
a
The default behavior of this method is to return an iterable containing the recognized words matched by this element (i.e. node.words()).
Compound class¶
-
class
Compound
(spec, extras=None, actions=None, name=None, value=None, value_func=None, elements=None, default=None)[source]¶ Element which parses a string spec to create a hierarchy of basic elements.
- Constructor arguments:
- spec (str) – compound specification
- extras (sequence) – extras elements referenced from the compound spec
- actions (dict) – this argument is currently unused
- name (str) – the name of this element
- value (object, default: None) – value to be returned when this element is successfully decoded If None, then the value(s) of child nodes are used instead
- value_func (callable, default: None) – function to be called for the node value when this element is successfully decoded. If None, then the value(s) of child nodes are used. This argument takes precedence over the value argument if it is present
- elements (sequence) – same as the extras argument
- default (default: None) – the default value of this element
Example:
# Define a command to type the sum of two spoken integers between # 1 and 50 using a Compound element. mapping = { "type <XAndY>": Text("%(XAndY)d"), } extras = [ Compound( # Pass the compound spec and element name. spec="<x> and <y>", name="XAndY", # Pass the internal IntegerRef extras. extras=[IntegerRef("x", 1, 50), IntegerRef("y", 1, 50)], # Pass a value function that adds the two spoken integers # together. value_func=lambda node, extras: extras["x"] + extras["y"]) ]
Choice class¶
-
class
Choice
(name, choices, extras=None, default=None)[source]¶ Element allowing a dictionary of phrases (compound specs) to be recognized to be mapped to objects to be used in an action.
A list or tuple of phrases to be recognized may also be used. In this case the strings are also interpreted as
Compound
string specifications. However, the values returned when compound specs are successfully decoded during the recognition process are the recognized words. Note: these values will be matching part(s) of the compound specs.- Constructor arguments:
- name (str) – the name of this element
- choices (dict, list or tuple) – dictionary mapping recognized phrases to returned values or a list/tuple of recognized phrases
- extras (list, default: None) – a list of included extras
- default (default: None) – the default value of this element
Example using a dictionary:
# Tab switching command, e.g. 'third tab'. mapping = { "<nth> tab": Key("c-%(nth)s"), } extras = [ Choice("nth", { "first" : "1", "second" : "2", "third" : "3", "fourth" : "4", "fifth" : "5", "sixth" : "6", "seventh" : "7", "eighth" : "8", "(last | ninth)": "9", "next" : "pgdown", "previous" : "pgup", }), ]
Example using a list:
# Command for recognizing and typing nth words, e.g. # 'type third'. mapping = { "type <nth>": Text("%(nth)s"), } extras = [ Choice("nth", [ "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", # Note that the decoded value for a compound spec like # this one, when used in a list/tuple of choices, # rather than a dictionary, is the recognized word: # "last" or "ninth". "(last | ninth)", "next", "previous", ]), ]