Example #1
0
    def testPreTests(self):
        # make sure that NatSpeak is loaded into memory
        testForException = self.doTestForException
        # these function should all fail before natConnect is called
        testForException(natlink.NatError, "natlink.playString('')")
        testForException(natlink.NatError, "natlink.getCurrentModule()")
        testForException(natlink.NatError, "natlink.getCurrentUser()")
        testForException(natlink.NatError, "natlink.getMicState()")
        testForException(natlink.NatError, "natlink.setMicState('off')")
        testForException(natlink.NatError, "natlink.execScript('')")
        testForException(natlink.NatError, "natlink.recognitionMimic('')")
        testForException(natlink.NatError, "natlink.playEvents([])")
        testForException(natlink.NatError, "natlink.inputFromFile('test.wav')")
        testForException(natlink.NatError, "natlink.setTimerCallback(None)")
        testForException(natlink.NatError, "natlink.getTrainingMode()")
        testForException(natlink.NatError,
                         "natlink.startTraining('calibrate')")
        testForException(natlink.NatError, "natlink.finishTraining()")
        testForException(natlink.NatError, "natlink.getAllUsers()")
        testForException(natlink.NatError, "natlink.openUser('testUser')")
        testForException(natlink.NatError, "natlink.saveUser()")
        testForException(natlink.NatError, "natlink.getUserTraining()")
        testForException(natlink.NatError, "natlink.waitForSpeech(0)")
        testForException(natlink.NatError, "natlink.GramObj().load('')")
        testForException(natlink.NatError, "natlink.DictObj()")

        # these functions should all work before natConnect is called
        natlink.displayText('', 0)
        natlink.getClipboard()
        natlink.getCallbackDepth()
        natlink.getCursorPos()
        natlink.getScreenSize()
        natlink.setBeginCallback(None)
        natlink.setChangeCallback(None)
        natlink.isNatSpeakRunning()
Example #2
0
    def testPreTests(self):
        # make sure that NatSpeak is loaded into memory
        testForException = self.doTestForException
        # these function should all fail before natConnect is called
        testForException( natlink.NatError, "natlink.playString('')" )
        testForException( natlink.NatError, "natlink.getCurrentModule()" )
        testForException( natlink.NatError, "natlink.getCurrentUser()" )
        testForException( natlink.NatError, "natlink.getMicState()" )
        testForException( natlink.NatError, "natlink.setMicState('off')" )
        testForException( natlink.NatError, "natlink.execScript('')" )
        testForException( natlink.NatError, "natlink.recognitionMimic('')" )
        testForException( natlink.NatError, "natlink.playEvents([])" )
        testForException( natlink.NatError, "natlink.inputFromFile('test.wav')" )
        testForException( natlink.NatError, "natlink.setTimerCallback(None)" )
        testForException( natlink.NatError, "natlink.getTrainingMode()" )
        testForException( natlink.NatError, "natlink.startTraining('calibrate')" )
        testForException( natlink.NatError, "natlink.finishTraining()" )
        testForException( natlink.NatError, "natlink.getAllUsers()" )
        testForException( natlink.NatError, "natlink.openUser('testUser')" )
        testForException( natlink.NatError, "natlink.saveUser()" )
        testForException( natlink.NatError, "natlink.getUserTraining()" )
        testForException( natlink.NatError, "natlink.waitForSpeech(0)" )
        testForException( natlink.NatError, "natlink.GramObj().load('')" )
        testForException( natlink.NatError, "natlink.DictObj()" )

        # these functions should all work before natConnect is called
        natlink.displayText('',0)
        natlink.getClipboard()
        natlink.getCallbackDepth()
        natlink.getCursorPos()
        natlink.getScreenSize()
        natlink.setBeginCallback(None)
        natlink.setChangeCallback(None)
        natlink.isNatSpeakRunning()
Example #3
0
def is_engine_available():
    """ Check whether Natlink is available. """
    global _engine
    if _engine:
        return True

    # Attempt to import natlink.
    try:
        import natlink
    except ImportError as e:
        _log.info("Failed to import natlink package: %s" % (e, ))
        return False
    except Exception as e:
        _log.exception("Exception during import of natlink package: %s" %
                       (e, ))
        return False

    try:
        if natlink.isNatSpeakRunning():
            return True
        else:
            _log.info("Natlink is available but NaturallySpeaking is not"
                      " running.")
            return False
    except Exception as e:
        _log.exception("Exception during natlink.isNatSpeakRunning(): %s" %
                       (e, ))
        return False
Example #4
0
def run():
    if not natlink.isNatSpeakRunning():
        raise TranscribeError,'NatSpeak should be running before transcribing files'
    try:
        natlink.natConnect()
        doTranscription()
    finally:
        natlink.natDisconnect()
Example #5
0
 def setUp(self):
     if not natlink.isNatSpeakRunning():
         raise TestError, 'NatSpeak is not currently running'
     if not self.connected:
         self.connect()
         self.user = natlink.getCurrentUser()[0]
         self.setMicState = "off"
         self.connected = 1
    def is_available(cls):
        """ Check whether Natlink is available. """
        try:
            import natlink
        except ImportError:
            return False

        if natlink.isNatSpeakRunning():
            return True
        else:
            return False
Example #7
0
    def is_available(cls):
        """ Check whether Natlink is available. """
        try:
            import natlink
        except ImportError:
            return False

        if natlink.isNatSpeakRunning():
            return True
        else:
            return False
Example #8
0
def is_engine_available(**kwargs):
    """
        Check whether Natlink is available.

        :param \\**kwargs: optional keyword arguments passed through to the
            engine for engine-specific configuration.
    """
    global _engine
    if _engine:
        return True

    platform_name = platform.system()
    if platform_name != 'Windows':
        _log.warning("%s is not supported by the Natlink engine backend",
                     platform_name)
        return False

    if struct.calcsize("P") == 8:  # 64-bit
        _log.warning("The python environment is 64-bit. Natlink requires a "
                     "32-bit python environment")
        return False

    # Attempt to import natlink.
    try:
        import natlink
    except ImportError as e:
        _log.warning(
            "Requested engine 'natlink' is not available: Natlink "
            "is not installed: %s", e)
        return False
    except Exception as e:
        _log.exception("Exception during import of natlink package: " "%s", e)
        return False

    try:
        if natlink.isNatSpeakRunning():
            return True
        else:
            _log.warning("Natlink is available but NaturallySpeaking is not"
                         " running.")
            return False
    except Exception as e:
        _log.exception("Exception during natlink.isNatSpeakRunning(): "
                       "%s", e)
        return False
Example #9
0
    def start_natlink(doNatConnect=None):
        """do the startup of the python macros system
        """
        global userDirectory, DNSVersion, baseDirectory, WindowsVersion, unimacroDirectory
        try:
            # compute the directory where this module came from
            if not natlink.isNatSpeakRunning():
                print 'start Dragon first, the rerun the script natlinkmain...'
                time.sleep(10)
                return

            if doNatConnect:
                natlink.natConnect(
                    1)  # 0 or 1, should not be needed when automatic startup

            #print "\n".join(["%s=%s" % (k,v) for k, v in sys.modules ])
            #print "\n".join(sys.modules.keys())
            for modname in ['natlink', 'natlinkmain']:
                try:
                    coreDirectory = os.path.split(
                        sys.modules[modname].__dict__['__file__'])[0]
                except KeyError:
                    pass
                else:
                    break

            if debugLoad: print "NatLink pyd dir " + coreDirectory
            baseDirectory = os.path.normpath(
                os.path.abspath(os.path.join(coreDirectory, "..")))
            if not baseDirectory in sys.path:
                sys.path.insert(0, baseDirectory)
                if debugLoad:
                    print 'insert baseDirectory: %s to sys.path!' % baseDirectory
            if debugLoad: print "NatLink base dir" + baseDirectory

            # get the current user information from the NatLink module
            userDirectory = status.getUserDirectory()
            if userDirectory:
                if not userDirectory in sys.path:
                    sys.path.insert(0, userDirectory)
                    if debugLoad:
                        print 'insert userDirectory: %s to sys.path!' % userDirectory
                else:
                    if debugLoad:
                        print 'userDirectory: %s' % userDirectory
            else:
                if debugLoad:
                    print 'no userDirectory'

            # for unimacro, in order to reach unimacro files to be imported:
            unimacroDirectory = status.getUnimacroDirectory()
            if unimacroDirectory:
                if status.UnimacroIsEnabled():
                    if not unimacroDirectory in sys.path:
                        sys.path.insert(0, unimacroDirectory)
                        if debugLoad:
                            print 'insert unimacroDirectory: %s to sys.path!' % unimacroDirectory
                    else:
                        if debugLoad:
                            print 'unimacroDirectory: %s' % unimacroDirectory
                else:
                    if debugLoad:
                        print 'Unimacro not enabled'

            else:
                if debugLoad:
                    print 'no unimacroDirectory'

            # setting searchImportDirs:
            setSearchImportDirs()

            # get invariant variables:
            DNSVersion = status.getDNSVersion()
            WindowsVersion = status.getWindowsVersion()

            # init things identical to when user changes:
            #   [MDL: this calls findAndLoadFiles()!]
            changeCallback('user', natlink.getCurrentUser())

            ##    BaseModel, BaseTopic = status.getBaseModelBaseTopic()

            # load all global files in user directory and current directory
            findAndLoadFiles()

            # initialize our callbacks
            natlink.setBeginCallback(beginCallback)
            natlink.setChangeCallback(changeCallback)

            print 'natlinkmain started from %s:\n  NatLink version: %s\n  DNS version: %s\n  Python version: %s\n  Windows Version: %s\n'% \
                      (status.getCoreDirectory(), status.getInstallVersion(),
                       DNSVersion, status.getPythonVersion(), WindowsVersion)

        except:
            sys.stderr.write('Error initializing natlinkmain\n')
            traceback.print_exc()

        if debugLoad:
            print "userDirectory: %s\nbaseDirectory: %s\nunimacroDirectory: %s\n" % (
                userDirectory, baseDirectory, unimacroDirectory)
            print "natlinkmain imported-----------------------------------"
        elif natlinkmainPrintsAtEnd:
            if status.UnimacroIsEnabled():
                print 'Unimacro enabled, user directory: %s' % status.getUnimacroUserDirectory(
                )
            if status.VocolaIsEnabled():
                print 'Vocola enabled, user directory: %s' % status.getVocolaUserDirectory(
                )
            if userDirectory:
                print "User defined macro's (UserDirectory) enabled: %s" % userDirectory
            print '-' * 40
        #else:
        #    natlinkLogMessage('natlinkmain started (imported)\n')
        if status.hadWarning:
            print '=' * 30
            print status.getWarningText()
            print '=' * 30
            status.emptyWarning()
Example #10
0
 def setUp(self):
     if not natlink.isNatSpeakRunning():
         raise TestError, 'NatSpeak is not currently running'
     self.connect()
     # remember user and get DragonPad in front:
     self.setMicState = "off"
Example #11
0
 def setUp(self):
     if not natlink.isNatSpeakRunning():
         raise TestError,'NatSpeak is not currently running'
     self.connect()
     # remember user and get DragonPad in front:
     self.setMicState = "off"
Example #12
0
    global _engine
    if _engine:
        return True

    # Attempt to import natlink.
    try:
        import natlink
    except ImportError, e:
        _log.info("Failed to import natlink package: %s" % (e,))
        return False
    except Exception, e:
        _log.exception("Exception during import of natlink package: %s" % (e,))
        return False

    try:
        if natlink.isNatSpeakRunning():
            return True
        else:
            _log.info("Natlink is available but NaturallySpeaking is not"
                      " running.")
            return False
    except Exception, e:
        _log.exception("Exception during natlink.isNatSpeakRunning(): %s" % (e,))
        return False


def get_engine():
    """ Retrieve the Natlink back-end engine object. """
    global _engine
    if not _engine:
        from .engine import NatlinkEngine
Example #13
0
def is_engine_available(**kwargs):
    """
        Check whether Natlink is available.

        :param \\**kwargs: optional keyword arguments passed through to the
            engine for engine-specific configuration.
    """
    # pylint: disable=too-many-return-statements
    global _engine
    if _engine:
        return True

    platform_name = platform.system()
    if platform_name != 'Windows':
        _log.warning("%s is not supported by the Natlink engine backend",
                     platform_name)
        return False

    if struct.calcsize("P") == 8:  # 64-bit
        _log.warning("The python environment is 64-bit. Natlink requires a "
                     "32-bit python environment")
        return False

    # Attempt to import natlink.
    try:
        import natlink
    except ImportError as e:
        # Add Natlink's default 'core' directory path to sys.path if
        # necessary.
        coredir_path = r'C:\\NatLink\\NatLink\\MacroSystem\\core'
        pyd_filename = 'natlink.pyd'
        pyd_path = os.path.join(coredir_path, pyd_filename)
        import_failure = True
        if os.path.isdir(coredir_path):
            if not os.path.isfile(pyd_path):
                _log.warning(
                    "Requested engine 'natlink' is not available: "
                    "The %r file is missing from Natlink's core "
                    "directory", pyd_filename)
                return False

            # Add the core directory to the path and try importing again.
            sys.path.append(coredir_path)
            try:
                import natlink
                import_failure = False
            except ImportError:
                pass
        if import_failure:
            _log.warning(
                "Requested engine 'natlink' is not available: "
                "Natlink is not installed: %s", e)
            return False
    except Exception as e:
        _log.exception("Exception during import of natlink package: " "%s", e)
        return False

    try:
        if natlink.isNatSpeakRunning():
            return True
        else:
            _log.warning("Requested engine 'natlink' is not available: "
                         "Dragon NaturallySpeaking is not running")
            return False
    except Exception as e:
        _log.exception("Exception during natlink.isNatSpeakRunning(): "
                       "%s", e)
        return False
Example #14
0
def start_natlink(doNatConnect=None):
    """do the startup of the python macros system
    
    Better not use doNatConnect, but ensure this is done before calling, and with a finally: natlink.natDisconnect() call
    """
    global loadedFiles
    print('--')
    nGrammarsLoaded = len(loadedFiles)
    if nGrammarsLoaded:
        if debugLoad:
            print("unload everything, %s grammars loaded"% nGrammarsLoaded)
        unloadEverything()
    else:
        if debugLoad:
            print("no grammars loaded yet")

    if natlinkmainPrintsAtStart:
        print('-- natlinkmain starting...')

    if not natlink.isNatSpeakRunning():
        print('start Dragon first, then rerun the script natlinkmain...')
        time.sleep(10)
        return

    if not doNatConnect is None:
        if doNatConnect:
            print('start_natlink, do natConnect with option 1, threading')
            natlink.natConnect(1) # 0 or 1, should not be needed when automatic startup
        else:
            print('start_natlink, do natConnect with option 0, no threading')
            natlink.natConnect(0) # 0 or 1, should not be needed when automatic startup

        print("----natlink.natConnect succeeded")

    # for modname in ['natlink', 'natlinkmain']:
    if not baseDirectory in sys.path:
        sys.path.insert(0,baseDirectory)
        if debugLoad:
            print('insert baseDirectory: %s to sys.path!'% baseDirectory)
    if debugLoad: print(("Natlink base dir" + baseDirectory))

    # get the current user information from the Natlink module
    if userDirectory and os.path.isdir(userDirectory):
        if not userDirectory in sys.path:
            sys.path.insert(0,userDirectory)
            if debugLoad:
                print('insert userDirectory: %s to sys.path!'% userDirectory)
        else:
            if debugLoad:
                print('userDirectory: %s'% userDirectory)
    else:
        if debugLoad:
            print('no userDirectory')

    # for unimacro, in order to reach unimacro files to be imported:
    if unimacroDirectory and os.path.isdir(unimacroDirectory):
        if status.UnimacroIsEnabled():
            if not unimacroDirectory in sys.path:
                sys.path.insert(0,unimacroDirectory)
                if debugLoad:
                    print('insert unimacroDirectory: %s to sys.path!'% unimacroDirectory)
            else:
                if debugLoad:
                    print('unimacroDirectory: %s'% unimacroDirectory)
        else:
            if debugLoad:
                print('Unimacro not enabled')

    else:
        if debugLoad:
            print('no unimacroDirectory')

    # setting searchImportDirs, also insert at front of sys.path if not in the list yet.
    setSearchImportDirs()


##    BaseModel, BaseTopic = status.getBaseModelBaseTopic()

    # load all global files in user directory and current directory
    # findAndLoadFiles()  

    # initialize our callbacks
    natlink.setBeginCallback(beginCallback)
    natlink.setChangeCallback(changeCallback)

    # init things identical to when user changes:
    changeCallback('user', natlink.getCurrentUser())

    print(('natlinkmain started from %s:\n  Natlink version: %s\n  DNS version: %s\n  Python version: %s\n  Windows Version: %s'% \
              (status.getCoreDirectory(), status.getInstallVersion(),
               DNSVersion, status.getPythonVersion(), windowsVersion, )))


    if debugLoad:
        print("userDirectory: %s\nbaseDirectory: %s\nunimacroDirectory: %s\n"% (userDirectory, baseDirectory, unimacroDirectory))
        print("loadedFiles: %s"% loadedFiles)
        print("natlinkmain imported-----------------------------------")
    elif natlinkmainPrintsAtEnd:
        if status.UnimacroIsEnabled():
            print('Unimacro enabled, UnimacroUserDirectory:\n  %s'% status.getUnimacroUserDirectory())
        if status.VocolaIsEnabled():
            print('Vocola enabled, VocolaUserDirectory:\n  %s'% status.getVocolaUserDirectory())
        if userDirectory:
            print("User defined macro's enabled, UserDirectory:\n  %s"% userDirectory)
        print('-'*40)
    #else:
    #    natlinkLogMessage('natlinkmain started (imported)\n')
    if status.hadWarning:
        print('='*30)
        print(status.getWarningText())
        print('='*30)
        status.emptyWarning()
Example #15
0
 def setUp(self):
     if not natlink.isNatSpeakRunning():
         raise TestError('NatSpeak is not currently running')
Example #16
0
    global _engine
    if _engine:
        return True

    # Attempt to import natlink.
    try:
        import natlink
    except ImportError, e:
        _log.info("Failed to import natlink package: %s" % (e,))
        return False
    except Exception, e:
        _log.exception("Exception during import of natlink package: %s" % (e,))
        return False

    try:
        if natlink.isNatSpeakRunning():
            return True
        else:
            _log.info("Natlink is available but NaturallySpeaking is not"
                      " running.")
            return False
    except Exception, e:
        _log.exception("Exception during natlink.isNatSpeakRunning(): %s" % (e,))
        return False


def get_engine():
    """ Retrieve the Natlink back-end engine object. """
    global _engine
    if not _engine:
        from .engine import NatlinkEngine
Example #17
0
 def setUp(self):
     if not natlink.isNatSpeakRunning():
         raise TestError('NatSpeak is not currently running')
