Last active
August 29, 2015 14:23
-
-
Save bfoz/72e561a83e534f5aa078 to your computer and use it in GitHub Desktop.
Convert JSGF grammars to Alexa examples using Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'jsgf' | |
module JSGF | |
class Grammar | |
# Convert a {Grammar} into a set of sample utterances for Alexa | |
# @option slots [Array] The rule names that should be used as slot names | |
# @return [Array<String>] An array of the example strings | |
def to_examples(slots:[]) | |
raise StandardError, "The grammar must have at least one root rule" unless roots | |
raise StandardError, "The grammar must contain at least one public rule" if roots.empty? | |
roots.flat_map {|name, rule| expand_atom(rule, ["#{name}Intent"], slots:slots) } | |
end | |
# Expand an {Atom} into an array of strings | |
# @return [Array] | |
def expand_atom(atom, prefix=[], slots:[], slot_name:nil) | |
case atom | |
when JSGF::Alternation | |
atom.map {|a| expand_atom(a, prefix, slots:slots, slot_name:slot_name) } | |
when JSGF::Atom | |
if prefix.first.is_a?(Array) | |
prefix.map {|pref| expand_atom(atom, pref, slots:slots, slot_name:slot_name) } | |
else | |
atom_name = atom.to_s | |
atom_name = "{#{atom_name}|#{slot_name}}" if slot_name && !atom_name.empty? | |
atom_name = nil if atom_name.empty? | |
[[*prefix, atom_name].compact.join(' ')] | |
end | |
when JSGF::Rule, Array | |
atom.reduce(prefix) {|memo, a| expand_atom(a, memo, slots:slots, slot_name:slot_name)} | |
when Hash | |
reference_name = atom[:name] | |
slot_name = slots.include?(reference_name) ? reference_name : nil | |
expand_atom(rules[atom[:name]], prefix, slots:slots, slot_name:slot_name) | |
else | |
raise "Unknown atom #{atom}" | |
end | |
end | |
end | |
end | |
# Example grammar. Replace this with your actual grammar. | |
grammar = JSGF.grammar 'ColorExpert' do | |
rule MyColorIs: 'my favorite color is :Color' | |
rule Color: %w{green red blue orange gold silver yellow black white} | |
end | |
File.write('utterances.txt', grammar.to_examples(slots:['Color'])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment