Please refer to theerrata for this document, which may include some normative corrections.
See alsotranslations.
Copyright © 2004W3C®(MIT,ERCIM,Keio), All RightsReserved. W3Cliability,trademark,document use andsoftware licensing rules apply.
This document defines syntax for representing grammars for usein speech recognition so that developers can specify the words andpatterns of words to be listened for by a speech recognizer. Thesyntax of the grammar format is presented in two forms, anAugmented BNF Form and an XML Form. The specification makes the tworepresentations mappable to allow automatic transformations betweenthe two forms.
This section describes the status of this document atthe time of its publication. Other documents may supersede thisdocument. A list of current W3C publications and the latestrevision of this technical report can be found in theW3C technical reports indexat http://www.w3.org/TR/.
This document has been reviewed by W3C Members and otherinterested parties, and it has been endorsed by the Directoras aW3CRecommendation. W3C's role in making the Recommendation is todraw attention to the specification and to promote its widespreaddeployment. This enhances the functionaility and interoperabilityof the Web.
This specification is part of the W3C Speech Interface Frameworkand has been developed within theW3C Voice Browser Activity (activity statement) by participants intheVoice Browser WorkingGroup (W3CMembers only).
The design of SRGS 1.0 has been widely reviewed (see thedisposition of comments) and satisfies the Working Group'stechnical requirements. A list of implementations is included in theSRGS 1.0implementation report, along with the associated test suite.
Comments are welcome onwww-voice@w3.org (archive).SeeW3C mailing list and archive usageguidelines.
The W3C maintains a list ofany patentdisclosures related to this work.
This document defines the syntax for grammar representation. Thegrammars are intended for use by speech recognizers and othergrammar processors so thatdevelopers can specify the words and patterns of words to belistened for by a speech recognizer.
The syntax of the grammar format is presented in two forms, anAugmented BNF (ABNF) Form and an XML Form. Thespecification ensures that the two representations aresemantically mappable to allow automatictransformations between the two forms.
Both the ABNF Form and XML Form have the expressive power of aContext-Free Grammar (CFG). Agrammarprocessor that does not support recursive grammars has theexpressive power of a Finite State Machine (FSM) or regularexpression language. For definitions of CFG, FSM, regularexpressions and other formal computational language theory see, forexample,[HU79]. This form oflanguage expression is sufficient for the vast majority of speechrecognition applications.
This W3C standard is known as the Speech Recognition GrammarSpecification and is modelled on the JSpeech Grammar Formatspecification[JSGF], which isowned by Sun Microsystems, Inc., California, U.S.A.
Agrammar processor is any entity that accepts as inputgrammars as described in this specification.
Auser agent is a grammar processor that accepts userinput and matches that input against a grammar to produce arecognition result that represents the detected input.
As the specification title implies, speech recognizers are animportant class of grammar processor. Another class of grammarprocessor anticipated by this specification is aDual-Tone Multi-Frequency (DTMF)detector. The type of input accepted by a user agent is determinedby themode
or modesof grammars it can process: e.g. speech input for"voice" mode grammars and DTMF input for"dtmf" mode grammars.
For simplicity, throughout this document references to a speechrecognizer apply to other types of grammar processor unlessexplicitly stated otherwise.
Aspeech recognizer is a user agent with the followinginputs and outputs:
The primary use of a speech recognizer grammar is to permit aspeech application to indicate to a recognizer what it shouldlisten for, specifically:
Speech recognizers may also support the Stochastic LanguageModels (N-Gram) Specification[NGRAM]. Both specifications define ways to set up aspeech recognizer to detect spoken input but define the word andpatterns of words by different and complementary means. Somerecognizers permit cross-references between grammars in the twoformats. Therule referenceelement of this specification describes how to reference an N-gramdocument.
The grammar specificationdoes not address a number ofother issues that affect speech recognition performance. Most ofthe following capabilities are addressed by the context in which agrammar is referenced or invoked: for example, through VoiceXML 2.0[VXML2] or through a speechrecognizer API.
The ABNF Form and XML Formare specified to ensurethat the two representations are semantically mappable. It shouldbe possible to automatically convert an ABNF Form grammar to an XMLForm grammar (or the reverse) so that the semantic performance ofthe grammars are identical. Equivalence of semantic performanceimplies that:
The XSL Transformation document inAppendix F demonstrates automatic conversion from XML toABNF. The reverse conversion requires an ABNF parser and atransformational program.
There are inherent limits to the automatic conversion to andFrom ABNF Form and XML Form.
A speech recognizer is capable of matching audio input against agrammar to produce araw text transcription (also known asliteral text) of the detected input. A recognizer may becapable of, but is not required to, perform subsequent processingof the raw text to produce asemantic interpretation ofthe input.
For example, the natural language utterance"I want to booka flight from Prague to Paris" could result in the followingXML data structure. To perform this additional interpretation steprequires semantic processing instructions that may be containedwithin a grammar that defines the legal spoken input or in anassociated document.
<book-flight> <depart>Prague</depart> <arrive>Paris</arrive> </book-flight>
The Speech Recognition Grammar Specification provides syntacticsupport for limited semantic interpretation. Thetag
construct and thetag-format
andtag
declarations provide aplaceholder for instructions to a semantic processor.
TheW3C VoiceBrowser Working Group is presently developing theSemanticInterpretation for Speech Recognition specification[SEM]. That specification defines alanguage that can be embedded in tags within SRGS grammars toperform the interpretation process. The semantic processing isdefined with respect to thelogical parse structure for grammar processing(seeAppendix H). Other tagformats could be used but are outside the scope of the W3Cactivities.
For examples of semantic interpretation in the latest workingdraft see[SEM].
The output of the semantic interpretation processor may berepresented using theNatural Language Semantics MarkupLanguage[NLSML]. ThisXML representation of interpreted spoken input can be used totransmit the result, as input toVoiceXML 2.0[VXML2] processing or in otherways.
The semantic interpretation carried out in the speechrecognition process is typically characterized by:
It is this restricted form of semantic interpretation that thisapproach is intended to support. A VoiceXML application thatreceives a speech result with semantic interpretation willtypically process the user input to carry out a dialog. Theapplication may also perform deeper semantic analysis, for exampleresolving deictic or anaphoric references.
The Speech Recognition Grammar Specification is designed topermit ABNF Form and XML Form grammars to be embedded into otherdocuments. For example, VoiceXML 1.0[VXML1] and VoiceXML 2.0[VXML2] permitinlinegrammars[VXML2§3.1.1.1] in which an ABNF Form grammar or XML Formgrammar is contained within a VoiceXML document.
Embedding an XML Form grammar within an XML document can beachieved with XML namespaces[XMLNS] or by incorporating the grammarXML Schema definition orDTDinto to enclosing document's schema or DTD.
An ABNF Form grammar may be embedded into any XML document ascharacter data. ABNF grammars will often contain angle bracketswhich require special handling within XML. ACDATA section[XML§2.7] or the escape sequences of "<
"and ">
" may be required to create well-formedXML. Note: angle brackets ('<' and '>') are used in ABNF todelimit anyURI,media type orrepeat operator.
anyURI
' primitive as defined in XML Schema Part2: Datatypes[SCHEMA2§3.2.17]. The XML Schema definition follows[RFC2396] and[RFC2732]. The syntaxrepresentation of a URI differs between the ABNF Form and the XMLForm. Any relative URI reference must be resolved according to therules given inSection 4.9.1.[SeeAppendix G for informationon media types for the ABNF and XML Forms of the Speech RecognitionGrammar Specification.]
<http://example.com/file-path>~<media-type>
type
attribute.Alegal rule expansion is any legaltoken,rulereference,tag, or any logicalcombination of legal rule expansions assequence,alternatives,repeated expansion orlanguage-attributed expansion.
A rule expansion is formally aregular expression (see,for example,[HU79]).
Arule definitionassociates a legal rule expansion with a rulename.
Atoken (a.k.a. a terminal symbol) is the part of agrammar that defines words or other entities that may be spoken.Any legal token is alegalexpansion.
For speech recognition, a token is typically an orthographicentity of thelanguage beingrecognized. However, a token may be any string that the speechrecognizer can convert to a phonetic representation.
Token Content: In both theXML Form andABNFForm any unmarked text within a rule definition, exceptexample phrases (XML only) ortag content, istokencontent. The unmarked text is delimited by any syntacticconstruct of the grammar form (see below for details on the ABNFForm and XML Form). For each token content span in a grammar thegrammar processor applies the followingtokenization,white space normalization,token normalization andpronunciation lookupprocesses. All token content in both the XML Form and ABNF Form istreated asCharacters in[XML].(informative: XML specifies Characters by reference to ISO/IEC10646[ISO/IEC 10646] andUnicode[Unicode].)
Tokenization behavior: Text spans containing tokensequences are delimited as follows:
Token type | Form | Example |
Single unquoted token | ABNF & XML | hello |
Single unquoted token:non-alphabetic | ABNF & XML | 2 |
Single quoted token: including whitespace | ABNF & XML | "San Francisco" |
Single quoted token: no whitespace | ABNF & XML | "hello" |
Two tokens delimited by whitespace | ABNF & XML | bon voyage |
Four tokens delimited by whitespace | ABNF & XML | this is a test |
Single XML token in <token> | XML Only | <token>SanFrancisco</token> |
White Space Normalization: White space must benormalized when contained in any token delimited by a <token>elements or by double quotes. Leading and trailing white spacecharacters are stripped. Any token-internal white space characteror sequence is collapsed to a single space character (#x20). Forexample, the following are all normalized to the same string, "SanFrancisco".
"San Francisco" " San Francisco " "San Francisco" " San Francisco "
Because the presence of white space within a token issignificant the following are distinct tokens.
"San Francisco" "SanFrancisco" "San_Francisco"
Token Normalization: Other normalization processes areapplied to the white space normalized token according to thelanguage and the capabilities of the speech recognizer.
Grammar processors may assumeEarly Uniform Normalization as defined in the CharacterModel for the World Wide Web 1.0[CHARMOD §4].
Pronunciation Lookup: To match spoken (audio) input toa grammar a speech recognition must be capable of modelling theaudio patterns of any token in a grammar. Speech recognizers employa diverse set of techniques for performing this key recognitionprocess. The following is an informative description of techniquesthat a speech recognizer may apply based on conventional largevocabulary speech recognition technology.
A large vocabulary speech recognizer converts each normalizedtoken to a phoneme sequence or a set of possible phoneme sequences.Conversion of an orthographic form (token) to the spoken form(phonemes) is a highly language-specific process. In many cases theconversion is even specific to a national variant, regional dialector other variant of the language. For example, for some tokensParisian French, Quebec French and Swiss French will each convertto different pronunciations.
The text-to-phoneme conversion in a large vocabulary speechrecognizer may involve some or all of the followingsub-processes.
Any language is likely to have other specialized processes fordetermining a pronunciation for a token. For example, for Japanesespecial techniques are required for Kanji and each Kana form.
For any language and recognizer there may be variation incoverage and completeness of the language's tokens.
When a grammar processor handles a grammar containing a tokenthat it cannot convert to phonemic form or otherwise use in thespeech recognition processing of audio it should inform the hostingenvironment.
Limitations of token handling: the following isinformative guidance to grammar developers.
The Pronunciation Lexicon activity[LEX] of the W3C Voice Browser Working Group willprovide guidance on the token-handling processes outlinedabove.
Token handling will vary between recognizers and will varybetween languages.
Grammar authors can improve document portability by avoidingcharacters and forms in tokens that do not have obviouspronunciations in the language. For English, the following are waysto handle some orthographic forms:
Any plain text within a rule definition istoken content. TheABNF Syntax (Appendix D) normativelydefines the token parsing behavior.
Alanguage attachment maybe provided for any token. When attached to a token the languagemodifies the handling of that token only.
Informative
The rule expansion of aruledefinition is delimited at the start and end by equals sign('=') and semicolon (';') respectively. Any leading plain text ofthe rule expansion is delimited by ('=') and similarly any finalplain text is closed by semicolon.
Within a rule expansion the following symbols have syntacticfunction and delimit plain text.
Within plain text regions delimited by these characters thetokenization,white space normalization,token normalizationandpronunciation lookupprocesses described above apply.
Anytoken
element explicitly delimits asingle token as described above. Thetoken
element may include an optionalxml:lang
attribute toindicate thelanguage of thecontained token.
Any other character data within arule element (rule definition) oritem element istoken content. Note that character data withintag orexample is not token text.
Any legal rule reference is alegal rule expansion .
Rulenames: Everyruledefinition has a local name that must be unique within thescope of the grammar in which it is defined. A rulename must matchthe"Name" Production of XML 1.0[XML §2.3] and be a legal XML ID.Section 3.1 documents the rule definitionmechanism and the legal naming of rules.
This table summarizes the various forms of rule reference thatare possible within and across grammar documents.
Note: an XML Form grammar document must provide one and only oneof theuri
orspecial
attributes on aruleref
element. There is no equivalent constraint inABNF since the syntactic forms are distinct.
Reference type | ABNF Form | XML Form |
2.2.1:Explicit local rule reference | $rulename | <rulerefuri="#rulename"/> |
2.2.2:Explicit reference to a named rule of agrammar identified by aURI | $<grammarURI#rulename> | <rulerefuri="grammarURI#rulename"/> |
2.2.2:Implicit reference to theroot rule of a grammar identified by aURI | $<grammarURI> | <rulerefuri="grammarURI"/> |
2.2.2:Explicit reference to a named rule of a grammaridentified by aURI with amedia type | $<grammarURI#rulename>~<media-type> | <rulerefuri="grammarURI#rulename" type="media-type"/> |
2.2.2:Implicit reference to the root rule of a grammaridentified by aURI with amedia type | $<grammarURI>~<media-type> | <ruleref uri="grammarURI"type="media-type"/> |
2.2.3:Special rule definitions | $NULL | <rulerefspecial="NULL"/> |
When referencing rules defined locally (defined in the samegrammar as contains the reference), always use a simple rulenamereference which consists of the local rulename only. The ABNF Formand XML Form have a different syntax for representing a simplerulename reference.
ABNF Form
The simple rulename reference is prefixed by a "$"character.
$city$digitXML Form
The
ruleref
element is an empty element with auri
attribute that specifies the rule reference as asame-document referenceURI[RFC2396]: that is, the attribute consists only of thenumber sign ('#') and the fragment identifier that indicates thelocally referenced rulename.<ruleref uri="#city"/><ruleref uri="#digit"/>
References to rules defined in other grammars are legal underthe conditions defined inSection 3.The external reference must identify the external grammar byURI and may identify aspecific rule within that grammar. If the fragment identifier thatwould indicate a rulename is omitted, then the referenceimplicitly targets theroot
rule of the external grammar.
Any externally-referenced rule may beactivated forrecognition. That is it may define the top-level syntax of spokeninput. For instance, VoiceXML[VXML2] grammar activation may explicitly reference oneor more public rules (seeSection3.2) and/or implicitly reference the root rule (seeSection 4.7).
A URI reference is illegal if the referring document andreferenced document have different modes. For instance, it isillegal to reference a "dtmf" grammar from a "voice" grammar. (SeeSection 4.6 for additional detailon modes).
A resource indicated by anURI reference may be available in one or moremedia types. The grammar authormay specify the preferred media-type via thetype
attribute (XML form) or in angle braces following the URI (ABNFform).When the content represented by a URI is available inmany data formats, a grammar processor may use thepreferredmedia-type to influence which of the multiple formats isused. For instance, on a server implementing HTTP contentnegotiation, the processor may use thepreferredmedia-type to order the preferences in the negotiation.
The resource representation delivered by dereferencing the URIreference may be considered in terms of two types. Thedeclared media-type is the asserted value for the resourceand theactual media-type is the true format of its content.The actual media-type should be the same as the declaredmedia-type, but this is not always the case (e.g. a misconfiguredHTTP server might returntext/plain
for anapplication/srgs+xml
document). A specific URI schememay require that the resource owner always, sometimes, or neverreturn a media-type. The declared media-type is the value returnedby the resource owner or, if none is returned, the preferred mediatype given in the grammar. There may be no declared media-type ifthe resource owner does not return a value and no preferred type isspecified. Whenever specified, the declared media-type isauthoritative.
Three special cases may arise. The declared media-type may notbe supported by the processor; this is an error. The declaredmedia-type may be supported but the actual media-type may notmatch; this is also an error. Finally, there may be no declaredmedia-type; the behavior depends on the specific URI scheme and thecapabilities of the grammar processor. For instance, HTTP 1.1allows document introspection (seeRFC 2616, section 7.2.1), the data scheme falls back toa default media type, and local file access defines no guidelines.The following table provides some informative examples:
HTTP 1.1 request | Local file access | |||
Media-type returned by theresource owner | text/plain | application/srgs+xml | <none> | <none> |
Preferred media-typeappearing in the grammar | Not applicable; the returned type takesprecedence | application/srgs+xml | <none> | |
Declared media-type | text/plain | application/srgs+xml | application/srgs+xml | <none> |
Behavior if the actualmedia-type is application/srgs+xml | Error; the declared andactual types do not match | The declared and actual types match;success if application/srgs+xml is supported by the grammarprocessor; otherwise an error | Scheme specific; the grammar processormight introspect the document to determine the type. |
SeeAppendix G for a summary ofthe status for media types for ABNF Form and XML Form grammars.
ABNF Form
In ABNF an external reference by URI is represented by a dollarsign ('$') followed immediately by either anABNF URI orABNF URI with media type. There must be nowhite space between the dollarsign and the URI.
// References to specific rules of an external grammar$<http://grammar.example.com/world-cities.gram#canada>$<http://grammar.example.com/numbers.gram#digit>//Implicit reference to the root rule of an external grammar$<../date.gram>// References with associated media types$<http://grammar.example.com/world-cities.gram#canada>~<application/srgs>$<../date.gram>~<application/srgs>
Note: the media type of
"application/srgs"
has beenrequested for ABNF Form grammars. SeeAppendix G for details.XML Form
An XML rule reference is represented by a
ruleref
element with auri
attribute that defines theURI of the referenced grammar and rulewithin it. If a fragment identifier is appended then the identifierindicates a specific rulename being referenced. If the fragmentidentifier is omitted then the reference is(implicitly) to the root rule of the referencedgrammar.The optional
type
attribute specifies themedia type of the grammarcontaining the reference.<!-- References to specific rules of an external grammar --><ruleref uri="http://grammar.example.com/world-cities.grxml#canada"/><ruleref uri="http://grammar.example.com/numbers.grxml#digit"/><!--Implicit reference to the root rule of an external grammar --><ruleref uri="../date.grxml"/><!-- References with associated media types --><ruleref uri="http://grammar.example.com/world-cities.grxml#canada" type="application/srgs+xml"/><ruleref uri="../date.grxml" type="application/srgs+xml"/>Note: the media type
"application/srgs+xml"
hasbeen requested for XML Form grammars. SeeAppendix G for details on media types for grammars.
Several rulenames are defined to have specific interpretationand processing by a speech recognizer. A grammar must not redefinethese rulenames.
In the ABNF Form a special rule reference is syntacticallyidentical to alocal rulereference. However, the names of the special rules arereserved to prevent aruledefinition with the same name.
In the XML Form a special rulename is represented with thespecial
attribute on aruleref
element.It is illegal to provide both thespecial
and theuri
attributes.
ABNF Form:$NULL
XML Form:<ruleref special="NULL"/>
ABNF Form:$VOID
XML Form:<ruleref special="VOID"/>
ABNF Form:$GARBAGE
XML Form:<ruleref special="GARBAGE"/>
$location = $city $GARBAGE $state;
<rule> <ruleref uri="#city"/> <ruleref special="GARBAGE"/> <ruleref uri="#state"/></rule>
The W3C Voice Browser Working Group has released a Working Draftfor the Stochastic Language Models (N-Gram) Specification[NGRAM]. These two specificationsrepresent different and complementary ways of informing a speechrecognizer of which words and patterns of words to listen for.
A speech recognizer may choose to support the Speech RecognitionN-Gram Grammar Specification in addition to the speech recognitiongrammar defined in this document.
If a speech recognizer supports both grammar representations itmay optionally support references between the two formats. Grammarsdefined in the ABNF Form or XML Form may reference start symbols ofN-Gram documents and vice versa.
The syntax for referencing an N-Gram is the same as referencingexternally defined ABNF Form or XML Form grammar documents. A mediatype is recommended on a reference to an N-gram document. TheWorking Group has not yet applied for a type on N-gram documents sono example is given. The fragment identifier (a rulename whenreferencing ABNF Form and XML Form grammars) identifies astartsymbol as defined by the N-Gram specification. If the startsymbol is absent the N-Gram, as a whole, is referenced as definedin the N-Gram specification.
ABNF Form
URI references to N-Gramdocuments follow the same syntax as references to other ABNF or XMLForm grammar documents. The following are examples of references toan N-Gram document via anexplicitrule reference and an implicit reference to theroot rule.
$<http://grammar.example.com/ngram.xml#StartSymbol>$<http://grammar.example.com/ngram.xml>XML Form
URI references to N-Gramdocuments follow the same syntax as reference to other ABNF Formand XML Form grammar documents. The following are examples ofreferences to an N-Gram document via anexplicit rule reference and an implicitreference to theroot rule.
<ruleref uri="http://grammar.example.com/ngram.xml#StartSymbol"/><ruleref uri="http://grammar.example.com/ngram.xml"/>
Asequence of legal rule expansions is itself alegal rule expansion.
The sequence of rule expansions implies the temporal order inwhich the expansions must be detected by theuser agent. This constraint applies to sequences oftokens, sequences of rule references, sequences of tags,parentheticals and all combinations of these rule expansions.
Both the ABNF Form and XML Form provide syntax for encapsulatingany expansion. This is used, for example, to attach arepeat operator, alanguage identifier or to ensure correctprecedence in parsing (ABNF only).
ABNF Form
A sequence of legal expansions separated bywhite space is a legalexpansion.
A legal expansion surrounded by parentheses ('(' and ')') is alegal expansion.
this is a test // sequence of tokens$action $object // sequence of rule referencesthe $object is $color // sequence of tokens and rule references(fly to $city) // parentheses for encapsulationSpecial cases
An empty parenthetical is legal as is a parenthetical containingonlywhite space; e.g.'()' or '( )'. Both forms are equivalent to$NULL and a grammar processor will behave as ifthe parenthetical were not present.
// equivalent sequencesphone homephone ( ) homeXML Form
A sequence of XML rule expansion elements (
<ruleref>
,<item>
,<one-of>
,<token>
<tag>
) and CDATA sections containing spaceseparated tokens must be recognized in temporal sequence. (The onlyexception is where one or more "item" elements appear within aone-of
element.)An
item
element can surround any expansion topermit arepeat attribute orlanguage identifier to beattached. Theweight
attribute ofitem
isignored unless the element appears within aone-of
element.<!-- sequence of tokens -->this is a test<!--sequence of rule references--><ruleref uri="#action"/> <ruleref uri="#object"/><!--sequence of tokens and rule references-->the <ruleref uri="#object"/> is <ruleref uri="#color"/><!-- sequence container --><item>fly to <ruleref uri="#city"/> </item>Special cases
An empty item element is legal as is an item element containingonlywhite space. Bothforms are equivalent to aNULLreference and a grammar processor will behave as if the item werenot present.
<!-- equivalent sequences -->phone homephone <item/> homephone <item></item> homephone <item> </item> home
Any set ofalternative legal rule expansions is itselfalegal rule expansion. For input tomatch a set of alternative rule expansions it must match one of theset of alternative expansions. A set of alternatives must containone or more alternatives.
Any set of alternatives may be labeled with alanguage attachment. In the XML Form anxml:lang
attribute ispresent on theone-of
element. In the ABNF Form toensure correct precedence the set of alternatives must bedelimited by parentheses with theABNF language attachment immediatelyfollowing.
A weight may be optionally provided for any number ofalternatives in an alternative expansion. Weights are simplepositive floating point values without exponentials. Legal formatsare"n"
,"n."
,".n"
and"n.n"
where"n"
is a sequence of one ormany digits.
A weight is nominally a multiplying factor in the likelihooddomain of a speech recognition search. A weight of 1.0 isequivalent to providing no weight at all. A weight greater than"1.0" positively biases the alternative and a weight less than"1.0" negatively biases the alternative.
[JEL98] and[RAB93] are informative references onthe topic of speech recognition technology and the underlyingstatistical framework within which weights are applied.
Grammar authors and speech recognizer developers should be awareof the following limitations upon the definition and application ofweights as outlined above.
ABNF Form
A set of alternative choices is identified as a list of legalexpansions separated by the vertical bar symbol. If necessary, theset of alternative choices may be delimited by parentheses.
Michael | Yuriko | Mary | Duke | $otherNames(1 | 2 | 3)A
weight
issurrounded by forward slashes and placed before each item in thealternatives list./10/ small | /2/ medium | large/3.1415/ pie | /1.414/ root beer | /.25/ colaSpecial Cases
It is legal for an alternative to be a reference to$NULL, an empty parenthetical or asingle tag. In each case the input is equivalent to matching $NULLand as a result the other alternatives are optional.
// Legal$rule1 = word | $NULL;$rule2 = () | word;$rule3 = word | {TAG-CONTENT};An empty alternative (white space only) is not legal.
// ILLEGAL$rule1 = a | | b;$rule2 = | b;$rule3 = a |;The following construct is interpreted as a single weightedalternative.
// Legal$rule1 = /2/ word;$rule2 = /2/ {TAG-CONTENT};$rule3 = /2/ $NULL;XML Form
The
one-of
element identifies a set of alternativeelements. Each alternative expansion is contained in aitem
element. There must be at least oneitem
element contained within aone-of
element.Weights are optionallyindicated by theweight
attribute on theitem
element.<one-of> <item>Michael</item> <item>Yuriko</item> <item>Mary</item> <item>Duke</item> <item><ruleref uri="#otherNames"/></item></one-of><one-of><item>1</item> <item>2</item> <item>3</item></one-of><one-of> <item weight="10">small</item> <item weight="2">medium</item> <item>large</item></one-of><one-of> <item weight="3.1415">pie</item> <item weight="1.414">root beer</item> <item weight=".25">cola</item></one-of>Special cases
A
one-of
element containing a single item is legaland requires that input match the single item. The single item maybe optionally weighted.<one-of> <item>word</item></one-of><one-of> <item weight="2.0">word</item></one-of>Is it legal for an alternative to be a reference toNULL, an empty item or a single tag. Ineach case the input is equivalent to matching NULL and as a resultthe other alternatives are optional.
<one-of> <item>word</item> <item/></one-of><one-of> <item>word</item><item> <ruleref special="NULL"/> </item></one-of><one-of> <item>word</item> <item> <tag>TAG-CONTENT</tag> </item></one-of>
Anyrepeated legal rule expansion is itself alegal rule expansion.
Operators are provided that define a legal rule expansion asbeing another sub-expansion that is optional, that is repeated zeroor more times, that is repeated one or more times, or that isrepeated some range of times.
ABNFForm Example | XMLForm Example | Behavior |
<n> <6> | repeat="n" repeat="6" | The contained expansion is repeatedexactly "n" times. "n" must be "0" or a positive integer. |
<m-n> <4-6> | repeat="m-n" repeat="4-6" | The contained expansion is repeatedbetween "m" and "n" times (inclusive). "m" and "n" must both be "0"or a positive integer and "m" must be less than or equal to"n". |
<m-> <3-> | repeat="m-" repeat="3-" | The contained expansion is repeated "m"times or more (inclusive). "m" must be "0" or a positive integer.For example, "3-" declares that the contained expansion can occurthree, four, five or more times. |
<0-1> [...] | repeat="0-1" | The contained expansion isoptional. |
As indicated in the table above, an expansion that can occur 0-1times is optional. Because optionality is such a common form theABNF syntax provides square brackets as a special operator forrepresenting optionality.
A repeat of "0-" indicates that an expansion can occur zerotimes, once or any number of multiple times. In regular expressionlanguages this is often represented by theKleene star('*') which is reserved but not used in ABNF.
A repeat of "1-" indicates that an expansion can occur once orany number of multiple times. In regular expression languages thisis often represented by thepositive closure ('+') whichis reserved but not used in ABNF.
Although both ABNF and XML support a grammar that permits anunbounded number of input tokens it is not the case that users willspeak indefinitely. Speech recognition can perform more effectivelyif the author indicates a more limited range of repeatoccurrences.
Where a number of possible repetitions (e.g. <m-> or<m-n> (n > 0) but not <0>) is expressed on aconstruct whose only content is one or moretag elements, the behavior of the grammar processor isnot defined and will be specific to individual implementations.
Any number of non-optional repetitions (e.g., <m-n>;m>0) ofVOID is equivalent toa singleVOID.
The behavior of a grammar processor in handling any number ofrepetitions ofNULL is notdefined and will be specific to individual implementations.
If the number of repetitions for any expansion can be only zero(i.e. <0> or <0-0>) then the expansion is equivalent toNULL.
Any repeat operator may specify an optional repeat probability.The value indicates the probability of successive repetition of therepeated expansion.
A repeat probability value must be in the floating pointingrange of "0.0" to "1.0" (inclusive). Values outside this range areillegal. The floating point format is one of "n", "n.", "n.nnnn",".nnnn" (with any number of digits after the dot).
Note: repeat probabilities andweights are different logical entities and have adifferent impact upon a speech recognition search.
Informative example: A simple example is an optional expansion(zero or one occurrences) with a probability — say "0.6". Thegrammar indicates that the chance that the expansion will bematched is 60% and that the chance that the expansion will not bepresent is 40%.
When no maximum is specified in a range (m-) the probabilitiesdecay exponentially.
Grammar authors and speech recognizer developers should be awareof the following limitations upon the definition and application ofrepeat probabilities as outlined above.
Useful references on statistical models of speech recognitioninclude[JEL98] and[RAB93].
ABNF Form
The following are postfix operators:
<m-n><m-> <m>
. A postfix operator is logicallyattached to the preceding expansion. Postfix operators have highprecedence and so are tightly bound to the immediately precedingexpansion (seeSection 2.8).Optional expansions may be delimited by square brackets:
[expansion]
. Alternatively, an optional expansion isindicated by the postfix operator "<0-1>
".The following symbols arereserved for future use inABNF: '*', '+', '?'. These symbols must not be used at any place ina grammar where the syntax currently permits a repeat operator.
// the token "very" is optional[very]very <0-1>// the rule reference $digit can occur zero, one or many times$digit <0->// the rule reference $digit can occur one or more times$digit <1->// the rule reference $digit can occur four, five or six times$digit <4-6>// the rule reference $digit can occur ten or more times$digit <10->// Examples of the following expansion// "pizza"// "big pizza with pepperoni"// "very big pizza with cheese and pepperoni"[[very] big] pizza ([with | and] $topping) <0->Repeat probabilities are only supported in the range form. Theprobability is delimited by slash characters and contained withinthe angle brackets:
<m-n /prob/>
and<m- /prob/>
.// the token "very" is optional and is 60% likely to occur// and 40% likely to be absent in inputvery <0-1 /0.6/>// the rule reference $digit must occur two to four times // with 80% probability of recurrence$digit <2-4 /.8/>XML Form
The
item
element has arepeat
attribute that indicates the number of times the containedexpansion may be repeated. The following example illustrates theaccepted values of the attribute.<!-- the token "very" is optional --><item repeat="0-1">very</item><!-- the rule reference to digit can occur zero, one or many times --><item repeat="0-"> <ruleref uri="#digit"/> </item><!-- the rule reference to digit can occur one or more times --><item repeat="1-"> <ruleref uri="#digit"/> </item><!-- the rule reference to digit can occur four, five or six times --><item repeat="4-6"> <ruleref uri="#digit"/> </item><!-- the rule reference to digit can occur ten or more times --><item repeat="10-"> <ruleref uri="#digit"/> </item><!-- Examples of the following expansion --><!-- "pizza" --><!-- "big pizza with pepperoni" --><!-- "very big pizza with cheese and pepperoni" --><item repeat="0-1"> <item repeat="0-1"> very </item> big </item> pizza<item repeat="0-"> <item repeat="0-1"> <one-of> <item>with</item> <item>and</item> </one-of> </item> <ruleref uri="#topping"/></item>The
repeat-prob
on the item element carries therepeat probability. Repeat probabilities are supported on any itemelement but are ignored if the repeat attribute is not alsospecified.<-- The token "very" is optional and is 60% likely to occur. --><-- Means 40% chance that "very" is absent in input --><item repeat="0-1" repeat-prob="0.6">very</item><-- The rule reference to digit must occur two to four times --><-- with 80% probability of recurrence. --><item repeat="2-4" repeat-prob=".8"> <ruleref uri="#digit"/> </item>
Atag is alegal ruleexpansion(a tag can also be declared in the grammarheader - seeS4.1).
Atag
is anarbitrary string that may beincluded inline within any legal rule expansion. Any number of tagsmay be included inline within a rule expansion.
Tags do not affect the legal word patterns defined by thegrammars or the process of recognizing speech or other input givena grammar.
Tags may contain content forsemantic interpretation. The semantic interpretationprocesses may affect the recognition result.
Language attachments have noeffect upon tags.
Thetag format declarationindicates the content type of all tags in a grammar.
It is legal to use atag
as a stand-aloneexpansion. For example, a rule may expand to a single tag and notokens.
$rule = {TAG-CONTENT};
<rule><tag>TAG-CONTENT</tag></rule>
ABNF Form
A
tag
is delimited by either a pair of opening andclosing curly brackets — '{' and '}' — or by the following3-character sequences which are considered very unlikely to occurwithin a tag — '{!{' and '}!}'. A tag delimited by single curlybrackets cannot contain the single closing curly bracket character('}'). A tag delimited by the 3-character sequence cannot containthe closing 3-character sequence ('}!}').The tag content is all text between the opening and closingcharacter sequences including leading and trailingwhite space. The contents of thetag are not parsed by the grammar processor.
Tag precedence is the same as for rule references and tokens. Inthe first example below there is a sequence of six space-separatedexpansions (3 tokens, a tag, a token and a tag). In the secondexample, the alternative is a choice between a sequence containinga token and a tag or a sequence containing a rule reference and atag.
$rule1 = this is a {TAG-CONTENT-1} test {TAG-CONTENT-2};$rule2 = open {TAG-CONTENT-1} | $close {TAG-CONTENT-2};$rule3 = {!{ a simple tag containing { and } needs no escaping }!};XML Form
A
tag
element can be a direct child of theitem
andrule
elements. The content oftag
is CDATA.<rule>this is a <tag>TAG-CONTENT-1</tag> test <tag>TAG-CONTENT-2</tag> </rule><rule> <one-of> <item> open <tag>TAG-CONTENT-1</tag> </item> <item> <ruleref uri="#close"/> <tag>TAG-CONTENT-2</tag> </item> </one-of></rule>
Anylegal rule expansion that hasan attachedlanguageidentifier is itself a legal rule expansion. Both the ABNF Formand the XML Form permit a legal language identifier to be attachedto anytoken,sequence orset ofalternatives(Note thatrulereference does not permit a language identifier to beattached). The syntax for theABNF Form and for theXML Form are provided below.
The language declaration for a rule expansion affects only thecontained content. Moreover, the language declaration affects onlythe handling oftokens in thecontained content and does not affecttags orrulereferences. The application of language to token handling andparticularly to pronunciation lookup is described inSection 2.1.
By default a grammar is a single language document with alanguage identifierprovided in thelanguagedeclaration in thegrammarheader (seeSection 4.5). Alltokens within that grammar, unless otherwise declared, will behandled according to the grammar's language.
In situations where applications target a multilingual usercommunity, grammars that contain words in more than one languagemay be needed. For example, in response to a prompt such as:"Do you want to talk to André Prévost?" (acombination of an English sentence with a French name), theresponse may be either"yes" or"oui".
The Speech Recognition Grammar Specification permits one grammarto collect input from more than one language. The specificationalso permits multiple grammars each with a separate single languageto be used in parallel. The specification also permits a singleinput utterance to contain more than one language. Finally, thespecification permits any combination of the above: for example,parallel grammars each with multi-lingual capability.
Not all user agents are required to support all languages, orindeed any or all of the multi-lingual capabilities. Theconformance requirements regarding multi-lingual support for XMLForm grammar processors and ABNF Form grammar processors are thesame and are laid out inSection5.4 andSection 5.6respectively.
There is a related challenge for multilingual applications thatdeal with proper names (people, streets, companies, etc.) that maybe spoken with different pronunciations or accents depending uponthe language of origin and the speaking language. It is oftenimpossible to predict the language that users will use to pronouncecertain tokens. In fact, users may actually use different languagesfor different words in the same sentence, and in unpredictableways. For instance, the name "Robert Jones" might be pronounced bya French-speaking user using the French pronunciation for "Robert"but an English pronunciation for "Jones", whereas a mono-lingualEnglish speaker would use the English pronunciation for bothwords.
Language scoping: language declarations are scopedlocally to a document and to a rule definition. In XML terminology,the language attribute is inherited down the document tree. Where alanguage change encompasses a reference to another grammar, thereferenced rule and its containing grammar define the language ofthe reference expansion. The language in effect at the point of therule reference does not have any effect upon the referencedrule.
Language and results: The language used in therecognition of a token is not considered a part of the speechresult even in the case that a language declaration is associatedwith a token.
ABNF Form
In the ABNF Form alanguage identifier may be right-attached to anylegal rule expansionexceptrule reference. Theattachment is an exclamation point character ('!') followed by alegal language identifier without interveningwhite space.
The language attachment has higherprecedence thansequences oralternatives. To attach a language to these ruleexpansion types the expansion should be delimited by parentheses(seeSection 2.3).
#ABNF 1.0 ISO-8859-1;// Default grammar language is US Englishlanguage en-US;// Single language attachment to tokens// Note that "fr-CA" (Canadian French) is applied to only// the word "oui" because of precedence rules$yes = yes | oui!fr-CA;// Single language attachment to an expansion$people1 = (Michel Tremblay | André Roy)!fr-CA;// Handling language-specific pronunciations of the same word// A capable speech recognizer will listen for Mexican Spanish and// US English pronunciations.$people2 = Jose!en-US; | Jose!es-MX;/** * Multi-lingual input possible * @example may I speak to André Roy * @example may I speak to Jose */public $request = may I speak to ($people1 | $people2);XML Form
XML 1.0[XML §2.12]defines the
xml:lang
attribute for languageidentification. The attribute provides a singlelanguage identifier for thecontent of the element on which it appears. Thexml:lang
attribute may be attached toone-of
,token
anditem
. It applies the token handling ofscoped tokens.<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0//EN" "http://www.w3.org/TR/speech-grammar/grammar.dtd"> <!-- the default grammar language is US English --><grammar xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xml:lang="en-US" version="1.0"> <!-- single language attachment to tokens "yes" inherits US English language "oui" is Canadian French language --> <rule> <one-of> <item>yes</item> <item xml:lang="fr-CA">oui</item> </one-of> </rule> <!-- Single language attachment to an expansion --> <rule> <one-of xml:lang="fr-CA"> <item>Michel Tremblay</item> <item>André Roy</item> </one-of> </rule> <!-- Handling language-specific pronunciations of the same word A capable speech recognizer will listen for Mexican Spanish and US English pronunciations. --> <rule> <one-of> <item xml:lang="en-US">Jose</item> <item xml:lang="es-MX">Jose</item> </one-of> </rule> <!-- Multi-lingual input is possible --> <rule scope="public"> <example> may I speak with André Roy </example> <example> may I speak with Jose </example> may I speak with <one-of> <item> <ruleref uri="#people1"/> </item> <item> <ruleref uri="#people2"/> </item> </one-of> </rule></grammar>
This section defines the precedence of the ABNF rule expansionsyntax. Because XML documents explicitly indicate structure thereis no ambiguity and thus a precedence definition is not required.The precedence definitions for the ABNF Form are intended tominimize the need for parentheses.
ABNF Form
The following is the ordering of precedence of rule expansions.Parentheses may be used to explicitly control rule structure.
- A rule reference, aquoted token, anunquoted token or atag.
- Parentheses ('(' and ')') forgrouping and square brackets ('[' and ']') foroptional grouping.
- Repeat operator (e.g."
<0-1>
") andlanguage attachment (e.g. "!en-AU") apply to thetightest immediate preceding rule expansion. (To apply them to asequence or to alternatives, use `()' or `[]' for grouping.)- Sequence of ruleexpansions.
- Set ofalternative ruleexpansions separated by vertical bars ('|') with optionalweights.
XML Form
None required. XML structure is explicit.
Arule definition associates a legalrule expansion with arulename. The ruledefinition is also responsible for defining thescope of the rule definition: whether itis local to the grammar in which it is defined or whether it may bereferenced within other grammars. Finally, the rule definition mayadditionally include documentation comments and otherpragmatics.
The rulename for each rule definition must be unique within agrammar. The same rulename may be used in multiple grammars.
A rule definition is referenced by a URI in arule reference with the rulename being representedas the fragment identifier.
The core purpose of a rule definition is to associate a legalrule expansion with a rulename.
A legal rulename in either the XML Form or ABNF Form is acharacter sequence that:
Defined rulenames must be unique within a grammar. Theschema enforces this by declaring therulename as an XML ID.
Rulenames are case-sensitive in both XML and ABNF grammars.Exact string comparison is used to resolve rulename references.
A legal rulename cannot be one of thespecial rules: specifically "NULL", "VOID" or"GARBAGE".
ABNF Form
The rule definition consists of an optional scoping declaration(explained in the next section) followed by a legal rule name, anequals sign, a legal rule expansion and a closing semicolon. Therule definition has one of the following legal forms:
$ruleName = ruleExpansion;public$ruleName = ruleExpansion;private$ruleName = ruleExpansion;For example:
$city = Boston | "New York" | Madrid;$command = $action $object;Special Cases
An empty rule definition is illegal.
It is legal to define a rule that expands to empty parenthesesor$NULL (equivalent forms). Itis legal to define a rule that expands to a single
tag
.// Legal$rule = ();$rule = $NULL;$rule = {TAG-CONTENT};// ILLEGAL$rule = ;XML Form
A rule definition is represented by the
rule
element. Theid
attribute of the element indicates thename of the rule and must be unique within the grammar (this isenforced by XML). The contents of therule
element maybe any legal rule expansion defined inSection 2. Thescope
attribute is explainedin the next section.<rule> <one-of> <item>Boston</item> <item>"San Francisco"</item> <item>Madrid</item> </one-of></rule><rule> <ruleref uri="#action"/> <ruleref uri="#object"/></rule>Special Cases
It is not legal to define an empty rule element or a ruleelement that contains onlywhite space CDATA.
It is legal to define a rule that expands to an empty item or toa single rule reference toNULL.
It is legal to define a rule that expands to a single
tag
element.<!-- Legal --><rule><item/></rule><rule><ruleref special="NULL"/></rule><rule><tag>TAG-CONTENT</tag></rule><!-- ILLEGAL --><rule/><rule></rule><rule> </rule>
Each defined rule has a scope. The scope is either "private" or"public". If not explicitly declared in a rule definition then thescope defaults to "private".
A public-scoped rule may beexplicitlyreferenced(using thefragment identifier syntax of a URI) in the rule definitionsof other grammars and in other non-grammar documents.A private-scopedrule cannot be so referencedand is directly accessible only within its containinggrammar. A private rule may be explicitly referenced only by otherrules within the same grammar.
Informative: grammar authors may consider the following guidancewhen scoping the rules of a grammar.
ABNF Form
A rule definition may be annotated with the keywords "public" or"private". If no scope is provided, the default is "private".
$town = Townsville | Beantown;private $city = Boston | "New York" | Madrid;public $command = $action $object;XML Form
The
scope
attribute of therule
element defines the scope of the rule definition. Defined valuesarepublic
andprivate
. If omitted, thedefault scope isprivate
.<rule> <one-of> <item>Townsville</item> <item>Beantown</item> </one-of></rule><rule scope="private"> <one-of> <item>Boston</item> <item>"San Francisco"</item> <item>Madrid</item> </one-of></rule><rule scope="public"> <ruleref uri="#action"/> <ruleref uri="#object"/></rule>
It is often desirable to include examples of phrases that matchrule definitions along with the definition. Zero, one or manyexample phrases may be provided for any rule definition. Becausethe examples are explicitly marked, automated tools can be used forregression testing and for generation of grammar documentation.
ABNF Form
Adocumentation comment is aC/C++/Java comment that starts with the sequence of characters
/**
and which immediately precedes the relevant ruledefinition. Zero or more@example
tags may becontained at the end of the documentation comment. The syntaxfollows theTagged Paragraph of a documentation comment of the Java Programming Language[JAVA §18.4]. The tokenization of the example follows the tokenization and sequence rules defined inSection 2.1 andSection 2.3 respectively./** * A simple directive to execute an action. * * @example open the window * @example close the door */public $command = $action $object;XML Form
Any number of "example" elements may be provided as the initialcontent within a "rule" element. The tokenization of the examplefollows the tokenization and sequence rules defined inSection 2.1 andSection 2.3 respectively.
<rule scope="public"> <!-- A simple directive to execute an action. --> <example> open the window </example> <example> close the door </example> <ruleref uri="#action"/> <ruleref uri="#object"/></rule>
A conforming stand-alone grammar document consists of alegal header followed by a body consistingof a set of legalrule definitions.All rules defined within that grammar are scoped within thegrammar's rulename namespace and each rulename must belegal and unique.
It is legal for a grammar to define no rules. The grammar cannotbe used for processing input since it defines no patterns formatching user input.
A legal stand-alone grammar header consists of a number ofrequired declarations and other optional declarations. In addition,the ABNF Form and XML Form each have additional requirements andcapabilities of the header that are specific to each syntacticform. The ordering of header declarations is also specific to thetwo forms.
The table summarizes the information declared in a grammarheader and the appropriate representation in the ABNF Form and XMLForm.
Declaration | Status | ABNF Form | XML Form |
Grammar version | Required | §4.2: ABNF self-identifying header | §4.3:version attribute ongrammar element |
XML Namespace | Required (XML only) | Not applicable | §4.3:xmlns attribute ongrammar element |
Document type | Recommended (XML only) | Not applicable | §4.3: XML DOCTYPE |
Character encoding | Recommended | §4.4: ABNF self-identifying header | §4.4:encoding attribute in XMLdeclaration |
Language | Required in voice mode Ignored in DTMF mode | §4.5:language declaration | §4.5:xml:lang attribute ongrammar element |
Mode | Optional | §4.6:mode declaration | §4.6:mode attribute ongrammar element |
Root rule | Optional | §4.7:root declaration | §4.7:root attribute ongrammar element |
Tag format | Optional | §4.8:tag-format declaration | §4.8:tag-format attribute ongrammar element |
Base URI | Optional | §4.9:base declaration | §4.9:xml:base attribute ongrammar element |
Pronunciation lexicon | Optional. Multiple allowed. | §4.10:lexicon declaration | §4.10:lexicon element |
Metadata | Optional. Multiple allowed. | §4.11.1:meta andhttp-equiv declarations | §4.11.1:meta element |
XML metadata | Optional. (XML Only) | Not applicable | §4.11.2:metadata element |
Tag | Optional. Multiple allowed. | §4.12:tag declaration | §4.12:tag element |
A grammar that complies to this specification must declare theversion to be "1.0".
Note: the grammar version indicates the version of thespecification implemented by the grammar and is not for versioningof the grammar content. Ameta
ormetadata
declaration may be used forcontent versioning.
ABNF Form: Header Summary
A legal header for a stand-alone ABNF document consists of arequiredABNF self-identifyingheader including the grammar version and optionalcharacter encoding followed by thesedeclarations in any order:
- Language
- Mode
- Root rule
- Tag format
- Base URI
- Pronunciation lexicon (anynumber)
- Meta and http-equiv (anynumber)
- Tag (any number)
ABNF comments may appearbetween the declarations in the ABNF header after the ABNFself-identifying header.
The header declarations are followed by therule definitions of the grammar.
The following are two examples of ABNF headers. Note thatordering of the declarations (except the ABNF self-identifyingheader) is unimportant.
#ABNF 1.0 ISO-8859-1;language en;mode voice;root $myRule;tag-format FORMAT-STRING;base <http://www.example.com/base-file-path>;lexicon <http://www.example.com/lexicon.file>;lexicon <http://www.example.com/strange-city-names.file>~<media-type>;meta "Author" is "Stephanie Williams";http-equiv "Date" is "Fri, 10 Feb 2002 17:27:21 GMT";{var x=1};
#ABNF 1.0;// A French Canadian grammarlanguage fr-CA;// It's a speech grammarmode voice;// Here's the root ruleroot $QuebecCities;
XML Form: Header Summary
A legal stand-alone XML Form grammar document consists of:
- LegalXML Prolog
- Root grammar element with the following attributes
grammar
element containing any number of thefollowing elements in any order:
- Pronunciation lexicon (anynumber)
- Meta and HTTP-Equiv (anynumber)
- Metadata (any number)
- Tag (any number)
Rule definitions follow the
lexicon
,meta
,metadata
andtag
declarations.The following are examples of XML Form grammars headers eachincluding all declarations permitted on the
grammar
element and one with the DOCTYPE declaration.<?xml version="1.0" encoding="ISO-8859-1"?><grammar version="1.0" xml:lang="en" mode="voice" root="myRule" xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xml:base="http://www.example.com/base-file-path"><?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0//EN" "http://www.w3.org/TR/speech-grammar/grammar.dtd"><grammar version="1.0" xml:lang="fr-CA" mode="voice" root="QuebecCities" xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xml:base="http://www.example.com/another-base-file-path">
TheABNF self-identifying header must be present in anylegal stand-alone ABNF Form grammar document.
The first character of an ABNF document must be the "#" symbol(x23) unless preceded by an optional XML 1.0byte order mark[XML §4.3.3]. The ABNF byte order mark follows theXML definition and requirements. For example, documents encoded inUTF-16 must begin with the byte order mark.
The optional byte order mark and required "#" symbol must befollowed immediately by the exact string "ABNF" (x41 x42 x4d x46)or the appropriate equivalent for the document's encoding (e.g. forUTF-16 little-endian: x23 x00 x41 x00 x42 x00 x4d x00 x46 x00). Ifthe byte order mark is absent on a grammar encoded in UTF-16 thenthe grammar processor should performauto-detection of character encoding in a manneranalogous to auto-detection of character encoding in XML[XML §F].
Next follows a single space character (x20) and the requiredversion number which is "1.0
" for this specification(x31 x2e x30).
Next follows an optionalcharacterencoding. Section 4.4 defines character encodings in moredetail. If present, there must be a single space character (x20)between the version number and the character encoding.
The self-identifying header is finalized with a semicolon (x3b)followed immediately by a newline. The semicolon must be the firstcharacter following the version number or the character encoding ifis present.
For the remaining declarations of the ABNF headerwhite space is notsignificant.
A legal stand-alone XML Form grammar document must have a legalXML Prolog[XML§2.8].
The XML prolog in an XML Form grammar comprises the XMLdeclaration and an optional DOCTYPE declaration referencing thegrammar DTD. It is followed by the rootgrammar
element. The XML prolog may also contain XML comments, processorinstructions and other content permitted by XML in a prolog.
The version number of the XML declaration indicates whichversion of XML is being used. The version number of thegrammar
element indicates which version of the grammarspecification is being used — "1.0
" for thisspecification. The grammar version is a required attribute.
The grammar element must designate the grammar namespace. Thiscan be achieved by declaring anxmlns
attribute or anattribute with an "xmlns" prefix. See[XMLNS] for details. Note that when the xmlns attributeis used alone, it sets the default namespace for the element onwhich it appears and for any child elements. The namespace for XMLForm grammars is defined ashttp://www.w3.org/2001/06/grammar.
It is recommended that the grammar element also indicate thelocation of the grammar schema (seeAppendix C) via thexsi:schemaLocation
attribute from[SCHEMA1].Although such indication is not required, to encourage it thisdocument provides such indication on all of the examples:
<grammar version="1.0" xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd"> ...</grammar>
If present, the optional DOCTYPE must reference the standardDOCTYPE and identifier.
<!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0//EN" "http://www.w3.org/TR/speech-grammar/grammar.dtd">
The character encoding is defined on the XML declaration asdefined by the XML specification. SeeSection 4.4 for detail.
The language is defined by thexml:lang
attributeon thegrammar
element. SeeSection 4.5 for details.
The grammarmode
is defined on thegrammar
element. SeeSection 4.6 for details.
Theroot
rule is defined on thegrammar
element. SeeSection 4.7 for details.
Thetag-format
is defined on thegrammar
element. SeeSection 4.8 for details.
The base URI for the document is defined by thexml:base
attribute on thegrammar
element. SeeSection 4.9 fordetails.
The character encoding declaration indicates the scheme used forencoding character data in the document. For example, for USapplications it would be common to use US-ASCII, UTF-8 (8-bitUnicode) or ISO-8859-1. For Japanese grammars, character encodingssuch as EUC-JP and UTF-16 (16-bit Unicode) could be used.
Except for the different syntactic representation, the ABNF Formfollows the character encoding handling defined for XML. XMLgrammar processors must accept both the UTF-8 and UTF-16 encodingsof ISO/IEC 10646 and may support other character encodings. Thisfollows from an XML grammar processor being a compliant XMLprocessor and thus required to support those character encodings.For consistency, ABNF grammar processor must also accept both theUTF-8 and UTF-16 encodings of ISO/IEC 10646 and may support othercharacter encodings.
For both XML Form and ABNF Form grammars the declaration of thecharacter encoding is optional but strongly recommended. XMLdefines behavior for XML processors that receive an XML documentwithout a character encoding declaration. For consistency an ABNFgrammar processor must follow the same behavior (with adjustmentsfor the different syntax). (Note the character encoding declarationis optional only in cases where it is optional for a legal XMLdocument.)
ABNF Form
The character encoding declaration is part of theself-identifying grammar header defined inSection 4.1 and is processed in combination with thebyte order mark, if present, using the same procedure as XML 1.0[XML §4.3.3].
The following are examples of ABNF self-identifying grammarheaders with and without the character encoding declaration.
Note: the ABNF Form syntax does not provide a characterreference syntax for entry of a specific character, for example,one not directly accessible from available input devices. Thiscontrasts withXML 1.0 syntax for character references[XML §4.1]. For developmentrequiring character references the XML Form of the specification isrecommended.
#ABNF 1.0 ISO-8859-1;#ABNF 1.0 EUC-JP;#ABNF 1.0;XML Form
XML declares character encodings as part of the document's XMLdeclaration on the first line of the document.
The following are examples of XML headers with and without thecharacter encoding declaration.
<?xml version="1.0" encoding="ISO-8859-1"?><?xml version="1.0" encoding="EUC-JP"?><?xml version="1.0"?>
The language declaration of a grammar provides thelanguage identifier thatindicates the primary language contained by the document andoptionally indicates a country or other variation. Additionally,any legal rule expansion may belabeled with a language identifier.
The language declaration is required for all speech recognitiongrammars: i.e. all grammars for which themode
is "voice". (Note that mode defaultsto voice if there is no explicit mode declaration in ABNF ormode
attribute in XML.)
If an XML Form grammar is incorporated within another XMLdocument — for example, as supported by VoiceXML 2.0 — then thexml:lang
attribute is optional on thegrammar
element and thexml:lang
attribute must be inherited from the enclosing document.
InDTMF grammars a languagedeclaration must be ignored if present.
The conformance definition inSection5 defines the behavior of a grammar processor when itencounters a language variant that it does not support.
ABNF Form
The ABNF header must contain zero or one languagedeclaration. It consists of the keyword"
language
",white space, a legallanguage identifier, optionalwhite space and a terminating semicolon character(';').language en-US;language fr;XML Form
Following the XML 1.0 specification[XML §2.12] thelanguage identifier is indicated by an
xml:lang
attribute on the rootgrammar
element.<grammar xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xml:lang="en-US" version="1.0"><grammar xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xml:lang="fr" version="1.0">
The mode of a grammar indicates the type of input that the useragent should be detecting. The default mode is "voice
"for speech recognition grammars. An alternative input mode definedinAppendix E is"dtmf
" input.
Themode
attribute indicates how to interpret thetokens contained by the grammar.Speech tokens are expected to be detected as speech audio thatsounds like the token. Behavior with DTMF input, if supported, isdefined inAppendix E.
It is often the case that a different user agent is used fordetecting DTMF tones than for speech recognition. The same may betrue for other modes defined in future revisions of thespecification.
The specification does not define a mechanism by which a singlegrammar can mix modes: that is, a representation for a mixed"voice
" and "dtmf
" grammar is notdefined. Moreover, it is illegal for a rule reference in onegrammar to reference any grammar with a different mode.
A user agent may, however, support the simultaneous activationof more than one grammar including both "voice
" and"dtmf
" grammars. This is necessary, for example, forDTMF-enabled VoiceXML browsers[VXML2]. (Note: parallel activation implies disjunctionat the root level of the grammars rather than mixing of modeswithin the structure of the grammars.)
ABNF Form
The ABNF header must contain zero or one modedeclaration. It consists of the keyword "
mode
",white space, either"voice
" or "dtmf
" optionalwhite space and a terminatingsemicolon character (';'). If the ABNF header does not declare themode then it defaults tovoice
.mode voice;mode dtmf;XML Form
The
mode
declaration is provided as an optionalmode
attribute on the rootgrammar
element. Legal values are"voice"
and"dtmf"
. If the mode attribute is omitted then thevalue defaults tovoice
.<grammar mode="voice" version="1.0" xml:lang="en-US" xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd"><grammar mode="dtmf" version="1.0" xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd">
Both the XML Form and ABNF Form permit the grammar header tooptionally declare a single rule to be the root rule of thegrammar. The rule declared as the root rule must be defined withinthe scope of the grammar. The rule declared as the root rule may bescoped as eitherpublic
orprivate
.
Animplicit rule reference to the root rule ofa grammar is legal. The syntax forimplicitlyreferencing root rules is defined inSection 2.2. It is an error to reference a grammarimplicitly by its root if that grammar does notdeclare a legal root rule.
Although a grammar is not required to declare a root rule it isgood practice to declare the root rule of any grammar.
ABNF Form
The ABNF header must contain zero or one root ruledeclaration. It consists of the keyword "
root
",white space, thelegal rulename of a rule definedwithin the grammar prefixed by the dollar sign ('$'), optionalwhite space and aterminating semicolon character (';'). If the ABNF header does notdeclare the root rule then it is not legal toimplicitly reference the grammar by its root.root $rulename;XML Form
The
root
rulename declaration is provided as anoptionalroot
attribute on thegrammar
element. Theroot
declaration must identify one ruledefined elsewhere within the same grammar. The value of the rootattribute is an XML IDREF (not a URI) and must not include thenumber sign ('#').<grammar root="rulename" ...>
Thetag-format
declaration is an optionaldeclaration of atag-format identifier that indicates thecontent type of allruletags andheader tagscontained within a grammar.
The tag-format identifier is aURI. It is recommended that the tag format identifierindicate both the content type and a version. Tags typicallycontain content for asemanticinterpretation processor and in such cases the identifier, ifpresent, should indicate the semantic processor to use.
Tag-format identifier values beginning with the string"semantics/x.y" (where x and y are digits) are reserved for use bytheW3C Semantic Interpretation for Speech Recognitionspecification[SEM] or futureversions of the specification.
Grammar processor handling of tags is undefined if the tagformat declaration is omitted.
ABNF Form
The ABNF header must contain zero or one tag formatdeclaration. It consists of the keyword"
tag-format
",white space, a tag format identifier (an ABNFURI), optionalwhite space and a terminatingsemicolon character (';').Informative example ("semantics/1.0" isa reservedidentifier) :
tag-format <semantics/1.0>;XML Form
The
tag-format
is an optional attribute of thegrammar
element and contains a tag formatidentifier.<grammar tag-format="semantics/1.0" ...>
Relative URIs are resolved according to abase URI,which may come from a variety of sources. The base URI declarationallows authors to specify a document's base URI explicitly. SeeSection 4.9.1 for details on theresolution of relative URIs.
The path information specified by the base URI declaration onlyaffects URIs in the document where the element appears.
The base URI declaration is permitted but optional in both theXML Form and the ABNF Form.
Note: the base URI may be declared in ameta declaration but the explicit base declarationis recommended for both the ABNF Form and XML Form.
ABNF Form
The ABNF header must contain zero or one base URIdeclaration. It consists of the keyword "
base
",white space, a legalABNF URI, optionalwhite space and a terminatingsemicolon character (';').base <http://www.example.com/base-file-path>;base <http://www.example.com/another-base-file-path>;XML Form
The base URI declaration follows[XML-BASE] and is indicated by a
xml:base
attribute on the rootgrammar
element.<grammar xmlns="http://www.w3.org/2001/06/grammar" xml:base="http://www.example.com/base-file-path" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" version="1.0"><grammar xmlns="http://www.w3.org/2001/06/grammar" xml:base="http://www.example.com/another-base-file-path" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" version="1.0">
User agents must calculate the base URI for resolving relativeURIs according to[RFC2396]. The following describes how RFC 2396 appliesto grammar documents.
User agents must calculate the base URI according to thefollowing precedences (highest priority to lowest):
xml:base
attribute onthegrammar
element or thebase
declaration in the ABNF header (see Section 4.9).A grammar may optionally reference one or more externalpronunciation lexicon documents. A lexicon document is identifiedby aURI with an optionalmedia type.
The pronunciation information contained within a lexicondocument is used only for tokens defined within the enclosinggrammar.
The W3C Voice Browser Working Group is developing thePronunciation Lexicon Markup Language[LEX]. The specification will address the matchingprocess between tokens and lexicon entries and the mechanism bywhich a speech recognizer handles multiple pronunciations frominternal and grammar-specified lexicons. Pronunciation handlingwith proprietary lexicon formats will necessarily be specific tothe speech recognizer.
Pronunciation lexicons are necessarily language-specific.Pronunciation lookup in a lexicon and pronunciation inference forany token may use an algorithm that is language-specific. (SeeSection 2.1 for additionalinformation on token handling and pronunciations.)
ABNF Form
The ABNF header may contain any number of pronunciation lexicondeclarations (zero, one or many). The lexicon declaration consistsof the "
lexicon
" keyword followed bywhite space, anABNF URI orABNF URI with media type, optional white space anda closing semicolon (';'). (Note that a lexicon URI is not precededby a dollar sign as is the case for ABNF rule references.)Example:#ABNF V1.0 ISO-8859-1; language en-US; lexicon <http://www.example.com/lexicon.file>; lexicon <http://www.example.com/strange-city-names.file>~<media-type>; ...XML Form
Any number of
lexicon
elements may occur asimmediate children of thegrammar
element. Thelexicon
element must have auri
attributespecifying aURI thatidentifies the location of the pronunciation lexicon document.The
lexicon
element may have atype
attribute that specifies themedia type of the pronunciation lexicon document.<grammar xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xml:lang="en" version="1.0"> <lexicon uri="http://www.example.com/lexicon.file"/> <lexicon uri="http://www.example.com/strange-city-names.file" type="media-type"/> ...
Grammar documents let authors specify metadata — informationabout a document rather than document content — in a number ofways.
Ameta
declaration in either the ABNF Form or XML Form may be used toexpress metadata information in both XML Form and ABNF Formgrammars or to reference metadata available in an externalresource. The XML Form also supports ametadata
element that provides a moregeneral and powerful treatment of metadata information thanmeta
. Sincemetadata
requires an XMLmetadata schema which cannot be expressed in ABNF, there is noequivalent ofmetadata
in the ABNF Form ofgrammars.
Ameta
declaration in either ABNF Form or the XMLForm associates a string to declared meta property or declares"http-equiv" content.
TheseeAlso
property is the only defined metaproperty name. It is used to specify a resource that might provideadditional metadata information about the containing grammar. Thisproperty is modelled on therdfs:seeAlso
property of ResourceDescription Framework (RDF) Schema Specification 1.0[RDF-SCHEMA §2.3.4].
It is recommended that for general metadata properties thatgrammar authors follow the metadata properties defined in theDublin Core Metadata Initiative[DC]. For example, "Creator" to identify the entityprimarily responsible for making the content of the grammar, "Date"to indicate creation date, or "Source" to indicate the resourceFrom which a grammar is derived (e.g. when converting an XML Formgrammar to the ABNF Form, use "Source" to provide the URI for theoriginal document.)
ABNF Form
The ABNF header may contain any number of meta declarations andhttp-equiv declarations (zero, one or many). Each declarationconsists of the "
meta
" or "http-equiv
"keyword followed bywhitespace, the name string delimited by quotes, the keyword"is
",whitespace, the content string delimited by quotes, optional whitespace and a closing semicolon (';').The name string and the content string must be delimited byeither a matching pair of double quotes ('"') or a matching pair ofsingle quotes ("'").
Informative example:
#ABNF 1.0;meta "Creator" is "Stephanie Williams";meta "seeAlso" is "http://example.com/my-grammar-metadata.xml";http-equiv "Expires" is '0';http-equiv "Date" is "Thu, 12 Dec 2000 23:27:21 GMT";XML Form
A metadata property is declared with a
meta
element. Either aname
orhttp-equiv
attribute is required. It is illegal to provide bothname
andhttp-equiv
attributes. Acontent
attribute is required. Themeta
,metadata
andlexicon
elements must occurbefore all rule elements contained with the rootgrammar
element. There are no constraints on theordering of themeta
,metadata
andlexicon
elements.Informative example:
<?xml version="1.0"?> <grammar version="1.0" xml:lang="en-US" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xmlns="http://www.w3.org/2001/06/grammar"> <meta name="Creator" content="Stephanie Williams"/> <meta name="seeAlso" content="http://example.com/my-grammar-metadata.xml"/> <meta http-equiv="Expires" content="0"/> <meta http-equiv="Date" content="Thu, 12 Dec 2000 23:27:21 GMT"/> ... </grammar>
Themetadata
element is container in whichinformation about the document can be placed using a metadataschema. Although any metadata schema can be used withmetadata
, it is recommended that the ResourceDescription Format (RDF) schema[RDF-SCHEMA] is used in conjunction with the generalmetadata properties defined in the Dublin Core Metadata Initiative[DC].
RDF is a declarative language and provides a standard way forusing XML to represent metadata in the form of statements aboutproperties and relationships of items on the Web. Content creatorsshould refer to W3C metadata Recommendations[RDF-SYNTAX] and[RDF-SCHEMA] when deciding whichmetadata RDF schema to use in their documents. Content creatorsshould also refer to the Dublin Core Metadata Initiative[DC], which is a set of generallyapplicable core metadata properties (e.g., Title, Creator, Subject,Description, Copyrights, etc.).
This specification only defines an XML representation for thisform of metadata declaration. There is no ABNF equivalent formetadata
. A conversion of an XML Form grammar to theABNF Form may extract the XML metadata into a separate documentthat is referenced with a "seeAlso" meta declaration in the ABNFdocument. Note: an agent that searches XML documents for metadatarepresented with RDF would be unable to locate RDF even if it wererepresented in ABNF. Thus, support for RDF in ABNF was consideredlow utility.
XML Form
Document properties declared with
metadata
elementcan use any metadata schema. Themetadata
,meta
, andlexicon
elements must occurbefore all rule elements contained with the rootgrammar
element. There are no constraints on theordering of themetadata
,meta
andlexicon
elements.Informative: This is an example of how
metadata
canbe included in an XML grammar document using the Dublin Coreversion 1.0 RDF schema[DC]describing general document information such as title, description,date, and so on:<?xml version="1.0"?> <grammar xmlns="http://www.w3.org/2001/06/grammar" version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xml:lang="en-US"> <metadata> <rdf:RDF xmlns:rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs = "http://www.w3.org/TR/1999/PR-rdf-schema-19990303#" xmlns:dc = "http://purl.org/metadata/dublin_core#"> <!-- Metadata about the grammar document --> <rdf:Description about="http://www.example.com/meta.grxml" dc:Title="Digit Grammar" dc:Description="Digit Grammar in W3C XML Form" dc:Publisher="W3C" dc:Language="en" dc:Date="2002-02-14" dc:Rights="Copyright 2002 Jan Smith" dc:Format="application/srgs+xml" > <dc:Creator> <rdf:Seq> <rdf:li>Jackie Crystal</rdf:li> <rdf:li>Jan Smith</rdf:li> </rdf:Seq> </dc:Creator> </rdf:Description> </rdf:RDF> </metadata></grammar>
A grammar may optionally specify one or moretag
declarations in the header. The content of atag
inthe header, just like atag in ruleexpansions, is an arbitrary string which may be used forsemantic interpretation.
ABNF Form
The ABNF header may contain any number of tag declarations(zero, one or many).
The tag declaration consists a string delimited as described inS2.6 ABNF Form, followedby a closing semicolon (';').
The tag content is all text between the opening and closingdelimiters including leading and trailingwhitespace. The contents of thetag are not parsed by the grammar processor.
#ABNF V1.0 ISO-8859-1; language en-US; {TAG-CONTENT-1}; {!{TAG-CONTENT-2}!}; $rule = . . .; ...XML Form
Any number of
tag
elements may occur as immediatechildren of thegrammar
element. The content oftag
is CDATA.<grammar xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xml:lang="en" version="1.0"> <tag>TAG-CONTENT-1<tag> <tag>TAG-CONTENT-2<tag> ...
Comments may be placed in most places in a grammar document. ForXML, use XML comments. For ABNF there are documentation commentsand C/C++/Java-style comments.
ABNF Form
C/C++/Java comments are permitted. Documentation comments arepermitted before
grammar
andlanguage
declarations and before anyrule
definition.Section 3.3 defines the formatfor representing examples in documentation comments before a ruledefinition.
// C++/Java-style single-line comment/* C/C++/Java-style comment *//** Java-style documentation comment */XML Form
An XML comment has the following syntax.
<!-- comment -->
The fetching and caching behavior of both ABNF Form and XML Formgrammar documents is defined primarily by the environment in whichthe grammar processor operates. For instance, VoiceXML 1.0 andVoiceXML 2.0 define certain fetching and caching behaviors thatapply to grammars activated by a VoiceXML browser. Similarly, anyAPI for a recognizer that supports ABNF Form or XML Form grammarsmay apply fetching and caching behaviors.
Grammar processors are recommended to support the followinginterpretation of "rendering" a grammar for the purpose ofdetermining document freshness.
Activation of a grammar is the point at which therecognizer begins detection of user input matching the grammar andis therefore analogous to the action of visual or audio renderingof system output. As with output rendering, grammar freshnessshould be checked close to the moment of grammar activation.
ABNF keywords are case sensitive. The keywords of the ABNFlanguage are not reserved. The keywords with specified meaning inABNF are:
Context | Keywords |
---|---|
Language declaration | "language" |
Mode declaration | "mode" |
Root declaration | "root" |
Tag format declaration | "tag-format" |
Base URI declaration | "base" |
Pronunciation lexicon | "lexicon" |
Meta or HTTP-equiv declaration | "meta", "http-equiv", "is" |
Rule definition | "public", "private" |
Since keywords are not reserved they may be used as rulenamesand as tokens. The following is a legal grammar that accepts asinput a sequence of one or more "public" tokens.
#ABNF 1.0 ISO-8859-1;language en-AU;root $public;mode voice;public $public = public $public | public;
This section is normative.
Different sets of grammar conformance criteria exist for:
An XML Form grammar document fragment is aConforming XMLForm Grammar Fragment if:
xmlns
attributes which refer to non-grammar namespaceelements are removed from the document,<?xml...?>
) is included at the top of thedocument,grammar
element does not alreadydesignate the grammar namespace using the "xmlns" attribute, thenxmlns="http://www.w3.org/2001/06/grammar"
is added tothe element.A document is aConforming Stand-Alone XML Form GrammarDocument if it meets both the following conditions.
The XML Form grammar specification and these conformancecriteria provide no designated size limits on any aspect of grammardocuments. There are no maximum values on the number of elements,the amount of character data, or the number of characters inattribute values.
The grammar namespace may be used with other XML namespaces asper the Namespaces in XML Recommendation[XMLNS]. Future work by W3C will address ways tospecify conformance for documents involving multiplenamespaces.
An XML Form grammar processor is a program that can parse andprocess XML Form grammar documents. Examples include speechrecognizers and DTMF detectors that accept the XML Form.
In aConforming XML Form Grammar Processor, the XMLparser must be able to parse and process all XML constructs definedby XML 1.0[XML] and Namespacesin XML[XMLNS]. This XMLparser is not required to perform validation of a grammar documentas per its schema or DTD; this implies that during processing of anXML Form grammar document it is optional to apply or expandexternal entity references defined in an external DTD.
A Conforming XML Form Grammar Processor must correctlyunderstand and apply the semantics of each possible grammar featuredefined by this document.
A Conforming XML Form Grammar Processor must meet the followingrequirements for handling of languages:
When a Conforming XML Form Grammar Processor encounters elementsor attributes in a non-grammar namespace it may:
A Conforming XML Form Grammar Processor is not required tosupport recursive grammars, that is, grammars in whichrule references include direct or indirectself-reference.
There is, however, no conformance requirement with respect toperformance characteristics of the XML Form Grammar Processor. Forinstance, no statement is required regarding the accuracy, speed orother characteristics of a speech recognizer or DTMF detector. Nostatement is made regarding the size of grammar or size of grammarvocabulary that an XML Form Grammar Processor must support.
An ABNF grammar document is a Conforming ABNF Document if itadheres to the specification described in this document (Speech Recognition Grammar Specification)including theFormal ABNFSpecification.
An ABNF Grammar Processor is a program that can parse andprocess ABNF grammar documents. Examples include speech recognizersand DTMF detectors that accept the ABNF Form.
A Conforming ABNF Grammar Processor must correctly understandand apply the semantics of each possible grammar feature defined bythis document.
A Conforming ABNF Grammar Processor must follow the samelanguage handling requirements as outlined inSection 5.4 for Conforming XML Form GrammarProcessors.
A Conforming ABNF Grammar Processor should inform its hostingenvironment if it encounters an illegal grammar document or othergrammar content that it is unable to process.
A Conforming ABNF Grammar Processor is not required to supportrecursive grammars, that is, grammars in whichrule references include direct or indirectself-reference.
There is, however, no conformance requirement with respect toperformance characteristics of the ABNF Grammar Processor. Forinstance, no statement is required regarding the accuracy, speed orother characteristics of a speech recognizer or DTMF detector. Nostatement is made regarding the size of grammar or size of grammarvocabulary that an ABNF Grammar Processor must support.
A Conforming ABNF/XML Form Grammar Processor must meet all theconformance criteria defined inSection 5.4 and inSection5.6.
Additionally an ABNF/XML Form Grammar Processor must be able toresolve and applyreferences fromXML Form Grammars to ABNF Form Grammars, andreferences from ABNF Form Grammars to XML FormGrammars.
A conforming user agent is aConforming XML Form Grammar Processor,Conforming ABNF Form Grammar Processor orConforming ABNF/XML Form Grammar Processorthat is capable of accepting user input of themode
of a grammar (i.e. speech inputin"voice"
mode, DTMF input"dtmf"
mode)and:
Current speech recognition technology is statistically based.Since the output is not deterministic and cannot be guaranteed tobe a correct representation of the input there is no conformancerequirement regarding accuracy. A conformance test may, however,require some examples of correct recognition of speech input todetermine conformance.
This document was written with the participation of the membersof the W3C Voice Browser Working Group(listed in alphabeticalorder):
This appendix is informative.
The grammar DTD is located athttp://www.w3.org/TR/speech-grammar/grammar.dtd
This appendix is normative.
The grammar schema is located athttp://www.w3.org/TR/speech-grammar/grammar.xsd
Note: the grammar schema includes theno-namespace core schema(below).
Theno-namespace core schema for grammars islocated athttp://www.w3.org/TR/speech-grammar/grammar-core.xsd. Itmay be used as a basis for specifying XML Form Grammar Fragmentsembedded in non-grammar namespace schemas.
This appendix is normative.
The notation used here follows theEBNF notation (Extended Backus-Naur Form) defined in theXML 1.0 Recommendation[XML§6].
Thewhite space handlingof the ABNF Form follows white space and end-of-line handlingof XML (seeSection 1.6).
Lexical Grammar for ABNF
The lexical grammar defines the lexical tokens of the ABNFformat and has single characters as its terminal symbols. As aconsequence neitherwhite space characters norABNF comments are allowed in lexical tokens unlessexplicitly specified.
SelfIdentHeader ::= '#ABNF' #x20 VersionNumber (#x20 CharEncoding)? ';'[Additional constraints: - The semicolon (';') must immediately be followed by anend-of-line. ]VersionNumber ::= '1.0' CharEncoding ::= NmtokenBaseURI ::= ABNF_URILanguageCode ::= Nmtoken[Additional constraints: - The language code must be a validlanguage identifier. ]RuleName ::= '$' ConstrainedNameConstrainedName ::= Name - (Char* ('.' | ':' | '-') Char*)TagFormat ::= ABNF_URILexiconURI ::= ABNF_URI | ABNF_URI_with_Media_TypeSingleQuotedCharacters ::= ''' [^']* ''' DoubleQuotedCharacters ::= '"' [^"]* '"' QuotedCharacters ::= SingleQuotedCharacters | DoubleQuotedCharactersWeight ::= '/' Number '/'Repeat ::= [0-9]+ ('-' [0-9]*)?[Additional constraints: - A number to the right of the hyphen must not be greater than the number to the left of the hyphen. ]Probability ::= '/' Number '/'[Additional constraints: - The float value must be in the range of "0.0" to "1.0" (inclusive). ]Number ::= [0-9]+ | [0-9]+ '.' [0-9]* | [0-9]* '.' [0-9]+ExternalRuleRef ::= '$' ABNF_URI | '$' ABNF_URI_with_Media_Type[Additional constraints: - The referenced grammar must have the same mode ("voice" or "dtmf") as the referencing grammar. - If the URI reference contains a fragment identifier, the referenced rule must be a public rule of another grammar. - If the URI reference does not contain a fragment identifier, i.e. if it is an implicit root rule reference, then the referenced grammar must declare a root rule. ]Token ::= Nmtoken | DoubleQuotedCharactersLanguageAttachment ::= '!' LanguageCodeTag ::= '{' [^}]* '}' | '{!{' (Char* - (Char* '}!}' Char*)) '}!}'------------------------------------------------------------ABNF_URI andABNF_URI_with_Media_Type are definedinSection 1.6 Terminology.Name is defined by the XMLName production[XML §2.3].Nmtoken is defined by the XMLNmtoken production[XML §2.3].NameChar is defined by the XMLNameChar production[XML §2.3].Char is defined by the XMLChar production[XML §2.2].
Note: As mentioned inSection2.5 the symbols "*", "+" and "?", which are often used inregular expression languages, are reserved for future use in ABNFand must not be used at any place in a grammar where the syntaxcurrently permits a repeat operator.
Syntactic Grammar for ABNF
The syntactic grammar has lexical tokens defined by the lexicalgrammar as its terminal symbols. Between two lexical tokens anynumber ofwhite spacesorABNF comments may appear.
grammar ::= SelfIdentHeader declaration* ruleDefinition*declaration ::= baseDecl | languageDecl | modeDecl | rootRuleDecl | tagFormatDecl | lexiconDecl | metaDecl| tagDeclbaseDecl ::= 'base' BaseURI ';'[Additional constraints: - A base declaration must not appear more than once in grammar. ]languageDecl ::= 'language' LanguageCode ';'[Additional constraints: - A language declaration must not appear more than once in grammar. - A language declaration is required if the grammar mode is "voice". ]modeDecl ::= 'mode' 'voice' ';' | 'mode' 'dtmf' ';'[Additional constraints: - A mode declaration must not appear more than once in grammar. ]rootRuleDecl ::= 'root' RuleName ';'[Additional constraints: - A root rule declaration must not appear more than once in grammar. - The root rule must be a rule that is defined within the grammar. ]tagFormatDecl ::= 'tag-format' TagFormat ';'[Additional constraints: - A tag-format declaration must not appear more than once in grammar. ]lexiconDecl ::= 'lexicon' LexiconURI ';'metaDecl ::= 'http-equiv' QuotedCharacters 'is' QuotedCharacters ';' | 'meta' QuotedCharacters 'is' QuotedCharacters ';'tagDecl ::= Tag ';'ruleDefinition ::= scope? RuleName '=' ruleExpansion ';'[Additional constraints: - The rule name must be unique within a grammar, i.e. no rule must be defined more than once within a grammar. ]scope ::= 'private' | 'public'ruleExpansion ::= ruleAlternative ( '|' ruleAlternative )*ruleAlternative ::= Weight? sequenceElement+sequenceElement ::= subexpansion | subexpansion repeatOperatorsubexpansion ::= Token LanguageAttachment? | ruleRef | Tag | '(' ')' | '(' ruleExpansion ')' LanguageAttachment? | '[' ruleExpansion ']' LanguageAttachment?ruleRef ::= localRuleRef | ExternalRuleRef | specialRuleReflocalRuleRef ::= RuleName[Additional constraints: - The referenced rule must be defined within the same grammar. ]specialRuleRef ::= '$NULL' | '$VOID' | '$GARBAGE'repeatOperator ::= '<' Repeat Probability? '>'
This appendix is normative.
This section defines a normative representation of a grammarconsisting ofDTMF tokens. ADTMF grammar can be used by a DTMF detector to determine sequencesof legal and illegal DTMF events. All grammar processors thatsupport grammars of mode"dtmf"
must implement thisAppendix. However, not all grammar processors are required tosupport DTMF input.
If thegrammar mode is declaredas "dtmf" thentokens contained bythe grammar are treated as DTMF tones (rather than the default ofspeech tokens).
There are sixteen (16) DTMF tones. Of these twelve (12) arecommonly found on telephone sets as the digits "0" through "9" plus"*" (star) and "#" (pound). The four DTMF tones not typicallypresent on telephones are "A", "B", "C", "D".
Each of the DTMF symbols is a legal DTMF token in a DTMFgrammar. As in speech grammars, tokens must be separated bywhite space in a DTMFgrammar. A space-separated sequence of DTMF symbols represents atemporal sequence of DTMF entries.
In the ABNF Form the "*" symbol is reserved so double quotesmust always be used to delimit "*" when defining an ABNF DTMFgrammar. It is recommended that the "#" symbol also be quoted. Asan alternative the tokens "star" and "pound" are acceptablesynonyms.
In any DTMF grammar anylanguagedeclaration in a grammar header is ignored and anylanguage attachments to rule expansionsare ignored.
In all other respects a DTMF grammar is syntactically the sameas a speech grammar. For example, DTMF grammars may userule references,special rules,tags andother specification features.
The following is a simple DTMF grammar that accepts a 4-digitPIN followed by a pound terminator. It also permits the sequence of"*" followed by "9" (e.g. to receive a help message).
#ABNF 1.0 ISO-8859-1;mode dtmf;$digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;public $pin = $digit <4> "#" | "*" 9;
<?xml version="1.0"?><grammar mode="dtmf" version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xmlns="http://www.w3.org/2001/06/grammar"><rule> <one-of> <item> 0 </item> <item> 1 </item> <item> 2 </item> <item> 3 </item> <item> 4 </item> <item> 5 </item> <item> 6 </item> <item> 7 </item> <item> 8 </item> <item> 9 </item> </one-of></rule><rule scope="public"> <one-of> <item> <item repeat="4"><ruleref uri="#digit"/></item> # </item> <item> * 9 </item> </one-of></rule></grammar>
This appendix is informative.
The transformation provided below is illustrative of theconversion of an XML Form grammar to the Augmented BNF Form. Knownlimitations:
The source for this transformation is located athttp://www.w3.org/TR/speech-grammar/grammar-transformer.xsl.
This appendix is informative.
The W3C Voice Browser Working Group has applied to IANA toregister amedia typeeach for the ABNF Form and XML Form of this Speech RecognitionGrammar Specification.
The ABNF media type identifies ABNF grammars. The media typeapplied for is"application/srgs"
.
Similarly, the XML Form grammar media type identifies XMLForm grammars. The media type applied for is"application/srgs+xml"
.
The W3C Voice Browser Working Group has adopted the conventionof using the ".gram" filename suffix for ABNF grammar documents andthe ".grxml" filename suffix for XML Form grammar documents.
This appendix is informative.
This section defines an informative representation of a parsedresult of speech recognition or other user agent processing. Thisrepresentation may be used as the basis for subsequent processingof user input, in particular,semanticinterpretation. For instance, the W3C Semantic Interpretationfor Speech Recognition specification[SEM] is defined around the logical parse structure.
This Appendix adopts the terminology and nomenclature ofIntroduction to Automata Theory, Languages, andComputation[HU79].
Denote thetokens of the alphabet of all tokensaccepted by a grammar ast1, t2....
An input or output token sequence is a space separated string oftokens. The logical parse structure containswhite-space-normalized tokens. The tokens in the logicalparse structure are optionally delimited by double quotes so thatwhite space and otherscharacters can be parsed unambiguously. e.g.t1,t2,"t3 withspace". (For consistency, all examples in this Appendix includedouble quotes.)
Letε (epsilon) or "" denote the unique string oflength 0, also known as the empty string.
Denote thetags of the alphabet of all tags accepted bya grammar as{tag1}, {tag2}, ....
Denote a legal expansion asE. (A legal expansion isdefined inSection 2.)
The expressive power of a rule expansion is aRegularExpression (see HU79) and has an equivalentFiniteAutomaton (see HU79). [The handling of rule referencesrequires special treatment: seeSection H.2.] The expressive power of the grammarspecification consists of:
We formalize the logical parse structure by creating aFinite Automaton with Output (see HU79). This construct isalso referred to as aFinite State Transducer.
We define the transitions for tokens and tags as producing anoutput symbol.
We represent parse output as an ordered array of outputentities:[e1,e2,e3,...].
An entitye may be a token, a tag or a rule expansion(seeH.2).
The empty output array is represented as[ε] orsimply[].
A $NULL reference is equivalent to a transition that accepts asinput ε and produces as output ε. In the notationof HU79:ε/ε.
A $VOID reference is logically equivalent to a missingtransition. It accepts no input and produces no output.
A $GARBAGE reference is equivalent to a transition that acceptsplatform specific input and produces as output ε.
Anambiguity occurs when for a specified sequence ofinput tokens matched to a specified rule of a grammar there is morethan one distinct logical parse structure that can be produced.
Anambiguity can occur at points of disjunction(choice) in a grammar. Disjunction exists with the use ofalternatives andrepeats.
A grammar processor may preserve any number of ambiguous logicalparse structures to create a set of alternative logical parsestructures for the input. It is legal for a grammar processor tomaintain all possible logical parse structures or to dispose of allbut one of the alternatives. There is no specified behavior forselection of ambiguities amongst possibilities by a grammarprocessors. As a result grammars that contain ambiguity do notguarantee portability of performance. Developers and grammar toolsshould be ambiguity-aware.
This Appendix does not illustrate all forms of ambiguousexpansions but provides examples of some of the form commonforms.
Matching a token to a token produces an array of 1 token.
Expansion | t1 |
Input | t1 |
Output | ["t1"] |
A $NULL reference is matched by an empty input sequence andoutput is an empty array.
Expansion | $NULL |
Input | "" |
Output | [] |
A tag is matched by an empty input sequence and output is anarray of 1 tag.
Expansion | {tag} or {!{tag}!} |
Input | "" |
Output | [{!{tag}!}] |
Concatenation: An expansion consisting of a token and a tag ismatched by input containing the token and produces as output atoken, tag array.
Expansion | t1 {tag1} |
Input | t1 |
Output | ["t1",{!{tag1}!}] |
Concatenation: an expansion consisting of a sequence of tokens,tags and $NULLs is matched by input that consists of the containedtokens. Output consists of the sequence of tokens and tags withorder preserved. e.g.
Expansion | t1 $NULL {tag1} t2 {tag2} t3 |
Input | t1 t2 t3 |
Output | ["t1",{!{tag1}!},"t2",{!{tag2}!},"t3"] |
Parenthetical structure is not preserved in the result. Thefollowing is the same sequence as the previous example but withparentheticals added to the expansion definition.
Expansion | ((t1) $NULL) {tag1} (t2 {tag2} t3) |
Input | t1 t2 t3 |
Output | ["t1",{!{tag1}!},"t2",{!{tag2}!},"t3"] |
Alternatives: a set of many alternative tokens is matched byinput of a single token and produces as output a single token.
Expansion | t1 | t2 |t3 |
Input | t2 |
Output | ["t2"] |
Alternatives: if any single expansion in a set of alternativescan be matched by null input then the set of alternatives may bematched by null input and the output is the output ofnull-accepting expansion. ($NULL, {tag} and repeat counts of zeroall permit null input.)
Expansion | t1 | t2 | $NULL |
Input | "" |
Output | [] |
With a different null-accepting expansion:
Expansion | t1 | t2 | {tag} |
Input | "" |
Output | [{!{tag}!}] |
Alternatives and ambiguity: several examples of ambiguousexpansions with the ambiguity arising from alternatives that acceptthe same input but produce different output.
Expansion | t1 {tag1} | t1 {tag2} | t2 |
Input | t1 |
Output 1 | ["t1",{!{tag1}!}] |
Output 2 | ["t1",{!{tag2}!}] |
In this example null input is ambiguous.
Expansion | {tag1} | {tag2} | $NULL |
Input | "" |
Output 1 | [{!{tag1}!}] |
Output 2 | [{!{tag2}!}] |
Output 3 | [] |
The following is not ambiguous because the different pathsthrough the expansion produce the same output.
Expansion | t1 | t1 | t2 |
Input | t1 |
Output 1 | ["t1"] |
Output 2 | ["t1"] |
Repeats: an optional expansion can be either matched by an emptytoken sequence or by any token sequence that matches the expansioncontained within the optional.
Expansion | t1 <0-1> |
Input 1 | "" |
Output 1 | [] |
Input 2 | t1 |
Output 2 | ["t1"] |
Repeats: order is preserved upon multiple expansions.
Expansion | (t1 {tag1}) <0-3> |
Input 1 | "" |
Output 1 | [] |
Input 2 | t1 |
Output 2 | ["t1",{!{tag1}!}] |
Input 3 | t1,t1,t1 |
Output 3 | ["t1",{!{tag1}!},"t1",{!{tag1}!},"t1",{!{tag1}!}] |
Repeats and null input: If the contents of an optional expansioncan be matched by an empty input sequence AND the output ofmatching the contained expansion is always an empty array then theoutput of matching the optional expansion by an empty sequence isalso an empty array.
Expansion | $NULL <0-1> |
Input | "" |
Output | [] |
Ambiguous repeats: If a repeated or optional expansion can bematched by an empty input sequence BUT the output of matching thecontained expansion may contain tags then the parse is ambiguous.It isrecommended that the parse be minimal: Output 1 ispreferred.
Expansion | {tag} <0-> |
Input | "" |
Output 1 | [] |
Output 2 | [{!{tag}!}] |
Output 3 | [{!{tag}!},{!{tag}!}] |
Output N | [{!{tag}!},{!{tag}!},{!{tag}!},...] |
A similar ambiguity arises if the repeated expansion contains aalternative expansion that has a null-accepting expansion.
Expansion | (t1 | {tag}) <0-3> |
Input | t1 |
Output 1 | ["t1"] |
Output 2 | ["t1",{!{tag}!}] |
Output 3 | [{!{tag}!},"t1"] |
Output 4 | ["t1",{!{tag}!},{!{tag}!}] |
Output 5 | [{!{tag}!},"t1",{!{tag}!}] |
Output 6 | [{!{tag}!},{!{tag}!},"t1"] |
A sequence with two repeat expansion can be ambiguous if the tworepeated expansions can accept the same input but produce differentoutput.
Expansion | (t1 {tag1}) <0-2> (t1 {tag2})<0-2> |
Input | t1,t1,t1 |
Output 1 | ["t1",{!{tag1}!},"t1",{!{tag1}!},"t1",{!{tag1}!} |
Output 2 | ["t1",{!{tag1}!},"t1",{!{tag1}!},"t1",{!{tag2}!} |
Output 3 | ["t1",{!{tag1}!},"t1",{!{tag2}!},"t1",{!{tag2}!} |
Output 4 | ["t1",{!{tag2}!},"t1",{!{tag2}!},"t1",{!{tag2}!} |
A rule reference is a legal rule expansion (seeSection 2.2).
We denote output obtained by matching the token sequence"t1,t2,..." against the expansion$rulename as$rulename[e1,e2,...] where"e1,e2,..." is the entitysequence obtained by matching that token sequence against the ruleexpansion defined for $rulename. Where a rule reference to anexternal rule is used the ABNF syntax for the rule reference isused (without any media type). For example,$<http://www.example.com/grammar.grxml#rulename">[e1,e2,...]
or an implicit root rule reference$<http://www.example.com/grammar.grxml">[e1,e2,...]
.For brevity, all the examples below use only local rulereferences.
The rulename of the top-level rule should enclose the logicalparse structure.
A distinct structure for matching rule references maintains theparse tree for the result. This structure may be utilized in thesemantic interpretation process or other computational processesthat derive from the parse output structure.
There is no distinction betweenlocal rule references (within the same grammar) andexternal rule references.
There is no distinction between a root reference and a referenceto a named grammar.
The following is a simple rule reference example.
Rule | $x = t1 t2 t3; |
Expansion | $x |
Input | t1,t2,t3 |
Output | $x["t1","t2","t3"] |
The following is a rule reference in sequence.
Rule | $x = t2 t3 t4; |
Expansion | t1 $x t5 |
Input | t1,t2,t3,t4,t5 |
Output | ["t1",$x["t2","t3","t4"],"t5"] |
The following includes a reference to a rule that outputs atag.
Rule | $x = t2 {tag}; |
Expansion | t1 $x t3 |
Input | t1,t2,t3 |
Output | ["t1",$x["t2",{!{tag}!}],"t3"] |
Multiple references to the same rule are permitted.
Rule | $x = t1 {tag1}; |
Expansion | $x $x $x |
Input | t1,t1,t1 |
Output | [$x["t1",{!{tag1}!}],$x["t1",{!{tag1}!}],$x["t1",{!{tag1}!}]] |
Rule references may be repeated.
Rule | $x = t1 {tag}; |
Expansion | $x <0-> |
Input | t1,t1,t1 |
Output | [$x["t1",{!{tag1}!}],$x["t1",{!{tag1}!}],$x["t1",{!{tag1}!}]] |
The Speech Recognition Grammar Specification has the expressivepower of aContext Free Grammar. This arises because thelanguage permits a rule to directly or indirectly reference itself.[Note: aConforming XML Form GrammarProcessor orConforming ABNF FormGrammar Processor is not required to support recursivegrammars.]
There is no distinct representation for a recursive rulereference.
Simple right recursion. Note: this grammar can be written in anon-recursive (regular expression) form.
Rule | $x = t1 {last} | t1 $x; |
Expansion | $x |
Input | t1,t1,t1 |
Output | [$x["t1",$x["t1",$x["t1",{!{last}!}]]]] |
Embedded recursion. Note that this matches any sequence ofn t1's followed byn t2's.
Rule | $x = {bottom} | (t1 $x t2); |
Expansion | $x |
Input | t1,t1,t2,t2 |
Output | [$x["t1",$x["t1",$x[{!{bottom}!}],"t2"],"t2"]] |
This appendix is informative.
The following features are under consideration for versions ofthe Speech Recognition Grammar Specification after version 1.0:
This appendix is informative.
The following shows a simple grammar that supports commands suchas "open a file" and "please move the window". It references aseparately-defined grammar for politeness which is not shownhere.
ABNF Form
#ABNF 1.0 UTF-8;language en;mode voice;root $basicCmd;meta "author" is "Stephanie Williams";/** * Basic command. * @example please move the window * @example open a file */public $basicCmd = $<http://grammar.example.com/politeness.gram#startPolite> $command $<http://grammar.example.com/politeness.gram#endPolite>;$command = $action $object;$action = /10/ open {TAG-CONTENT-1} | /2/ close {TAG-CONTENT-2} | /1/ delete {TAG-CONTENT-3} | /1/ move {TAG-CONTENT-4};$object = [the | a] (window | file | menu);XML Form
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0//EN" "http://www.w3.org/TR/speech-grammar/grammar.dtd"><grammar xmlns="http://www.w3.org/2001/06/grammar" xml:lang="en" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" version="1.0" mode="voice" root="basicCmd"><meta name="author" content="Stephanie Williams"/><rule scope="public"> <example> please move the window </example> <example> open a file </example> <ruleref uri="http://grammar.example.com/politeness.grxml#startPolite"/> <ruleref uri="#command"/> <ruleref uri="http://grammar.example.com/politeness.grxml#endPolite"/></rule><rule> <ruleref uri="#action"/> <ruleref uri="#object"/></rule><rule> <one-of> <item weight="10"> open <tag>TAG-CONTENT-1</tag> </item> <item weight="2"> close <tag>TAG-CONTENT-2</tag> </item> <item weight="1"> delete <tag>TAG-CONTENT-3</tag> </item> <item weight="1"> move <tag>TAG-CONTENT-4</tag> </item> </one-of></rule><rule> <item repeat="0-1"> <one-of> <item> the </item> <item> a </item> </one-of> </item> <one-of> <item> window </item> <item> file </item> <item> menu </item> </one-of></rule></grammar>
These two grammars illustrate referencing between grammars. Thesame grammar is shown in both XML Form and ABNF Form.
ABNF: http://www.example.com/places.gram
#ABNF 1.0 ISO-8859-1;language en;mode voice;root $city_state;public $city = Boston | Philadelphia | Fargo;public $state = Florida | North Dakota | New York;// References to local rules// Artificial example allows "Boston, Florida!"public $city_state = $city $state;ABNF: http://www.example.com/booking.gram
#ABNF 1.0 ISO-8859-1;language en;mode voice;// Reference by URI syntaxpublic $flight = I want to fly to $<http://www.example.com/places.gram#city>;// Reference by URI syntaxpublic $exercise = I want to walk to $<http://www.example.com/places.gram#state>;//Implicit reference to root rule by URIpublic $wet = I want to swim to $<http://www.example.com/places.gram>;
XML Form Grammar:http://www.example.com/places.grxml
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0//EN" "http://www.w3.org/TR/speech-grammar/grammar.dtd"><grammar xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xml:lang="en" version="1.0" root="city_state" mode="voice"> <rule scope="public"> <one-of> <item>Boston</item> <item>Philadelphia</item> <item>Fargo</item> </one-of> </rule> <rule scope="public"> <one-of> <item>Florida</item> <item>North Dakota</item> <item>New York</item> </one-of> </rule> <!-- Reference by URI to a local rule --> <!-- Artificial example allows "Boston, Florida"! --> <rule scope="public"> <ruleref uri="#city"/> <ruleref uri="#state"/> </rule></grammar>XML Form Grammar:http://www.example.com/booking.grxml
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0//EN" "http://www.w3.org/TR/speech-grammar/grammar.dtd"><grammar xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xml:lang="en" version="1.0" mode="voice"> <!-- Using URI syntax --> <rule scope="public"> I want to fly to <ruleref uri="http://www.example.com/places.grxml#city"/> </rule> <!-- Using URI syntax --> <rule scope="public"> I want to walk to <ruleref uri="http://www.example.com/places.grxml#state"/> </rule> <!--Implicit reference to root rule of a grammar by URI --> <rule scope="public"> I want to swim to <ruleref uri="http://www.example.com/places.grxml"/> </rule></grammar>
The following two grammars are XML Form grammars with Koreanyes/no content. The first represents the Korean symbols as Unicodecharacters and has UTF-8 encoding. The second represents the sameUnicode characters using character escaping.
ABNF Form Grammar with Unicode Characters inUTF-8 Encoding
#ABNF 1.0 UTF-8;language ko;mode voice;root $yes_no_ko;/* * Simple Korean yes/no grammar * @example 예 */public $yes_no_ko = 예 | 아니오 ;XML Form Grammar with Unicode Characters inUTF-8 Encoding
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0//EN" "http://www.w3.org/TR/speech-grammar/grammar.dtd"><grammar xml:lang="ko" version="1.0" mode="voice" xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" root="yes_no_ko"> <!-- yes/no grammar --> <rule scope="public"> <example>예</example> <one-of> <item>예</item> <item>아니오</item> </one-of> </rule></grammar>XML Form Grammar with Character Escaping ofUnicode Characters
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0//EN" "http://www.w3.org/TR/speech-grammar/grammar.dtd"><grammar xml:lang="ko" version="1.0" mode="voice" xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" root="main"> <!-- yes/no grammar --> <rule scope="public"> <example>예</example> <one-of> <item>예</item> <item>아니오</item> </one-of> </rule></grammar>
The following two grammars are XML Form grammars with Chinesenumber content. The first represents the Chinese symbols as Unicodecharacters with the UTF-8 encoding. The second represents the sameUnicode characters using character escaping.
ABNF Form Grammar with Unicode Characters inUTF-8 Encoding
#ABNF 1.0 UTF-8;language zh;mode voice;root $main;public $main = $digits1_9;/* * @example 四 */private $digits1_9 = 一 | 二 | 三 | 四 | 五 | 六 | 七 | 八 | 九;XML Form Grammar with Unicode Characters inUTF-8 Encoding
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0//EN" "http://www.w3.org/TR/speech-grammar/grammar.dtd"><grammar version="1.0" xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xml:lang="zh" mode="voice" root="main"> <rule scope="public"> <ruleref uri="#digits1_9"/> </rule> <rule scope="private"> <example>四</example> <one-of> <item>一</item> <item>二</item> <item>三</item> <item>四</item> <item>五</item> <item>六</item> <item>七</item> <item>八</item> <item>九</item> </one-of> </rule></grammar>XML Form Grammar with Character Escaping ofUnicode Characters
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0//EN" "http://www.w3.org/TR/speech-grammar/grammar.dtd"><grammar version="1.0" xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xml:lang="zh" mode="voice" root="main"> <rule scope="public"> <ruleref uri="#digits1_9"/> </rule> <rule scope="private"> <example>四</example> <one-of> <item>一</item> <item>二</item> <item>三</item> <item>四</item> <item>五</item> <item>六</item> <item>七</item> <item>八</item> <item>九</item> </one-of> </rule></grammar>
This Swedish XML Form grammar provides a comprehensive set offorms of "yes" and "no". All characters are contained within theISO-8859-1 (Latin-1) character set.
XML Form Grammar with ISO-8859-1
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0//EN" "http://www.w3.org/TR/speech-grammar/grammar.dtd"><grammar version="1.0" xmlns="http://www.w3.org/2001/06/grammar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/06/grammar http://www.w3.org/TR/speech-grammar/grammar.xsd" xml:lang="sv" mode="voice" root="main"> <rule scope="public"> <example>ja det är rätt</example> <example>nej det är fel</example> <one-of> <item> <ruleref uri="#yes_rule"/> </item> <item> <ruleref uri="#no_rule"/> </item> </one-of> </rule> <rule scope="private"> <example>ja det är rätt</example> <one-of> <item>exakt</item> <item>javisst</item> <item> ja <item repeat="0-1"> <ruleref uri="#yes_emphasis"/> </item> </item> <item>jepp</item> <item>korrekt</item> <item>okej</item> <item>rätt</item> <item>si</item> <item>säkert</item> <item>visst</item> </one-of> </rule> <rule scope="private"> <example>det stämmer</example> <one-of> <item>det gjorde jag</item> <item> <item repeat="0-1">det</item> stämmer </item> <item>det är rätt</item> <item>det är korrekt</item> <item>det är riktigt</item> </one-of> </rule> <rule scope="private"> <example>nej det är fel</example> <one-of> <item>icke</item> <item>fel</item> <item> nej <item repeat="0-1"> <ruleref uri="#no_emphasis"/> </item> </item> <item>nix</item> <item>no</item> </one-of> </rule> <rule scope="private"> <example>det är fel</example> <one-of> <item>det gjorde jag inte</item> <item> <item repeat="0-1">det</item> stämmer inte </item> <item>det är fel</item> <item>absolut inte</item> <item>inte alls</item> </one-of> </rule></grammar>