def DISABLED_test_natlink_timer(self): return callback_occurred = False def callback(): callback_occurred = True ticks = 200 import time import natlink natlink.natConnect() try: natlink.setTimerCallback(callback, ticks) # time.sleep(1) import sys import time import win32gui timeout = time.time() + 3 while time.time() < timeout: print("Luke") sys.stdout.flush() if win32gui.PumpWaitingMessages(): raise RuntimeError("We got an unexpected WM_QUIT message!") time.sleep(1) natlink.setTimerCallback(None, 0) print("callback occurred:", callback_occurred) finally: natlink.natDisconnect()
def delete_words(input): natlink.natConnect(0) try: for line in input.readlines(): delete_word(line.rstrip()) finally: natlink.natDisconnect()
def connect(user_name, mic_state=None, mic_change_callback = None): """Connects to the SR system. **INPUTS** *STR* name of the Natspeak user to open *STR* mic_state -- *'on'* or *'off'*. State to put the mic in after connection. If *None*, then leave mic alone. *FCT* mic_change_callback -- mic_change_callback(*STR* mic_state) (optional) function to be called when the microphone state changes. **OUTPUTS** *none* -- """ global sr_is_connected, vc_user_name, vc_base_model, vc_base_topic global sr_mic_change_callback if not sr_is_connected: trace('sr_interface.connect', 'mic_state=%s, sr_is_connected=%s' % (mic_state, sr_is_connected)) # trace_call_stack('sr_interface.connect') # 1 means use threads -- needed for GUI apps natlink.natConnect(1) sr_is_connected = 1 openUser(user_name) if mic_state: natlink.setMicState(mic_state) if mic_change_callback: set_change_callback(mic_change_callback)
def dump_words(input, include_pronunciations, verbose_level): natlink.natConnect(0) try: for line in input.readlines(): dump_word(line.rstrip(), include_pronunciations, verbose_level) finally: natlink.natDisconnect()
def run(): try: natlink.natConnect(1) TestDialog(MakeDlgTemplate()).DoModal() natlink.natDisconnect() except: natlink.natDisconnect() raise
def run(): if not natlink.isNatSpeakRunning(): raise TranscribeError,'NatSpeak should be running before transcribing files' try: natlink.natConnect() doTranscription() finally: natlink.natDisconnect()
def connect(self): # start with 1 for thread safety when run from pythonwin: print 'connecting' natlink.natConnect(natconnectOption) # next line should be enabled when testing the testNumbersGrammar functions in debug mode: # otherwise disable! print 'connected natlink (Unimacro)' pass
def demodlg (): Title='Train Phrases' p=[('word 1'),('word 2'),('word 3')] dlg=TrainDialog(Title, p, 1) try: natlink.natConnect(1) except: return dlg.DoModal() natlink.natDisconnect()
def demodlg(): Title = 'Train Phrases' p = [('word 1'), ('word 2'), ('word 3')] dlg = TrainDialog(Title, p, 1) try: natlink.natConnect(1) except: return dlg.DoModal() natlink.natDisconnect()
def run(args): fileSpecs, userName, baseModel, baseTopic = parseArgs(args) if not fileSpecs: return try: natlink.natConnect() doTraining(fileSpecs, userName, baseModel, baseTopic) natlink.natDisconnect() except TrainingError, message: natlink.natDisconnect() print '' print 'TrainingError:', message
def run(args): fileSpecs,userName,baseModel,baseTopic = parseArgs(args) if not fileSpecs: return try: natlink.natConnect() doTraining(fileSpecs,userName,baseModel,baseTopic) natlink.natDisconnect() except TrainingError,message: natlink.natDisconnect() print '' print 'TrainingError:',message
def load_words(input): natlink.natConnect(0) try: for line in input.readlines(): fields = parse_word_definition(line) if fields == None: continue written, spoken, properties, pronunciations = fields load_word(written, spoken, properties) finally: natlink.natDisconnect()
def goTrain(self,ToTrain): Title='Train Phrases' Phrases=[] for p in ToTrain: Phrases.append((p)) try: natlink.natConnect(1) except: return MicState=natlink.getMicState() dlg=TrainDialog.TrainDialog(Title,Phrases,MicState) SetMic('off') dlg.DoModal() natlink.natDisconnect()
def goTrain(self, ToTrain): Title = 'Train Phrases' Phrases = [] for p in ToTrain: Phrases.append((p)) try: natlink.natConnect(1) except: return MicState = natlink.getMicState() dlg = TrainDialog.TrainDialog(Title, Phrases, MicState) SetMic('off') dlg.DoModal() natlink.natDisconnect()
def run(): global logFile, natconnectOption logFile = open(logFileName, "w") log("log messages to file: %s" % logFileName) log('starting UnittestMouse') # trick: if you only want one or two tests to perform, change # the test names to her example def tttest.... # and change the word 'test' into 'tttest'... # do not forget to change back and do all the tests when you are done. suite = unittest.makeSuite(UnittestMouse, 'test') ## natconnectOption = 0 # no threading has most chances to pass... log('\nstarting tests with threading: %s\n' % natconnectOption) natlink.natConnect(natconnectOption) result = unittest.TextTestRunner().run(suite) dumpResult(result, logFile=logFile) natlink.natDisconnect() logFile.close()
def connect(user_name, mic_state=None, mic_change_callback=None): """Connects to the SR system. **INPUTS** *STR* name of the Natspeak user to open *STR* mic_state -- *'on'* or *'off'*. State to put the mic in after connection. If *None*, then leave mic alone. *FCT* mic_change_callback -- mic_change_callback(*STR* mic_state) (optional) function to be called when the microphone state changes. **OUTPUTS** *none* -- """ global sr_is_connected, vc_user_name, vc_base_model, vc_base_topic global sr_mic_change_callback, natspeak_version, period_space_after_spoken_form_letter, category_information_in_vocabulary_entries if not sr_is_connected: trace( 'sr_interface.connect', 'mic_state=%s, sr_is_connected=%s' % (mic_state, sr_is_connected)) # trace_call_stack('sr_interface.connect') # 1 means use threads -- needed for GUI apps natlink.natConnect(1) sr_is_connected = 1 openUser(user_name) check_alpha_bravo() # check the exact spelling of military alphabet # return the results in alpha_bravo dict if mic_state: natlink.setMicState(mic_state) if mic_change_callback: set_change_callback(mic_change_callback) natspeak_version = NLstatus.getDNSVersion() if natspeak_version >= 11: period_space_after_spoken_form_letter = ' ' # new in NatSpeak 11 category_information_in_vocabulary_entries = True trace( 'sr_interface.period_space_after_spoken_form_letter', 'natspeak_version: %s, nperiod_space_after_spoken_form_letter: "%s"' % (natspeak_version, period_space_after_spoken_form_letter))
def connect(user_name, mic_state=None, mic_change_callback = None): """Connects to the SR system. **INPUTS** *STR* name of the Natspeak user to open *STR* mic_state -- *'on'* or *'off'*. State to put the mic in after connection. If *None*, then leave mic alone. *FCT* mic_change_callback -- mic_change_callback(*STR* mic_state) (optional) function to be called when the microphone state changes. **OUTPUTS** *none* -- """ global sr_is_connected, vc_user_name, vc_base_model, vc_base_topic global sr_mic_change_callback, natspeak_version, period_space_after_spoken_form_letter, category_information_in_vocabulary_entries if not sr_is_connected: trace('sr_interface.connect', 'mic_state=%s, sr_is_connected=%s' % (mic_state, sr_is_connected)) # trace_call_stack('sr_interface.connect') # 1 means use threads -- needed for GUI apps natlink.natConnect(1) sr_is_connected = 1 openUser(user_name) check_alpha_bravo() # check the exact spelling of military alphabet # return the results in alpha_bravo dict if mic_state: natlink.setMicState(mic_state) if mic_change_callback: set_change_callback(mic_change_callback) natspeak_version = NLstatus.getDNSVersion() if natspeak_version >= 11: period_space_after_spoken_form_letter = ' ' # new in NatSpeak 11 category_information_in_vocabulary_entries = True trace('sr_interface.period_space_after_spoken_form_letter', 'natspeak_version: %s, nperiod_space_after_spoken_form_letter: "%s"'% (natspeak_version, period_space_after_spoken_form_letter))
def main(): # Define required and optional command-line arguments. parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="Script for safely using Natlink's inputFromFile() " "function.\n\n" "This script is intended to be run in a dedicated process in " "order to work around potential page faults." ) parser.add_argument( "file", type=argparse.FileType("r"), help="Name of the wave file to take input from." ) parser.add_argument( "--no-utt-detect", default=False, action="store_true", help="Do not perform utterance detection (i.e. don't split speech " "at pauses) when processing the specified wave file. Use this if " "the file contains only one utterance." ) # Parse command-line arguments. args = parser.parse_args() # Get the filename and uttdetect arguments. f = args.file filename = f.name f.close() # Close the file object created by argparse uttdetect = 0 if args.no_utt_detect else 1 # Instruct Windows to suppress the error reporting window if this script # causes a page fault. win32api.SetErrorMode(win32con.SEM_NOGPFAULTERRORBOX) # Connect to NatSpeak. natlink.natConnect() try: # Process the specified wave file using the specified options. natlink.inputFromFile(filename, 0, [], uttdetect) finally: # Disconnect from NatSpeak. natlink.natDisconnect()
def run(): global s global g natlink.natConnect(1) #if natlink.isNatSpeakRunning() else wait try: print 'MicState:', natlink.getMicState() natlink.setBeginCallback(beginCallback) natlink.setChangeCallback(changeCallback) updateGrammarFromClient() natlink.setMicState('on') natlink.waitForSpeech(300) #data = client_socket.recv(512) #data = raw_input ( "SEND( TYPE q or Q to Quit):" ) except: #print sys.exc_info() print traceback.format_exc() finally: g.unload() natlink.natDisconnect() print 'iDisconnected.' s.close() print 'all closed'
def __enter__(self): natlink.natConnect(True) return self
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()
def run(): natlink.natConnect(1) TestDialog(MakeDlgTemplate()).DoModal() natlink.natDisconnect()
def setUp(self): natlink.natConnect()
def PreDoModal(self): try: natlink.natDisconnect() natlink.natConnect(1) except: pass
def setUp(self): natlink.natConnect() self.folders = __import__("_folders") self.grammarInstance = self.folders.thisGrammar
try: natlink.natDisconnect() natlink.natConnect(1) except: pass def PostDoModal(self): natlink.natDisconnect() def CheckCreateApp(): if sys.modules.has_key("pywin.framework.startup"): App=ServerApp() App.InitInstance() else: print 'does not have "pywin.framework.startup" imported' def demodlg (): dlg=MainWindow() dlg.DoModal() if __name__=='__main__': natlink.natConnect() demodlg() natlink.natDisconnect() #demomodeless() else: CheckCreateApp()
grammars[grammar_name].setExclusive(exclusive) return "done" @rpc def activate(grammar_name, rule_name): grammars[grammar_name].activate(rule_name, 0) return "done" @rpc def deactivate(grammar_name, rule_name): grammars[grammar_name].deactivate(rule_name) return "done" #@rpc #def updateList(grammar_name, list_name, elements): Pass try: print "loading" natlink.natConnect(1) natlink.openUser("Michael") natlink.setMicState("on") natlink.setTimerCallback(drainRequests, 100) natlink.waitForSpeech(0) except Exception as e: print e finally: shutdown()
def connect(self): # start with 1 for thread safety when run from pythonwin: natlink.natConnect(natconnectOption)
return [nl_user_file, fallback_config_file] # choose between .natlink/natlink.ini in home or the fallback_directory: return [join(home, config_sub_dir, natlink_inifile), fallback_config_file] def run() -> None: logger = logging.getLogger('natlink') try: # TODO: remove this hack. As of October 2021, win32api does not load properly, except if # the package pywin32_system32 is explictly put on new dll_directory white-list pywin32_dir = os.path.join(sysconfig.get_path('platlib'), "pywin32_system32") if os.path.isdir(pywin32_dir): os.add_dll_directory(pywin32_dir) config = NatlinkConfig.from_first_found_file(config_locations()) main = NatlinkMain(logger, config) main.setup_logger() main.start() except Exception as exc: print(f'Exception: "{exc}" in loader.run', file=sys.stderr) print(traceback.format_exc()) raise Exception from exc if __name__ == "__main__": natlink.natConnect() run() natlink.natDisconnect()
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()
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()
def setUp(self): natlink.natConnect() self.control = __import__("_control") self.grammarInstance = self.control.utilGrammar