private void btnRecognize_Click(object sender, RoutedEventArgs e) { text = txtInput.Text.ToLower(); text = CleanText(text); words = text.Split(' '); wcount = words.Length; //words = words.Distinct().ToArray(); txtOutput.Text = text; Choices choices = new Choices(words); GrammarBuilder gb = new GrammarBuilder(new GrammarBuilder(choices), 0, wcount); //GrammarBuilder gb = new GrammarBuilder(txtInput.Text.Trim()); gb.Culture = new CultureInfo("es-MX"); Grammar grammar = new Grammar(gb); //recognizer = new SpeechRecognitionEngine("SR_MS_es-MX_TELE_11.0"); //recognizer = new SpeechRecognitionEngine(new CultureInfo("es-MX")); recognizer.LoadGrammar(grammar); recognizer.SetInputToWaveFile(@"E:\Proyectos\Audio Timestamps\chapter01.wav"); //recognizer.SetInputToDefaultAudioDevice(); recognizer.RecognizeCompleted += new EventHandler<RecognizeCompletedEventArgs>(RecognizeCompletedHandler); recognizer.RecognizeAsync(RecognizeMode.Multiple); }
public override void Initiate(IEnumerable<string> commandKeys) { var choices = new Choices(); choices.Add(commandKeys.ToArray()); var gr = new Grammar(new GrammarBuilder(choices)); _mainSpeechRecognitionEngine.RequestRecognizerUpdate(); _mainSpeechRecognitionEngine.LoadGrammar(gr); _mainSpeechRecognitionEngine.SpeechRecognized += _mainSpeechRecognitionEngine_SpeechRecognized; try { _mainSpeechRecognitionEngine.SetInputToDefaultAudioDevice(); } catch (Exception exception) { base.WriteLine(string.Format("Unable to set default input audio device. Error: {0}", exception.Message), OutputLevel.Error, null); return; } var subChoices = new Choices(); subChoices.Add(new[] { "tab", "enter" }); var subGr = new Grammar(new GrammarBuilder(subChoices)); _subSpeechRecognitionEngine.RequestRecognizerUpdate(); _subSpeechRecognitionEngine.LoadGrammar(subGr); _subSpeechRecognitionEngine.SpeechRecognized += _subSpeechRecognitionEngine_SpeechRecognized; _subSpeechRecognitionEngine.SetInputToDefaultAudioDevice(); }
public Grammar BuildGrammar() { Choices choiceBuilder = new Choices(); // Songs if (SongHelper.SongCount() > 0) // it freaks out if there's nothing in the one-of bit. { GrammarBuilder songBuilder = new GrammarBuilder(); songBuilder.Append("play song"); songBuilder.Append(SongHelper.GenerateSongChoices()); choiceBuilder.Add(songBuilder); } GrammarBuilder shuffleBuilder = new GrammarBuilder(); shuffleBuilder.Append("shuffle all songs"); choiceBuilder.Add(shuffleBuilder); // Playlists if (SongHelper.PlaylistCount() > 0) { GrammarBuilder playListBuilder = new GrammarBuilder(); playListBuilder.Append("play playlist"); playListBuilder.Append(SongHelper.GeneratePlaylistChoices()); choiceBuilder.Add(playListBuilder); GrammarBuilder shufflePlayListBuilder = new GrammarBuilder(); shufflePlayListBuilder.Append("shuffle playlist"); shufflePlayListBuilder.Append(SongHelper.GeneratePlaylistChoices()); choiceBuilder.Add(shufflePlayListBuilder); } Grammar gram = new Grammar(new GrammarBuilder(choiceBuilder)); return gram; }
public string Generate(Grammar Grammar, bool Debug) { if (string.IsNullOrEmpty(Grammar.GetTemplatePath())) return null; // generate the parser file StringBuilder parsers = new StringBuilder(); string parser = File.ReadAllText(Grammar.GetTemplatePath() + templateName); // build non terminal tokens foreach (NonTerminalSymbol s in Grammar.GetNonTerminals()) { string method = GenerateParseMethod(s); parsers.Append(method); } if (Debug) { parser = parser.Replace(@"<%Imports%>", "Imports TinyPG.Debug"); parser = parser.Replace(@"<%Namespace%>", "TinyPG.Debug"); parser = parser.Replace(@"<%IParser%>", "\r\n Implements IParser\r\n"); parser = parser.Replace(@"<%IParseTree%>", "IParseTree"); } else { parser = parser.Replace(@"<%Imports%>", ""); parser = parser.Replace(@"<%Namespace%>", Grammar.Directives["TinyPG"]["Namespace"]); parser = parser.Replace(@"<%IParser%>", ""); parser = parser.Replace(@"<%IParseTree%>", "ParseTree"); } parser = parser.Replace(@"<%ParseNonTerminals%>", parsers.ToString()); return parser; }
internal void LoadCurrentSyllabus(SyllabusTracker syllabusTracker) { if (_speechRecognitionEngine == null) return; // not currently running recognition _speechRecognitionEngine.RequestRecognizerUpdate(); _speechRecognitionEngine.UnloadAllGrammars(); // new choices consolidation for commands - one command per syllabus file line var commandLoad = new Choices(); foreach (var baseSyllabus in syllabusTracker.Syllabi) { foreach (var command in baseSyllabus.Commands) { commandLoad.Add(command); } } // add commands - should be per input language, but now English VoiceCommands.AddCommands(commandLoad); var gBuilder = new GrammarBuilder(); gBuilder.Append(commandLoad); var grammar = new Grammar(gBuilder) { Name = "Syllabus" }; _speechRecognitionEngine.LoadGrammar(grammar); var dictgrammar = new DictationGrammar("grammar:dictation#pronunciation") { Name = "Random" }; _speechRecognitionEngine.LoadGrammar(dictgrammar); }
private void Window1_Load() { obj.SpeakAsync("hello, Please Choose the Model of car...."); // Create a simple grammar that recognizes "red", "green", or "blue". Choices models = new Choices(); models.Add(new string[] { "toyota", "suzuki", "honda", "kia","bmw"}); // Create a GrammarBuilder object and append the Choices object. GrammarBuilder gb = new GrammarBuilder(); gb.Append(models); // Create the Grammar instance and load it into the speech recognition engine. Grammar g = new Grammar(gb); recognizer.LoadGrammar(g); recognizer.Enabled= true; // Register a handler for the SpeechRecognized event. recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized); }
/* * SpeechRecognizer * * @param GName - grammar file name */ public SpeechRecognizer(string GName, int minConfidence) { //creates the speech recognizer engine sr = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("pt-PT")); sr.SetInputToDefaultAudioDevice(); Console.WriteLine("confiança : " + minConfidence); sr.UpdateRecognizerSetting("CFGConfidenceRejectionThreshold", minConfidence); Grammar gr = null; //verifies if file exist, and loads the Grammar file, else load defualt grammar if (System.IO.File.Exists(GName)) { gr = new Grammar(GName); gr.Enabled = true; } else Console.WriteLine("Can't read grammar file"); //load Grammar to speech engine sr.LoadGrammar(gr); //assigns a method, to execute when speech is recognized sr.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(SpeechRecognized); //assigns a method, to execute when speech is NOT recognized sr.SpeechRecognitionRejected += new EventHandler<SpeechRecognitionRejectedEventArgs>(SpeechRecognitionRejected); // Start asynchronous, continuous speech recognition. sr.RecognizeAsync(RecognizeMode.Multiple); }
public VoiceRecognizer() { try { // Create a new SpeechRecognitionEngine instance. voiceEngine = new SpeechRecognitionEngine(new CultureInfo("en-US")); // Setup the audio device voiceEngine.SetInputToDefaultAudioDevice(); // Create the Grammar instance and load it into the speech recognition engine. Grammar g = new Grammar(CommandPool.BuildSrgsGrammar()); voiceEngine.LoadGrammar(g); //voiceEngine.EndSilenceTimeout = new TimeSpan(0, 0, 1); // Register a handler for the SpeechRecognized event voiceEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized); // Start listening in multiple mode (that is, don't quit after a single recongition) voiceEngine.RecognizeAsync(RecognizeMode.Multiple); IsSetup = true; } catch(Exception e) { IsSetup = false; } }
public The_Road_To_100() { InitializeComponent(); PmainManu.BringToFront(); PmainManu.Dock = DockStyle.Fill; organizeMenu(); if (Directory.Exists(@"C:\The Road To 100\user.ID 1")) { setPersonal_Screen(); Bcontinue.Enabled = true; } else { DirectoryInfo di = Directory.CreateDirectory(@"C:\The Road To 100"); di.Create(); di.Attributes = FileAttributes.Directory | FileAttributes.Hidden; } Choices commands = new Choices(); commands.Add(new string[] { "start", "finish", "close" }); GrammarBuilder GB = new GrammarBuilder(); GB.Append(commands); Grammar grammar = new Grammar(GB); sre.LoadGrammarAsync(grammar); sre.SetInputToDefaultAudioDevice(); sre.SpeechRecognized += sre_src; }
public void CreateGrammar() { var b = new GrammarBuilder(); b.Append(Config.ComputerName); Grammar = new Grammar(b); }
public void CreateGrammar() { var b = new GrammarBuilder(); b.Append(Config.StopListening); Grammar = new Grammar(b); }
private void LoadGrammar(Grammar grammar) { EndSpeechRecognition(); speechRecognizer.UnloadAllGrammars(); speechRecognizer.LoadGrammar(grammar); }
public void StartListening() { if (null != _ri) { _speechEngine = new SpeechRecognitionEngine(_ri.Id); // Create a grammar from grammar definition XML file. using (var memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(KAIT.Kinect.Service.Properties.Resources.SpeechGrammar))) { var g = new Grammar(memoryStream); _speechEngine.LoadGrammar(g); } _speechEngine.SpeechRecognized += _speechEngine_SpeechRecognized; _speechEngine.SpeechRecognitionRejected += _speechEngine_SpeechRecognitionRejected; // let the convertStream know speech is going active _convertStream.SpeechActive = true; _speechEngine.SetInputToAudioStream( _convertStream, new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null)); _speechEngine.RecognizeAsync(RecognizeMode.Multiple); } }
private Grammar BrightnessGrammar() { // Change/Set Brightness to Choices var choices = new Choices(); for (var i = -255; i <= 255; i++) { SemanticResultValue choiceResultValue = new SemanticResultValue(i.ToString(), i); GrammarBuilder resultValueBuilder = new GrammarBuilder(choiceResultValue); choices.Add(resultValueBuilder); } GrammarBuilder changeGrammar = "Change"; GrammarBuilder setGrammar = "Set"; GrammarBuilder brightnessGrammar = "Brightness"; GrammarBuilder toGrammar = "To"; SemanticResultKey resultKey = new SemanticResultKey("brightness", choices); GrammarBuilder resultContrast = new GrammarBuilder(resultKey); Choices alternatives = new Choices(changeGrammar, setGrammar); GrammarBuilder result = new GrammarBuilder(alternatives); result.Append(brightnessGrammar); result.Append(toGrammar); result.Append(resultContrast); Grammar grammar = new Grammar(result); grammar.Name = "Set Brightness"; return grammar; }
public SpeechRecogniser() { RecognizerInfo ri = SpeechRecognitionEngine.InstalledRecognizers().Where(r => r.Id == RecognizerId).FirstOrDefault(); if (ri == null) return; sre = new SpeechRecognitionEngine(ri.Id); // Build a simple grammar of shapes, colors, and some simple program control var instruments = new Choices(); foreach (var phrase in InstrumentPhrases) instruments.Add(phrase.Key); var objectChoices = new Choices(); objectChoices.Add(instruments); var actionGrammar = new GrammarBuilder(); //actionGrammar.AppendWildcard(); actionGrammar.Append(objectChoices); var gb = new GrammarBuilder(); gb.Append(actionGrammar); var g = new Grammar(gb); sre.LoadGrammar(g); sre.SpeechRecognized += sre_SpeechRecognized; sre.SpeechHypothesized += sre_SpeechHypothesized; sre.SpeechRecognitionRejected += new EventHandler<SpeechRecognitionRejectedEventArgs>(sre_SpeechRecognitionRejected); var t = new Thread(StartDMO); t.Start(); valid = true; }
/// <summary> /// Loads the grammar in to the recognition engine. /// </summary> protected virtual void LoadGrammar(string pathToGrammar, EventHandler<LoadGrammarCompletedEventArgs> GrammarLoaded) { NMDebug.Log("Loading Grammar..."); Grammar grammar = new Grammar(pathToGrammar + @"Default.xml"); RecognitionEngine.LoadGrammarCompleted += GrammarLoaded; RecognitionEngine.LoadGrammarAsync(grammar); }
/// <summary> /// 語音辨識初始化 /// </summary> private void CreateSpeechRecongnition() { //Initialize speech recognition var recognizerInfo = (from a in SpeechRecognitionEngine.InstalledRecognizers() where a.Culture.Name == "en-US" select a).FirstOrDefault(); if (recognizerInfo != null) { this.speechEngine = new SpeechRecognitionEngine(recognizerInfo.Id); Choices recognizerString = new Choices(); recognizerString.Add("start"); GrammarBuilder grammarBuilder = new GrammarBuilder(); //Specify the culture to match the recognizer in case we are running in a different culture. grammarBuilder.Culture = recognizerInfo.Culture; grammarBuilder.Append(recognizerString); // Create the actual Grammar instance, and then load it into the speech recognizer. var grammar = new Grammar(grammarBuilder); //載入辨識字串 this.speechEngine.LoadGrammarAsync(grammar); this.speechEngine.SpeechRecognized += SreSpeechRecognized; //設定input音源(目前使用預設音源) this.speechEngine.SetInputToDefaultAudioDevice(); this.speechEngine.RecognizeAsync(RecognizeMode.Multiple); } }
void BuildSpeechEngine(RecognizerInfo rec) { _speechEngine = new SpeechRecognitionEngine(rec.Id); var choices = new Choices(); choices.Add("venus"); choices.Add("mars"); choices.Add("earth"); choices.Add("jupiter"); choices.Add("sun"); var gb = new GrammarBuilder { Culture = rec.Culture }; gb.Append(choices); var g = new Grammar(gb); _speechEngine.LoadGrammar(g); //recognized a word or words that may be a component of multiple complete phrases in a grammar. _speechEngine.SpeechHypothesized += new EventHandler<SpeechHypothesizedEventArgs>(SpeechEngineSpeechHypothesized); //receives input that matches any of its loaded and enabled Grammar objects. _speechEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(_speechEngineSpeechRecognized); //receives input that does not match any of its loaded and enabled Grammar objects. _speechEngine.SpeechRecognitionRejected += new EventHandler<SpeechRecognitionRejectedEventArgs>(_speechEngineSpeechRecognitionRejected); //C# threads are MTA by default and calling RecognizeAsync in the same thread will cause an COM exception. var t = new Thread(StartAudioStream); t.Start(); }
public void InicializeSpeechRecognize() { RecognizerInfo ri = GetKinectRecognizer(); if (ri == null) { throw new RecognizerNotFoundException(); } try { _sre = new SpeechRecognitionEngine(ri.Id); } catch(Exception e) { Console.WriteLine(e.Message); throw e; } var choises = new Choices(); foreach(CommandSpeechRecognition cmd in _commands.Values) { choises.Add(cmd.Choise); } var gb = new GrammarBuilder {Culture = ri.Culture}; gb.Append(choises); var g = new Grammar(gb); _sre.LoadGrammar(g); _sre.SpeechRecognized += SreSpeechRecognized; _sre.SpeechHypothesized += SreSpeechHypothesized; _sre.SpeechRecognitionRejected += SreSpeechRecognitionRejected; }
public IntroGrammar() { Choices majors = new Choices(); majors.Add(new SemanticResultValue("Computer Science", "CSC")); SemanticResultKey majorKey = new SemanticResultKey(Slots.Major.ToString(), majors); Choices years = new Choices(); for (int i = 2001; i < 2020; i++) { years.Add(new SemanticResultValue(i.ToString(), i)); } SemanticResultKey year = new SemanticResultKey(Slots.GradYear.ToString(), years); Choices yesOrNo = new Choices(); yesOrNo.Add(new SemanticResultValue("yes", "yes")); yesOrNo.Add(new SemanticResultValue("yeah", "yes")); yesOrNo.Add(new SemanticResultValue("yep", "yes")); yesOrNo.Add(new SemanticResultValue("no", "no")); yesOrNo.Add(new SemanticResultValue("nope", "no")); SemanticResultKey yesNo = new SemanticResultKey(Slots.YesNo.ToString(), yesOrNo); Choices options = new Choices(); options.Add(majorKey); options.Add(year); options.Add(yesNo); GrammarBuilder builder = new GrammarBuilder(); builder.Append(options); grammar = new Grammar(builder); }
public void StartListening() { if (null != _ri) { _speechEngine = new SpeechRecognitionEngine(_ri.Id); // Create a grammar from grammar definition XML file. using (var memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(KAIT.Kinect.Service.Properties.Resources.SpeechGrammar))) { var g = new Grammar(memoryStream); _speechEngine.LoadGrammar(g); } _speechEngine.SpeechRecognized += _speechEngine_SpeechRecognized; _speechEngine.SpeechRecognitionRejected += _speechEngine_SpeechRecognitionRejected; // let the convertStream know speech is going active _convertStream.SpeechActive = true; // For long recognition sessions (a few hours or more), it may be beneficial to turn off adaptation of the acoustic model. // This will prevent recognition accuracy from degrading over time. ////speechEngine.UpdateRecognizerSetting("AdaptationOn", 0); _speechEngine.SetInputToAudioStream( _convertStream, new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null)); _speechEngine.RecognizeAsync(RecognizeMode.Multiple); //_isInTrainingMode = true; } //else // throw new InvalidOperationException("RecognizerInfo cannot be null"); }
public override Tree<SyntaxToken> Read(LinkedList<MixedToken> tokens, Grammar grammar) { // Do not create negate syntax token if we are able to create a subtract syntax token var lastNegateNode = tokens.FindLastNode(t => t.Value.IsLexicToken && t.Value.LexicToken is SubtractToken && (t.Previous != null && !t.Previous.Value.IsTree || t.Previous == null)); if (lastNegateNode != null) { var next = lastNegateNode.Next; if (next == null) throw new ParserException("Unexpected argument of 'negate' operator."); if (!next.Value.IsTree) throw new ParserException("Argument of 'negate' operator was not parsed."); NegateSyntaxToken token = new NegateSyntaxToken(); Tree<SyntaxToken> tree = new Tree<SyntaxToken>(token); tree.Leafs.Add(next.Value.Tree); tokens.AddBefore(lastNegateNode, new MixedToken(tree)); tokens.Remove(lastNegateNode); tokens.Remove(next); return tree; } return null; }
public static SpeechRecognitionEngine getEngine(String lang) { if(init) recEngine.Dispose(); Console.WriteLine("Kastat current engine"); culture = new System.Globalization.CultureInfo(lang); choices = new Choices(); grammarBuilder = new GrammarBuilder(); VoiceCommands.Init(lang); choices.Add(VoiceCommands.GetAllCommands()); grammarBuilder.Culture = culture; grammarBuilder.Append(choices); grammar = new Grammar(grammarBuilder); Console.WriteLine("Initialiserat svenskt grammar"); try { recEngine = new SpeechRecognitionEngine(culture); recEngine.LoadGrammarAsync(grammar); Console.WriteLine("Laddat enginen med " + lang); } catch (UnauthorizedAccessException e) { Console.WriteLine("Error: UnauthorizedAccessException"); Console.WriteLine(e.ToString()); } init = true; recEngine.SetInputToDefaultAudioDevice(); return recEngine; }
//Speech recognizer private SpeechRecognitionEngine CreateSpeechRecognizer() { RecognizerInfo ri = GetKinectRecognizer(); SpeechRecognitionEngine sre; sre = new SpeechRecognitionEngine(ri.Id); //words we need the program to recognise var grammar = new Choices(); grammar.Add(new SemanticResultValue("moustache", "MOUSTACHE")); grammar.Add(new SemanticResultValue("top hat", "TOP HAT")); grammar.Add(new SemanticResultValue("glasses", "GLASSES")); grammar.Add(new SemanticResultValue("sunglasses", "SUNGLASSES")); grammar.Add(new SemanticResultValue("tie", "TIE")); grammar.Add(new SemanticResultValue("bow", "BOW")); grammar.Add(new SemanticResultValue("bear", "BEAR")); //etc var gb = new GrammarBuilder { Culture = ri.Culture }; gb.Append(grammar); var g = new Grammar(gb); sre.LoadGrammar(g); //Events for recognising and rejecting speech sre.SpeechRecognized += SreSpeechRecognized; sre.SpeechRecognitionRejected += SreSpeechRecognitionRejected; return sre; }
// Use this for initialization void Start() { grammar = new Grammar(); grammar.AddTag("story", new string[] { "#story_beginning# #story_problem# #story_climax# #story_ending#" }); grammar.AddTag("story_beginning", new string[] { "Once upon a time there was a valiant #animal#" }); grammar.AddTag("story_problem", new string[] { "that never #difficulty_verb#.", "that one day heard some strange words: #strange_calling#" }); grammar.AddTag("story_climax", new string[] { "Suddenly, he decided to #resolution_verb#." }); grammar.AddTag("story_ending", new string[] { "Finally he could #result_verb# without worries." }); grammar.AddTag("difficulty_verb", new string[] {"slept", "danced", "talked"}); grammar.AddTag("resolution_verb", new string[] {"run", "sing", "give up"}); grammar.AddTag("result_verb", new string[] {"sleep", "dance", "talk freely"}); grammar.AddTag("strange_calling", new string[] {"Hello #name#!", "Hello my #writer_object#!"}); grammar.AddTag("animal", new string[] {"dolphin", "dog", "cat", "lamb", "lion"}); grammar.AddTag("name", new string[] {"Mr. Gil", "Madame", "Masked Man"}); grammar.AddTag("writer_object", new string[] {"text", "book", "beloved code"}); InvokeRepeating("TestEvaluation", 1f, 2f); }
public Node Parse(Grammar grammar, IEnumerable<Token> tokens) { _chart.Clear(); _chart.Add(new State(grammar.GetStart().Earley(0))); using (var enumerator = tokens.GetEnumerator()) { var token = enumerator.Current; for (int i = 0; enumerator.MoveNext(); i++) { if (i >= _chart.Count) SyntaxError(token); token = enumerator.Current; var rules = _chart[i]; for (int j = 0; j < rules.Count; j++) { if (!rules[j].IsFinal) if (rules[j].NextTerm.GetType() == typeof (NonTerminal)) Predict(grammar, i, j); else Scan(token, i, j); else Complete(i, j); } } } int n = _chart.Count - 1; var complete = _chart[n].FinalRules(grammar.Start).FirstOrDefault(); if (complete == null) SyntaxError(); return BuildTree(complete, n); }
public SpeechRecognizer(string file, KinectSensor sensor) { this.grammarFile = file; this.kinectSensor = sensor; audioSource = kinectSensor.AudioSource; audioSource.AutomaticGainControlEnabled = false; audioSource.BeamAngleMode = BeamAngleMode.Adaptive; Func<RecognizerInfo, bool> matchingFunc = r => { string value; r.AdditionalInfo.TryGetValue("Kinect", out value); return "True".Equals(value, StringComparison.InvariantCultureIgnoreCase) && "en-US".Equals(r.Culture.Name, StringComparison.InvariantCultureIgnoreCase); }; var recognizerInfo = SpeechRecognitionEngine.InstalledRecognizers().Where(matchingFunc).FirstOrDefault(); if (recognizerInfo == null) return; speechRecognitionEngine = new SpeechRecognitionEngine(recognizerInfo.Id); var grammar = new Grammar(grammarFile); speechRecognitionEngine.LoadGrammar(grammar); audioStream = audioSource.Start(); speechRecognitionEngine.SetInputToAudioStream(audioStream, new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null)); speechRecognitionEngine.AudioStateChanged += onAudioStateChanged; speechRecognitionEngine.SpeechRecognized += onSpeechRecognized; speechRecognitionEngine.RecognizeCompleted += onSpeechRecognizeCompleted; speechRecognitionEngine.EmulateRecognizeCompleted += onEmulateRecognizeCompleted; }
public void initRS() { try { SpeechRecognitionEngine sre = new SpeechRecognitionEngine(new CultureInfo("en-US")); var words = new Choices(); words.Add("Hello"); words.Add("Jump"); words.Add("Left"); words.Add("Right"); var gb = new GrammarBuilder(); gb.Culture = new System.Globalization.CultureInfo("en-US"); gb.Append(words); Grammar g = new Grammar(gb); sre.LoadGrammar(g); sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized); sre.SetInputToDefaultAudioDevice(); sre.RecognizeAsync(RecognizeMode.Multiple); } catch (Exception e) { label1.Text = "init RS Error : " + e.ToString(); } }
public SpeechEngine(KinectHandler handler) { _kinectHandler = handler; _commands = new GrammarBuilder(); _grammar = new Grammar(_commands); _grammar.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(_grammar_SpeechRecognized); }
protected virtual void Init(Grammar root) { }
private void LoadSpeech() { try { engine = new SpeechRecognitionEngine(); //Instancia engine.SetInputToDefaultAudioDevice(); //microfone Choices cNumbers = new Choices(); for (int i = 0; i <= 100; i++) { cNumbers.Add(i.ToString()); } Choices c_commandosOfSystem = new Choices(); c_commandosOfSystem.Add(GrammarRules.WhatTimeIs.ToArray()); // Adicioando WhatsTimeIs da classe GrammarRules c_commandosOfSystem.Add(GrammarRules.whatDateIs.ToArray()); // WhatDateIs da classe GrammarRules c_commandosOfSystem.Add(GrammarRules.JarvisStartListening.ToArray()); c_commandosOfSystem.Add(GrammarRules.JarvisStopListening.ToArray()); c_commandosOfSystem.Add(GrammarRules.MinimizeWindow.ToArray()); // minimizar janela c_commandosOfSystem.Add(GrammarRules.normalWindow.ToArray()); //Máximizar janela c_commandosOfSystem.Add(GrammarRules.conversaWindows.ToArray()); //Conversa c_commandosOfSystem.Add(GrammarRules.conversa2Windows.ToArray()); //apresentação c_commandosOfSystem.Add(GrammarRules.conversa3Windows.ToArray()); c_commandosOfSystem.Add(GrammarRules.conversa4Windows.ToArray()); c_commandosOfSystem.Add(GrammarRules.ChanceVoice.ToArray()); //Mudar voz do sistema //Comando "pare de ouvir" == Jarvis GrammarBuilder gb_comandsOfSystem = new GrammarBuilder(); gb_comandsOfSystem.Append(c_commandosOfSystem); Grammar g_commandsOfSystem = new Grammar(gb_comandsOfSystem); g_commandsOfSystem.Name = "sys"; //Ajuda identificar em qual grámatica foi chamado o comando GrammarBuilder gbNumber = new GrammarBuilder(); gbNumber.Append(cNumbers); // 5 vezes gbNumber.Append(new Choices("vezes", "mais", "menos", "por")); gbNumber.Append(cNumbers); Grammar gNumbers = new Grammar(gbNumber); gNumbers.Name = "calc"; engine.LoadGrammar(g_commandsOfSystem); //carregar a gramática //carregar a gramática // engine.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(words)))); engine.SpeechRecognized += new EventHandler <SpeechRecognizedEventArgs>(rec); //nivel do aúdio engine.AudioLevelUpdated += new EventHandler <AudioLevelUpdatedEventArgs>(audioLevel); engine.SpeechRecognitionRejected += new EventHandler <SpeechRecognitionRejectedEventArgs>(rej); engine.RecognizeAsync(RecognizeMode.Multiple); //Iniciar o reconhecimento Speaker.Speak("Estou carregando os arquivos "); } catch (Exception ex) { MessageBox.Show("Ocorreu um erro", ex.ToString()); } }
public override Pattern Regen(Grammar g) { return(new ReduceAction(L.Regen(g), ActionCodegen)); }
public GrammarSanity(Grammar grammar) { this.grammar = grammar; }
public ScriptInterpreter(Grammar grammar) : this(new LanguageData(grammar)) { }
public string Generate(Grammar Grammar, bool Debug) { if (string.IsNullOrEmpty(Grammar.GetTemplatePath())) { return(null); } string scanner = File.ReadAllText(Grammar.GetTemplatePath() + templateName); int counter = 2; StringBuilder tokentype = new StringBuilder(); StringBuilder regexps = new StringBuilder(); StringBuilder skiplist = new StringBuilder(); foreach (TerminalSymbol s in Grammar.SkipSymbols) { skiplist.AppendLine(" SkipList.Add(TokenType." + s.Name + ");"); } if (Grammar.FileAndLine != null) { skiplist.AppendLine(" FileAndLine = TokenType." + Grammar.FileAndLine.Name + ";"); } // build system tokens tokentype.AppendLine("\r\n //Non terminal tokens:"); tokentype.AppendLine(Helper.Outline("_NONE_", 3, "= 0,", 5)); tokentype.AppendLine(Helper.Outline("_UNDETERMINED_", 3, "= 1,", 5)); // build non terminal tokens tokentype.AppendLine("\r\n //Non terminal tokens:"); foreach (Symbol s in Grammar.GetNonTerminals()) { tokentype.AppendLine(Helper.Outline(s.Name, 3, "= " + String.Format("{0:d},", counter), 5)); counter++; } // build terminal tokens tokentype.AppendLine("\r\n //Terminal tokens:"); bool first = true; foreach (TerminalSymbol s in Grammar.GetTerminals()) { regexps.Append(" regex = new Regex(" + s.Expression.ToString() + ");\r\n"); regexps.Append(" Patterns.Add(TokenType." + s.Name + ", regex);\r\n"); regexps.Append(" Tokens.Add(TokenType." + s.Name + ");\r\n\r\n"); if (first) { first = false; } else { tokentype.AppendLine(","); } tokentype.Append(Helper.Outline(s.Name, 3, "= " + String.Format("{0:d}", counter), 5)); counter++; } scanner = scanner.Replace(@"<%SkipList%>", skiplist.ToString()); scanner = scanner.Replace(@"<%RegExps%>", regexps.ToString()); scanner = scanner.Replace(@"<%TokenType%>", tokentype.ToString()); if (Debug) { scanner = scanner.Replace(@"<%Namespace%>", "TinyPG.Debug"); scanner = scanner.Replace(@"<%IToken%>", " : TinyPG.Debug.IToken"); } else { scanner = scanner.Replace(@"<%Namespace%>", Grammar.Directives["TinyPG"]["Namespace"]); scanner = scanner.Replace(@"<%IToken%>", ""); } return(scanner); }
public UserifyVisitor(Grammar g) { grammar = g; }
public SLR1Parser(Grammar grammar) : base(grammar) { }
internal ParserDataBuilder(LanguageData language) { _language = language; _grammar = _language.Grammar; }
public void TestTableAcceptor() { var symbols = new Dictionary <string, Symbol> { { "S", new Symbol(Symbol.SymTypes.NoTerminal, "S") }, { "E", new Symbol(Symbol.SymTypes.NoTerminal, "E") }, { "E'", new Symbol(Symbol.SymTypes.NoTerminal, "E'") }, { "T", new Symbol(Symbol.SymTypes.NoTerminal, "T") }, { "T'", new Symbol(Symbol.SymTypes.NoTerminal, "T'") }, { "F", new Symbol(Symbol.SymTypes.NoTerminal, "F") }, { "id", new Symbol(Symbol.SymTypes.Terminal, "id") }, { "+", new Symbol(Symbol.SymTypes.Terminal, "+") }, { "*", new Symbol(Symbol.SymTypes.Terminal, "*") }, { "(", new Symbol(Symbol.SymTypes.Terminal, "(") }, { ")", new Symbol(Symbol.SymTypes.Terminal, ")") }, { "EPSILON", new Symbol(Symbol.SymTypes.Epsilon, "EPSILON") } }; var productionRules = new List <ProductionRule>(); var productionRuleBody = new List <Symbol> { symbols["Program"] }; var productionRule = new ProductionRule(symbols["Start"], productionRuleBody); productionRules.Add(productionRule); productionRuleBody = new List <Symbol> { symbols["Form_list"] }; productionRule = new ProductionRule(symbols["Program"], productionRuleBody); productionRules.Add(productionRule); productionRuleBody = new List <Symbol> { symbols["Form_list"], symbols["Form"] }; productionRule = new ProductionRule(symbols["Form_list"], productionRuleBody); productionRules.Add(productionRule); productionRuleBody = new List <Symbol> { symbols["Definition"] }; productionRule = new ProductionRule(symbols["Form"], productionRuleBody); productionRules.Add(productionRule); productionRuleBody = new List <Symbol> { symbols["Expression"] }; productionRule = new ProductionRule(symbols["Form"], productionRuleBody); productionRules.Add(productionRule); productionRuleBody = new List <Symbol> { symbols["Definition_list"], symbols["Definition"] }; productionRule = new ProductionRule(symbols["Definition_list"], productionRuleBody); productionRules.Add(productionRule); productionRuleBody = new List <Symbol> { symbols["Variable_definition"] }; productionRule = new ProductionRule(symbols["Definition"], productionRuleBody); productionRules.Add(productionRule); productionRuleBody = new List <Symbol> { symbols["(Paren"] }; productionRule = new ProductionRule(symbols["Definition"], productionRuleBody); productionRules.Add(productionRule); productionRuleBody = new List <Symbol> { symbols["Variable_definition"] }; productionRule = new ProductionRule(symbols["Definition"], productionRuleBody); productionRules.Add(productionRule); var g = new Grammar(productionRules, symbols.Values.ToList()); //build table var analyzer = new LR1Table(g); analyzer.Print(); Assert.IsTrue(analyzer.Accept("(id)")); }
protected virtual void AssignTokenIDTypes(Grammar root) { }
public static string ToString(Grammar grammar) => ToString(grammar.Rules);
protected virtual void AssignStringTypes(Grammar root) { }
protected virtual void DefineTokenNamesAndLiteralsInGrammar(Grammar root) { }
} // Name public override void Execute() { Log.Debug("Loading uploaded HMRC data for customer {0}...", this.customerID); List <MpData> lst = DB.Fill <MpData>( "LoadCustomerUploadedHmrcAccountData", CommandSpecies.StoredProcedure, new QueryParameter("CustomerID", this.customerID) ); if (lst.Count < 1) { Log.Debug("Customer {0} has no uploaded HMRC marketplace.", this.customerID); return; } // if Log.Say( lst.Count > 1 ? Severity.Alert : Severity.Debug, "Customer {0} has {1}.", this.customerID, Grammar.Number(lst.Count, "uploaded HMRC marketplace") ); var vendorInfo = global::Integration.ChannelGrabberConfig.Configuration.Instance.Hmrc; int counter = 1; foreach (MpData mpData in lst) { try { AccountModel x = Serialized.Deserialize <AccountModel>(Encrypted.Decrypt(mpData.SecurityData)); if (x.password != VendorInfo.TopSecret) { Log.Warn( "Password is not '{1}' for marketplace {0}, skipping it.", mpData.MpID, VendorInfo.TopSecret ); continue; } // if } catch { Log.Warn("Failed to deserialise security data for marketplace {0}, skipping it.", mpData.MpID); continue; } // try var model = new AccountModel { accountTypeName = vendorInfo.Name, displayName = mpData.NewEmail, name = mpData.NewEmail, login = mpData.NewEmail, password = VendorInfo.TopSecret, }; string displayName = string.Format("{0}{1}", mpData.NewEmail, lst.Count > 1 ? "-" + counter : string.Empty); Log.Debug("Updating security data and display name for marketplace id {0}...", mpData.MpID); DB.ExecuteNonQuery( "UpdateCustomerUploadedHmrcAccountData", CommandSpecies.StoredProcedure, new QueryParameter("@MpID", mpData.MpID), new QueryParameter("@DisplayName", displayName), new QueryParameter("@SecurityData", new Encrypted(new Serialized(model))) ); Log.Debug("Updated security data and display name for marketplace id {0}.", mpData.MpID); counter++; } // for each } // Execute
protected virtual void AliasTokenIDsAndLiterals(Grammar root) { }
private void CreateGrammar() { _grammar = _grammarLoader.CreateGrammar(); }
protected internal virtual void DefineTokens(Grammar root) { }
public void PerformanceTest() { // this test shows that var grammar = new Grammar(new QuerySyntax()); var lexer = new Lexer(grammar); var parser = new Parser(grammar); var source = "(1+3)*(5.0/0.4)-16.3e5"; //var source = "(color=white or color=green) and wheels >=10"; var shuntingYard = new ShuntingYardParser(grammar); var tokens = lexer.Tokenize(source).ToArray(); var rpn = shuntingYard.BuildRPN(tokens); var exp = shuntingYard.BuildAST <object, double>(tokens); var expression = parser.Parse <object, double>(source); var d = expression.Compile(); var sw = new Stopwatch(); sw.Start(); for (var i = 0; i < 10000; i++) { lexer.Tokenize(source); } sw.Stop(); Debug.WriteLine("tokenizing: " + sw.ElapsedMilliseconds); sw = new Stopwatch(); sw.Start(); for (var i = 0; i < 10000; i++) { shuntingYard.BuildRPN(tokens); } sw.Stop(); Debug.WriteLine("infix->postfix: " + sw.ElapsedMilliseconds); sw = new Stopwatch(); sw.Start(); for (var i = 0; i < 10000; i++) { shuntingYard.BuildAST <object, double>(tokens); } sw.Stop(); Debug.WriteLine("infix->AST: " + sw.ElapsedMilliseconds); sw = new Stopwatch(); sw.Start(); for (var i = 0; i < 10000; i++) { parser.Parse <object, double>(source); } sw.Stop(); Debug.WriteLine("source->ast: " + sw.ElapsedMilliseconds); sw = new Stopwatch(); sw.Start(); for (var i = 0; i < 10000; i++) { expression.Compile(); } sw.Stop(); Debug.WriteLine("ast->IL: " + sw.ElapsedMilliseconds); }
private void Form1_Load(object sender, EventArgs e) { this.FormBorderStyle = FormBorderStyle.None; //Vollbildmodus this.WindowState = FormWindowState.Maximized; //Vollbildmodus SvgImage.Width = 1200; // Größe des Svg-Bilds SvgImage.Height = 850; //Füge die Svg-Datei in die Picturebox(SvgImage) ein SVGParser.MaximumSize = new Size(SvgImage.Width, SvgImage.Height); selectedPath = Application.StartupPath + @"/Europa.svg"; svgDocument = SVGParser.GetSvgDocument(selectedPath); SvgImage.Image = SVGParser.GetBitmapFromSVG(selectedPath); int i = 0; string pfad = Application.StartupPath + @"/LänderPunkte.txt"; // Textdatei öffnen, Umlaute richtig lesen StreamReader DateiLesen = new StreamReader(pfad, Encoding.Default); // Solange Dateiende nicht erreicht while (!DateiLesen.EndOfStream) { //eine Zeile aus der Textdatei lesen string zeile = DateiLesen.ReadLine(); string[] daten = zeile.Split(';'); //Fülle das Array Länder Länder[i] = new Land(); Länder[i].setNummer(Convert.ToInt32(daten[0])); Länder[i].setName(daten[1]); Länder[i].setpunkteLand(Convert.ToInt32(daten[2])); Länder[i].setHaupstadt(daten[3]); Länder[i].setpunkteHauptstadt(Convert.ToInt32(daten[4])); Länder[i].setpunkteBeides(Convert.ToInt32(daten[5])); i++; } // Datei schließen DateiLesen.Close(); //Sprachsteuerung try { Recogn.SetInputToDefaultAudioDevice(); Recogn.SpeechRecognized += new EventHandler <SpeechRecognizedEventArgs>(recognizer_Speechrecognized); Recogn.SpeechRecognitionRejected += new EventHandler <SpeechRecognitionRejectedEventArgs>(recognizer_Speechnotrecognized); } catch { MessageBox.Show("Mikrofon fehlt!"); } try { Grammar Grammatik = new Grammar(Application.StartupPath + @"/grammar.xml", "LänderuStädte"); Recogn.UnloadAllGrammars(); Recogn.LoadGrammar(Grammatik); Recogn.RecognizeAsync(RecognizeMode.Multiple); } catch { MessageBox.Show("fEHleeEeeEeR!11!"); } }
void conectaActiva() { //Nos aseguramos que la cuenta de sensores conectados sea de al menos 1 if (KinectSensor.KinectSensors.Count > 0) { //Checamos que la variable _sensor sea nula if (this.sensor == null) { //Asignamos el primer sensor Kinect a nuestra variable this.sensor = KinectSensor.KinectSensors[0]; if (this.sensor != null) { try { //Iniciamos el dispositivo Kinect this.sensor.Start(); //Esto es opcional pero ayuda a colocar el dispositivo Kinect a un cierto angulo de inclinacion, desde -27 a 27 // sensor.ElevationAngle = 3; //Informamos que se ha conectado e inicializado correctamente el dispositivo Kinect // Error err = new VME.Error(RecursosLocalizables.StringResources.KinectDetect, 3); // err.Show(); } catch (Exception ex) { } //Creamos esta variable ri que tratara de encontrar un language pack valido haciendo uso del metodo obtenerLP RecognizerInfo ri = obtenerLP(); //Si se encontro el language pack requerido lo asignaremos a nuestra variable speechengine if (ri != null) { this.speechengine = new SpeechRecognitionEngine(ri.Id); //Creamos esta variable opciones la cual almacenara las opciones de palabras o frases que podran ser reconocidas por el dispositivo Choices opciones = new Choices(); //Comenzamos a agregar las opciones comenzando por el valor de opcion que tratamos reconocer y una llave que identificara a ese valor //Por ejemplo en esta linea "uno" es el valor de opcion y "UNO" es la llave opciones.Add(RecursosLocalizables.StringResources.aceptar, "UNO"); //En esta linea "windows ocho" es el valor de opcion y "TRES" es la llave y asi sucesivamente opciones.Add(new SemanticResultValue("windows", "TRES")); opciones.Add(new SemanticResultValue("new windows", "TRES")); //Esta variable creará todo el conjunto de frases y palabras en base a nuestro lenguaje elegido en la variable ri var grammarb = new GrammarBuilder { Culture = ri.Culture }; //Agregamos las opciones de palabras y frases a grammarb grammarb.Append(opciones); //Creamos una variable de tipo Grammar utilizando como parametro a grammarb var grammar = new Grammar(grammarb); //Le decimos a nuestra variable speechengine que cargue a grammar this.speechengine.LoadGrammar(grammar); //mandamos llamar al evento SpeechRecognized el cual se ejecutara cada vez que una palabra sea detectada speechengine.SpeechRecognized += new EventHandler <SpeechRecognizedEventArgs>(speechengine_SpeechRecognized); //speechengine inicia la entrada de datos de tipo audio speechengine.SetInputToAudioStream(sensor.AudioSource.Start(), new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null)); speechengine.RecognizeAsync(RecognizeMode.Multiple); } } } } }
public abstract string Flatten(Grammar grammar);
public RankingScore(Grammar grammar) : base(grammar, "Score") { }
private void OnGetGrammar(Grammar response, Dictionary <string, object> customData) { Log.Debug("ExampleSpeechToText.OnGetGrammar()", "{0}", customData["json"].ToString()); _getGrammarTested = true; }
public void loadCommands(XmlNodeList arg, String profileName) { ui.log("GrammarHandler.loadCommands(xmlNodeList)"); xmlCommands = arg; if (xmlCommands.Count == 0) { //MessageBox.Show("Please add some commands") lvCommands.Clear(); ui.setStatus("Profile is empty, please createa some commands!"); return; } if (commands != null) { commands.Clear(); } // Reset //ui.recognizer.sre.Dispose(); clear(); // Configure ListView lvCommands.Clear(); lvCommands.View = View.Details; lvCommands.GridLines = true; lvCommands.Sorting = SortOrder.Ascending; lvCommands.Columns.Add("Command", 500, HorizontalAlignment.Left); lvCommands.Columns.Add("Type", 146, HorizontalAlignment.Left); int cnt = 0; //Console.WriteLine("##### " + xmlCommands.Count); ui.log("---------------"); foreach (XmlNode node in xmlCommands) { String speech = node.ChildNodes[0].InnerText.ToString(); if (speech != "") { cnt++; speechCommands.Add(node.ChildNodes[0].InnerText.ToString()); //Console.WriteLine(command.InnerXml.ToString()); //Console.WriteLine(node.ChildNodes[0].InnerText); //ui.log(node.ChildNodes[0].InnerText.ToString()); CommandVO command = new CommandVO(); command.method = node.Attributes[0].InnerText.ToString(); command.haltOnAppChange = intStringToBoolean(node.Attributes[1].InnerText.ToString()); command.duration = float.Parse(node.Attributes[2].InnerText.ToString()); command.speech = node.ChildNodes[0].InnerText; command.window = node.ChildNodes[1].InnerText; command.autoType = node.ChildNodes[2].InnerText; command.clipboard = node.ChildNodes[3].InnerText; //Console.WriteLine("node.ChildNodes[3].Attributes[0].ToString() = " + node.ChildNodes[3].Attributes[0].Value.ToString()); command.clipboardAutoPaste = intStringToBoolean(node.ChildNodes[3].Attributes[0].Value.ToString()); command.multiKey = node.ChildNodes[4].InnerText; command.multiKeyCtrl = intStringToBoolean(node.ChildNodes[4].Attributes[0].Value.ToString()); command.multiKeyAlt = intStringToBoolean(node.ChildNodes[4].Attributes[1].Value.ToString()); command.multiKeyShift = intStringToBoolean(node.ChildNodes[4].Attributes[2].Value.ToString()); ListViewItem listViewItem = new ListViewItem(command.speech); listViewItem.SubItems.Add(command.method); lvCommands.Items.Add(listViewItem); commands.Add(command); //ui.log(command.speech + ": " + "\t" + "method:" + command.method.ToString() + "\t" + "haltOnAppChange:" + command.haltOnAppChange.ToString() + "\t" + "+delay:" + command.delay.ToString()); ui.log("Command added: [" + command.speech + "]"); //ui.log("command.clipboard: [\n" + command.clipboard + "\n]"); //Server.UrlDecode } } ui.log("---------------"); ui.stopListening(); gb = new GrammarBuilder(speechCommands); g = new Grammar(gb); ui.recognizer.sre.LoadGrammar(g); ui.recognizer.sre.RecognizeAsync(RecognizeMode.Multiple); ui.setStatus(cnt.ToString() + " commands loaded and ready!"); EventHandler handler = grammarLoaded; if (null != handler) { handler(this, EventArgs.Empty); } }
public static void Main(string[] args) { // // the following program produces a parse table for the following grammar // for infix expressions, and appropriately applies operator precedence of // the + - * / operators, otherwise evaluating the leftmost operations first // // S' -> e // e -> i // e -> ( e ) // e -> e * e // e -> e / e // e -> e + e // e -> e - e // // Grammar grammar = new Grammar(); grammar.Tokens = new string[] { "S'", "e", "+", "-", "*", "/", "i", "(", ")" }; grammar.PrecedenceGroups = new PrecedenceGroup[] { new PrecedenceGroup { Derivation = Derivation.None, Productions = new Production[] { //S' -> e new Production { Left = 0, Right = new int[] { 1 } }, //e -> i new Production { Left = 1, Right = new int[] { 6 } }, //e -> ( e ) new Production { Left = 1, Right = new int[] { 7, 1, 8 } } } }, new PrecedenceGroup { Derivation = Derivation.LeftMost, Productions = new Production[] { //e -> e * e new Production { Left = 1, Right = new int[] { 1, 4, 1 } }, //e -> e / e new Production { Left = 1, Right = new int[] { 1, 5, 1 } }, } }, new PrecedenceGroup { //productions are left associative and bind less tightly than * or / Derivation = Derivation.LeftMost, Productions = new Production[] { //e -> e + e new Production { Left = 1, Right = new int[] { 1, 2, 1 } }, //e -> e - e new Production { Left = 1, Right = new int[] { 1, 3, 1 } } } } }; // generate the parse table Parser parser = new Parser(grammar); // write the parse table to the screen Debug.DumpParseTable(parser); Debug.DumpLALRStates(parser); Debug.DumpNonterminals(parser); Debug.DumpTerminals(parser); Debug.DumpLR0States(parser); Debug.DumpLR1Items(parser); }
private void CreateSpeechGrammars() { // Create SemanticResultValue objects that contain activator possibilities SemanticResultValue okayGeorge = new SemanticResultValue("Okay George", "Start Listening"); SemanticResultValue georgeListen = new SemanticResultValue("George Listen", "Start Listening"); SemanticResultValue stopListening = new SemanticResultValue("Stop Listening", "Stop Listening"); // Create Activator 'choices' Choices choicesActivator = new Choices(); choicesActivator.Add(new Choices(new GrammarBuilder[] { okayGeorge, georgeListen, stopListening })); // Build the phrase and add 'choices' GrammarBuilder grammarActivator = new GrammarBuilder(); grammarActivator.Append(new SemanticResultKey("activator", choicesActivator)); // Build a Grammar object from the GrammarBuilder. ActivateGrammar = new Grammar(grammarActivator); // Create SemanticResultValue objects that contain Navigation possibilities SemanticResultValue go = new SemanticResultValue("Go", "Navigate"); SemanticResultValue goTo = new SemanticResultValue("Go to", "Navigate"); SemanticResultValue navigateTo = new SemanticResultValue("Navigate to", "Navigate"); SemanticResultValue menuShop = new SemanticResultValue("Shop", "Shop"); SemanticResultValue menuAccount = new SemanticResultValue("Account", "Account"); SemanticResultValue menuWish_list = new SemanticResultValue("Wish list", "Wishlist"); SemanticResultValue menuWishlist = new SemanticResultValue("Wishlist", "Wishlist"); SemanticResultValue menuSearch = new SemanticResultValue("Search", "Search"); SemanticResultValue menuHome = new SemanticResultValue("Home", "Home"); // Create Navigator 'Choices' Choices choicesNavigatorActivate = new Choices(); choicesNavigatorActivate.Add(new Choices(new GrammarBuilder[] { go, goTo, navigateTo })); Choices choicesNavigation = new Choices(); choicesNavigation.Add(new Choices(new GrammarBuilder[] { menuShop, menuAccount, menuWish_list, menuWishlist, menuSearch, menuHome })); // build the phrasing GrammarBuilder grammarNavigation = new GrammarBuilder(); grammarNavigation.Append(new SemanticResultKey("activator", choicesNavigatorActivate)); grammarNavigation.Append(new SemanticResultKey("where", choicesNavigation)); NavigateGrammar = new Grammar(grammarNavigation); // Create SemanticResultValue objects that contain search possibilities SemanticResultValue search = new SemanticResultValue("Search", "Search"); SemanticResultValue searchFor = new SemanticResultValue("Search for", "Search"); SemanticResultValue searchIn = new SemanticResultValue("Search in", "Search"); // Create SemanticResultValue objects that contain category possibilities SemanticResultValue woman = new SemanticResultValue("woman", "womens"); SemanticResultValue women = new SemanticResultValue("women", "womens"); SemanticResultValue womens = new SemanticResultValue("womens", "womens"); SemanticResultValue female = new SemanticResultValue("female", "womens"); SemanticResultValue male = new SemanticResultValue("male", "mens"); SemanticResultValue man = new SemanticResultValue("man", "mens"); SemanticResultValue men = new SemanticResultValue("men", "mens"); SemanticResultValue mens = new SemanticResultValue("mens", "mens"); // Create Search Choices choicesSearch = new Choices(); choicesSearch.Add(new Choices(new GrammarBuilder[] { search, searchFor, searchIn })); //Create Categories Choices choicesCategories = new Choices(); choicesCategories.Add(new Choices(new GrammarBuilder[] { woman, women, womens, female, male, man, men, mens })); // build category search GrammarBuilder grammarSearchCategories = new GrammarBuilder(); grammarSearchCategories.Append(new SemanticResultKey("activator", choicesSearch)); grammarSearchCategories.Append(new SemanticResultKey("category", choicesCategories)); SearchCatGrammar = new Grammar(grammarSearchCategories); List <SemanticResultValue> arraySubCatValue = new List <SemanticResultValue>(); foreach (Models.Category category in Collector.Categories) { foreach (Models.SubCategory subCategory in category.SubCategories) { arraySubCatValue.Add(new SemanticResultValue(subCategory.Title.Replace("&", "and"), subCategory.Title)); } } Choices choicesSubCategories = new Choices(); foreach (SemanticResultValue semValue in arraySubCatValue) { choicesSubCategories.Add(new Choices(new GrammarBuilder(semValue))); } GrammarBuilder grammarSubCat = new GrammarBuilder(); grammarSubCat.Append(new SemanticResultKey("activator", choicesSearch)); grammarSubCat.Append(new SemanticResultKey("category", choicesCategories)); grammarSubCat.Append(new SemanticResultKey("subcategory", choicesSubCategories)); SearchSubCatGrammar = new Grammar(grammarSubCat); // Create SemanticResultValue objects that contain wishlist possibilities SemanticResultValue addToWishlist = new SemanticResultValue("Add to the wishlist", "Add to Wishlist"); SemanticResultValue addToWishlist2 = new SemanticResultValue("Add to my wishlist", "Add to Wishlist"); SemanticResultValue removeFromWishlist = new SemanticResultValue("Remove from my wishlist", "Remove from Wishlist"); SemanticResultValue add = new SemanticResultValue("add", "Add to Wishlist"); SemanticResultValue remove = new SemanticResultValue("remove", "Remove from Wishlist"); SemanticResultValue removeFromWishlist2 = new SemanticResultValue("Remove from the wishlist", "Remove from Wishlist"); // Create Activator 'choices' Choices choicesWishlist = new Choices(); choicesWishlist.Add(new Choices(new GrammarBuilder[] { addToWishlist, addToWishlist2, removeFromWishlist, removeFromWishlist2 })); // Build the phrase and add 'choices' GrammarBuilder grammarWishlist = new GrammarBuilder(); grammarWishlist.Append(new SemanticResultKey("activator", choicesWishlist)); // Build a Grammar object from the GrammarBuilder. WishListGrammar = new Grammar(grammarWishlist); IsListening = false; }
public GrammarSemanticsMessage(int msgID, Grammar g, IToken offendingToken) : this(msgID, g, offendingToken, null, null) { }
public string Generate(Grammar Grammar, bool Debug) { if (string.IsNullOrEmpty(Grammar.GetTemplatePath())) { return(null); } string generatedtext = File.ReadAllText(Grammar.GetTemplatePath() + templateName); StringBuilder tokens = new StringBuilder(); StringBuilder colors = new StringBuilder(); int colorindex = 1; foreach (TerminalSymbol t in Grammar.GetTerminals()) { if (!t.Attributes.ContainsKey("Color")) { continue; } tokens.AppendLine(Helper.Indent(5) + "Case TokenType." + t.Name + ":"); tokens.AppendLine(Helper.Indent(6) + @"sb.Append(""{{\cf" + colorindex + @" "")"); tokens.AppendLine(Helper.Indent(6) + "Exit Select"); int red = 0; int green = 0; int blue = 0; int len = t.Attributes["Color"].Length; if (len == 1) { if (t.Attributes["Color"][0] is long) { int v = Convert.ToInt32(t.Attributes["Color"][0]); red = (v >> 16) & 255; green = (v >> 8) & 255; blue = v & 255; } } else if (len == 3) { if (t.Attributes["Color"][0] is int || t.Attributes["Color"][0] is long) { red = Convert.ToInt32(t.Attributes["Color"][0]) & 255; } if (t.Attributes["Color"][1] is int || t.Attributes["Color"][1] is long) { green = Convert.ToInt32(t.Attributes["Color"][1]) & 255; } if (t.Attributes["Color"][2] is int || t.Attributes["Color"][2] is long) { blue = Convert.ToInt32(t.Attributes["Color"][2]) & 255; } } colors.Append(String.Format(@"\red{0}\green{1}\blue{2};", red, green, blue)); colorindex++; } generatedtext = generatedtext.Replace(@"<%HightlightTokens%>", tokens.ToString()); generatedtext = generatedtext.Replace(@"<%RtfColorPalette%>", colors.ToString()); if (Debug) { generatedtext = generatedtext.Replace(@"<%Namespace%>", "TinyPG.Debug"); } else { generatedtext = generatedtext.Replace(@"<%Namespace%>", Grammar.Directives["TinyPG"]["Namespace"]); } return(generatedtext); }
public LR0(Grammar grammar) : base(grammar) { automaton = CreateAutomaton(grammar); }
public void button1_Click(object sender, EventArgs e) { button1.Enabled = false; button1.Text = "God Called"; label2.Text = "The god is listening..."; label2.ForeColor = Color.Red; SpeechRecognitionEngine GodListener = new SpeechRecognitionEngine(); Choices GodList = new Choices(); GodList.Add(new string[] { "Make toast", "Make me toast", "Make me some toast", "Make me immortal", "Make rain", "call rain", "call the rain", "make it rain", "wink out of existence", "begone", "go now", "wink yourself out of existence" }); GrammarBuilder gb = new GrammarBuilder(); gb.Append(GodList); Grammar GodGrammar = new Grammar(gb); GodListener.MaxAlternates = 2; try { GodListener.RequestRecognizerUpdate(); GodListener.LoadGrammar(GodGrammar); GodListener.SetInputToDefaultAudioDevice(); GodListener.SpeechRecognized += GodListener_SpeechRecognized; GodListener.AudioStateChanged += GodListener_AudioStateChanged; GodListener.AudioLevelUpdated += GodListener_AudioLevelUpdated; GodListener.RecognizeAsync(RecognizeMode.Multiple); } catch { return; } }