Example #18
0
    def _execute(self, data=None):
        self._log.info("Executing: %s", self.command)

        # Suppress showing the new CMD.exe window on Windows.
        startupinfo = None
        if os.name == 'nt' and self._hide_window:
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

        # Pre-process self.command before passing it to subprocess.Popen.
        command = self.command
        if isinstance(command, string_types):
            # Split command strings using shlex before passing it to Popen.
            # Use POSIX mode only if on a POSIX platform.
            command = shlex.split(command, posix=os.name == "posix")
        try:
            self._proc = subprocess.Popen(command,
                                          stdout=subprocess.PIPE,
                                          stderr=subprocess.STDOUT,
                                          stdin=subprocess.PIPE,
                                          startupinfo=startupinfo)
        except Exception as e:
            self._log.exception("Exception from starting subprocess %s: "
                                "%s", self._str, e)
            return False

        # Call process_command either synchronously or asynchronously.
        def call():
            try:
                if self._process_command:
                    process_func = self._process_command
                else:
                    process_func = self.process_command
                process_func(self._proc)
                return_code = self._proc.wait()
                if return_code != 0:
                    self._log.error("Command %s failed with return code "
                                    "%d", self._str, return_code)
                    return False
                return True
            except Exception as e:
                self._log.exception("Exception processing command %s: %s",
                                    self._str, e)
                return False
            finally:
                self._proc = None

        if self.synchronous:
            return call()

        # Execute in a new daemonized thread so that the command cannot
        # stop the SR engine from exiting.
        thread = threading.Thread(target=call)
        thread.setDaemon(True)
        thread.start()

        # Start a timer if using natlink to allow asynchronous execution
        # to work.
        try:
            import natlink
            if not natlink.isNatSpeakRunning():
                return True
        except ImportError:
            return True
        engine = get_engine()
        if engine.name == "natlink":

            def natlink_timer():
                # Let the thread run for a bit.
                if thread.is_alive():
                    thread.join(0.002)
                else:
                    timer.stop()

            try:
                timer = engine.create_timer(natlink_timer, 0.02)
            except natlink.NatError:
                # Ignore errors if natConnect() hasn't been called.
                pass
        return True
Example #19
0
def start_natlink(doNatConnect=None):
    """do the startup of the python macros system
    """
    global userDirectory, DNSVersion, baseDirectory, WindowsVersion
    try:
        # compute the directory where this module came from
        if not natlink.isNatSpeakRunning():
            print 'start Dragon first, the rerun the script natlinkmain...'
            time.sleep(10)
            return

        if doNatConnect:
            natlink.natConnect(1) # 0 or 1, should not be needed when automatic startup

        #print "\n".join(["%s=%s" % (k,v) for k, v in sys.modules ])
        #print "\n".join(sys.modules.keys())
        for modname in ['natlink', 'natlinkmain']:
            try:
                coreDirectory = os.path.split(
                   sys.modules[modname].__dict__['__file__'])[0]
            except KeyError:
                pass
            else:
                break

        if debugLoad: print "NatLink pyd dir " + coreDirectory
        baseDirectory = os.path.normpath(os.path.abspath(os.path.join(coreDirectory,"..")))
        if debugLoad: print "NatLink base dir" + baseDirectory
        
        # get the current user information from the NatLink module
        userDirectory = status.getUserDirectory()
        # for unimacro, in order to reach unimacro files to be imported:
        if userDirectory and os.path.isdir(userDirectory) and not userDirectory in sys.path:
            if debugLoad:
                print 'insert userDirectory: %s to sys.path!'% userDirectory
            sys.path.insert(0,userDirectory)
    
        # setting searchImportDirs:
        setSearchImportDirs()
    
        # get invariant variables:
        DNSVersion = status.getDNSVersion()
        WindowsVersion = status.getWindowsVersion()
        
        # init things identical to when user changes:
        changeCallback('user', natlink.getCurrentUser())
    
    ##    BaseModel, BaseTopic = status.getBaseModelBaseTopic()
        print 'Starting natlinkmain from %s:\n  NatLink version: %s\n  DNS version: %s\n  Python version: %s\n  Windows Version: %s\n'% \
                  (status.getCoreDirectory(), status.getInstallVersion(),
                   DNSVersion, status.getPythonVersion(), WindowsVersion)
            
        # load all global files in user directory and current directory
        findAndLoadFiles()
    
        # initialize our callbacks
        natlink.setBeginCallback(beginCallback)
        natlink.setChangeCallback(changeCallback)
    
    except:
        sys.stderr.write( 'Error initializing natlinkmain\n' )
        traceback.print_exc()
    
    if debugLoad:
        print "userDirectory: %s\nbaseDirectory: %s"% (userDirectory, baseDirectory)
        print "natlinkmain imported-----------------------------------"
    elif natlinkmainPrintsAtEnd:
        print 'natlinkmain started (imported)\n'
    else:
        natlinkLogMessage('natlinkmain started (imported)\n')
    if status.hadWarning:
        print '='*30
        print status.getWarningText()
        print '='*30
        status.emptyWarning()