Ejemplo n.º 1
0
        public void SpechRecog()
        {
            if (sre == null)
            {
                sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("ru-RU"));
            }
            string grammarPath = @"C:\Users\Morfa\Diplom\WindowsFormsApp1\WindowsFormsApp1\";
            //Компилируем наше грамматическое правило в файл Commands.cfg
            FileStream fs = new FileStream(grammarPath + "Commands.cfg", FileMode.Create);

            SrgsGrammarCompiler.Compile(grammarPath + "Comands.xml", (Stream)fs);
            fs.Close();

            Grammar gr = new Grammar(grammarPath + "Commands.cfg", "Команды");

            //Загружаем скомпилированный файл грамматики
            sre.LoadGrammar(gr);

            //Подписываемся на событие распознавания
            sre.SpeechRecognized += new EventHandler <SpeechRecognizedEventArgs>(sre_SpeechRecognized);

            sre.SetInputToDefaultAudioDevice();

            //Запускаем асинхронно распознаватель
            sre.RecognizeAsync(RecognizeMode.Multiple);
        }
Ejemplo n.º 2
0
        static Grammar LoadGrammar(string grammarPathString, bool forceCompile)
        {
            if (grammarPathString == null)
            {
                return(null);
            }

            string compiledGrammarPathString;
            string grammarExtension = Path.GetExtension(grammarPathString);

            if (grammarExtension.Equals(".grxml", StringComparison.OrdinalIgnoreCase))
            {
                compiledGrammarPathString = Path.ChangeExtension(grammarPathString, "cfg");
            }
            else if (grammarExtension.Equals(".cfg", StringComparison.OrdinalIgnoreCase))
            {
                compiledGrammarPathString = grammarPathString;
            }
            else
            {
                throw new FormatException("Grammar file format is unsupported: " + grammarExtension);
            }

            // skip cpmpilation if "cfg" grammar already exists
            if (forceCompile || !File.Exists(compiledGrammarPathString))
            {
                FileStream fs   = new FileStream(compiledGrammarPathString, FileMode.Create);
                var        srgs = new SrgsDocument(grammarPathString);
                SrgsGrammarCompiler.Compile(srgs, fs);
                fs.Close();
            }

            return(new Grammar(compiledGrammarPathString));
        }
Ejemplo n.º 3
0
 private static MemoryStream CombineCfg(string rule, Stream stream, SrgsRule[] extraRules)
 {
     using (MemoryStream memoryStream = new MemoryStream())
     {
         SrgsDocument srgsDocument = new SrgsDocument();
         srgsDocument.TagFormat = SrgsTagFormat.KeyValuePairs;
         foreach (SrgsRule srgsRule in extraRules)
         {
             srgsDocument.Rules.Add(srgsRule);
         }
         SrgsGrammarCompiler.Compile(srgsDocument, memoryStream);
         using (StreamMarshaler streamHelper = new StreamMarshaler(stream))
         {
             long    position = stream.Position;
             Backend org      = new Backend(streamHelper);
             stream.Position       = position;
             memoryStream.Position = 0L;
             MemoryStream memoryStream2 = new MemoryStream();
             using (StreamMarshaler streamHelper2 = new StreamMarshaler(memoryStream))
             {
                 Backend extra   = new Backend(streamHelper2);
                 Backend backend = Backend.CombineGrammar(rule, org, extra);
                 using (StreamMarshaler streamBuffer = new StreamMarshaler(memoryStream2))
                 {
                     backend.Commit(streamBuffer);
                     memoryStream2.Position = 0L;
                     return(memoryStream2);
                 }
             }
         }
     }
 }
Ejemplo n.º 4
0
        private void InitSpeach()
        {
            //Создаем распознаватель с русской локализацией
            SpeechRecognitionEngine sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("ru-RU"));

            string grammarPath = @"d:\test\";
            //Компилируем наше грамматическое правило в файл Маршруты.cfg
            FileStream fs = new FileStream(grammarPath + "Маршруты.cfg", FileMode.Create);

            SrgsGrammarCompiler.Compile(grammarPath + "Маршруты.grxml", (Stream)fs);
            fs.Close();

            Grammar gr = new Grammar(grammarPath + " Маршруты.cfg", "Маршруты");

            //Загружаем скомпилированный файл грамматики
            sre.LoadGrammar(gr);

            //Подписываемся на событие распознавания
            //sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);

            //Пусть голос поступает с устройства по умолчанию
            sre.SetInputToDefaultAudioDevice();

            //Запускаем асинхронно распознаватель
            sre.RecognizeAsync(RecognizeMode.Multiple);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Compile the given grammar to a file
        /// </summary>
        /// <param name="srgDoc">The document to be complied into cfg grammar file</param>
        /// <param name="cfgPath">The full path of the cfg file that will be save to</param>
        public static void CompileGrammarToFile(SrgsDocument srgDoc, string cfgPath)
        {
            FileStream fs = new FileStream(cfgPath, FileMode.Create);

            SrgsGrammarCompiler.Compile(srgDoc, (Stream)fs);
            fs.Close();
        }
Ejemplo n.º 6
0
        public void GrammarCompile(string xml_grammar, string cfg_grammar)
        {
            FileStream fs     = new FileStream(cfg_grammar, FileMode.Create);
            XmlReader  reader = XmlReader.Create(xml_grammar);

            SrgsGrammarCompiler.Compile(reader, (Stream)fs);
            fs.Close();
        }
Ejemplo n.º 7
0
        public void CompileStronglyTypedGrammarToDllFromPath()
        {
            SrgsDocument srgsDoc = CreateSrgsDocument();

            string temp = GetTestFilePath();

            // Cannot compile to assemblies on .NET Core
            Assert.Throws <PlatformNotSupportedException>(() => SrgsGrammarCompiler.CompileClassLibrary(srgsDoc, temp, new string[0], keyFile: null));
        }
Ejemplo n.º 8
0
        public void CompileStronglyTypedGrammarToCfg()
        {
            SrgsDocument srgsDoc = CreateSrgsDocument();

            using var ms = new MemoryStream();
            SrgsGrammarCompiler.Compile(srgsDoc, ms);

            Assert.True(ms.Position > 0);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Returns a stream object for a grammar.
        /// </summary>
        private MemoryStream LoadCfg(bool isImportedGrammar, bool stgInit)
        {
            // No parameters to the constructors
            Uri          uriGrammar = Uri;
            MemoryStream stream     = new();

            if (uriGrammar != null)
            {
                throw new PlatformNotSupportedException();
            }
            else if (_srgsDocument != null)
            {
                // If srgs, compile to a stream
                SrgsGrammarCompiler.Compile(_srgsDocument, stream);
                if (_baseUri == null && _srgsDocument.BaseUri != null)
                {
                    // If we loaded the SrgsDocument from a file then that should be used as the base path.
                    // But it should not override any baseUri supplied directly to the Grammar constructor or in the xmlBase attribute in the xml.
                    _baseUri = _srgsDocument.BaseUri;

                    // So the priority order for getting the base path is:
                    // 1. The xml:base attribute in the xml.
                    // 2. The baseUri passed to the Grammar constructor.
                    // 3. The path the xml was originally loaded from.
                }
            }
            else if (_grammarBuilder != null)
            {
                // If GrammarBuilder, compile to a stream
                _grammarBuilder.Compile(stream);
            }
            else
            {
                // If stream, load
                SrgsGrammarCompiler.CompileXmlOrCopyCfg(_appStream, stream, null);
            }

            stream.Position = 0;

            // Update the rule name
            _ruleName = CheckRuleName(stream, _ruleName, isImportedGrammar, stgInit, out _sapi53Only, out _semanticTag);

            // Create an app domain for the grammar code if any
            CreateSandbox(stream);

            stream.Position = 0;
            return(stream);
        }
Ejemplo n.º 10
0
        public void CompileStronglyTypedGrammarFromFileToCfg()
        {
            SrgsDocument srgsDoc = CreateSrgsDocument();

            string temp = GetTestFilePath();

            using (XmlWriter writer = XmlWriter.Create(temp))
            {
                srgsDoc.WriteSrgs(writer);
            }

            using var ms = new MemoryStream();

            SrgsGrammarCompiler.Compile(temp, ms);

            Assert.True(ms.Position > 0);
        }
Ejemplo n.º 11
0
        public void InitializeRecognizer()
        {
            recognizer = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US"));
            string            xmlGrammar = Environment.CurrentDirectory + "\\grammar.grxml";
            string            cfgGrammar = Environment.CurrentDirectory + "grammar.cfg";
            FileStream        fs         = new FileStream(cfgGrammar, FileMode.Create);
            XmlReaderSettings settings   = new XmlReaderSettings();

            settings.DtdProcessing = DtdProcessing.Parse;
            XmlReader reader = XmlReader.Create(xmlGrammar, settings);

            SrgsGrammarCompiler.Compile(reader, (Stream)fs);
            fs.Close();
            Grammar g = new Grammar(cfgGrammar, "commands");

            recognizer.LoadGrammar(g);
            recognizer.SpeechRecognized +=
                new EventHandler <SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
            recognizer.SetInputToDefaultAudioDevice();
        }
Ejemplo n.º 12
0
        private MemoryStream LoadCfg(bool isImportedGrammar, bool stgInit)
        {
            Uri          uri          = Uri;
            MemoryStream memoryStream = new MemoryStream();

            if (uri != null)
            {
                string mimeType;
                string localPath;
                using (Stream stream = _resourceLoader.LoadFile(uri, out mimeType, out _baseUri, out localPath))
                {
                    stream.Position = 0L;
                    SrgsGrammarCompiler.CompileXmlOrCopyCfg(stream, memoryStream, uri);
                }
                _resourceLoader.UnloadFile(localPath);
            }
            else if (_srgsDocument != null)
            {
                SrgsGrammarCompiler.Compile(_srgsDocument, memoryStream);
                if (_baseUri == null && _srgsDocument.BaseUri != null)
                {
                    _baseUri = _srgsDocument.BaseUri;
                }
            }
            else if (_grammarBuilder != null)
            {
                _grammarBuilder.Compile(memoryStream);
            }
            else
            {
                SrgsGrammarCompiler.CompileXmlOrCopyCfg(_appStream, memoryStream, null);
            }
            memoryStream.Position = 0L;
            _ruleName             = CheckRuleName(memoryStream, _ruleName, isImportedGrammar, stgInit, out _sapi53Only, out _semanticTag);
            CreateSandbox(memoryStream);
            memoryStream.Position = 0L;
            return(memoryStream);
        }
Ejemplo n.º 13
0
        private void LoadGrammar()
        {
            string grammarPath = @"..\..\Grammars\";
            //Компилируем наше грамматическое правило в файл KeywordsGrammar.cfg
            FileStream fs = new FileStream(grammarPath + "KeywordsGrammar.cfg", FileMode.Create);

            SrgsGrammarCompiler.Compile(grammarPath + "KeywordsGrammar.xml", (Stream)fs);
            fs.Close();
            Grammar KeywordsGrammar = new Grammar(grammarPath + "KeywordsGrammar.cfg", "topLevel");

            KeywordsGrammar.Priority = 3;

            fs = new FileStream(grammarPath + "VariablesGrammar.cfg", FileMode.Create);
            SrgsGrammarCompiler.Compile(grammarPath + "VariablesGrammar.xml", (Stream)fs);
            fs.Close();
            Grammar VariableGrammar = new Grammar(grammarPath + "VariablesGrammar.cfg", "topLevel");

            VariableGrammar.Priority = 0;
            //Загружаем скомпилированный файл грамматики

            sre.LoadGrammar(KeywordsGrammar);
            sre.LoadGrammar(VariableGrammar);
        }
Ejemplo n.º 14
0
        private static MemoryStream CombineCfg(string rule, Stream stream, SrgsRule[] extraRules)
        {
            using (MemoryStream streamExtra = new())
            {
                // Create an SrgsDocument from the set of rules
                SrgsDocument sgrsDocument = new();
                sgrsDocument.TagFormat = SrgsTagFormat.KeyValuePairs;
                foreach (SrgsRule srgsRule in extraRules)
                {
                    sgrsDocument.Rules.Add(srgsRule);
                }

                SrgsGrammarCompiler.Compile(sgrsDocument, streamExtra);

                using (StreamMarshaler streamMarshaler = new(stream))
                {
                    long    endSeekPosition = stream.Position;
                    Backend backend         = new(streamMarshaler);
                    stream.Position = endSeekPosition;

                    streamExtra.Position = 0;
                    MemoryStream streamCombined = new();
                    using (StreamMarshaler streamExtraMarshaler = new(streamExtra))
                    {
                        Backend extra    = new(streamExtraMarshaler);
                        Backend combined = Backend.CombineGrammar(rule, backend, extra);

                        using (StreamMarshaler streamCombinedMarshaler = new(streamCombined))
                        {
                            combined.Commit(streamCombinedMarshaler);
                            streamCombined.Position = 0;
                            return(streamCombined);
                        }
                    }
                }
            }
        }