def getWordInfo(word, flag = None): """get word info, if word OK skip if there is no spoken form, or the length > sr_max_word_length """ ## trace('sr_interface.getWordInfo', 'word=%s, rest=%s' % (word, rest)) if not word: trace('sr_interface.getWordInfo', 'getWordInfo, empty word: %s'% word) return #if word.find('.') >= 0: # trace('sr_interface.getWordInfo', 'getWordInfo, word with . in spoken forms, skip: %s'% word) # return if word.endswith('\\'): trace('sr_interface.getWordInfo', 'getWordInfo, empty spoken form: %s'% word) return if len(word) > sr_max_word_length: trace('sr_interface.getWordInfo', 'getWordInfo, (too?) long word (%s):\n%s'% (len(word), word)) return try: if flag is None: answer = natlink.getWordInfo(word) else: answer = natlink.getWordInfo(word, flag) except: # In case the word's spelling is not allowed by # NatSpeak print "WARNING: error trying to get info from vocabulary word '%s'\n" \ "Maybe you forgot to start Dragon NaturallySpeaking before starting VoiceCode?" % repr(word) debug.print_error_info() answer = None return answer
def getWordInfo(word, flag = None): """get word info, if word OK skip if there is no spoken form, or the length > sr_max_word_length """ ## trace('sr_interface.getWordInfo', 'word=%s, rest=%s' % (word, rest)) if not word: trace('sr_interface.getWordInfo', 'getWordInfo, empty word: %s'% word) return if word.endswith('\\'): trace('sr_interface.getWordInfo', 'getWordInfo, empty spoken form: %s'% word) return if len(word) > sr_max_word_length: trace('sr_interface.getWordInfo', 'getWordInfo, (too?) long word (%s):\n%s'% (len(word), word)) return try: if flag is None: answer = natlink.getWordInfo(word) else: answer = natlink.getWordInfo(word, flag) except: # In case the word's spelling is not allowed by # NatSpeak print "WARNING: error trying to get info from vocabulary word '%s'\n" + \ "Maybe you forgot to start Dragon NaturallySpeaking before starting VoiceCode?" % repr(word) # debug.print_call_stack() answer = None return answer
def find_word(word): try: flags = natlink.getWordInfo(word, 2) if flags != None: return 2 flags = natlink.getWordInfo(word, 3) if flags != None: return 1 return 0 except InvalidWord: return -1
def set_word_properties(name, properties): old_flags = natlink.getWordInfo(name, 0) if old_flags == None: raise natlink.UnknownName flags = apply_properties(properties, old_flags) if flags == old_flags: return print "changing properties of '%s' to 0x%x" % (name, flags) print " from 0x%x" % old_flags natlink.setWordInfo(name, flags) if natlink.getWordInfo(name, 0) != flags: print "FAILED! properties remain 0x%x" % natlink.getWordInfo(name, 0)
def dump_word(name, include_pronunciations, verbose_level): try: flags = natlink.getWordInfo(name, 3) pronunciations = natlink.getWordProns(name) except InvalidWord: print >> sys.stderr, "Error: '%s' is an invalid word" % name return if flags == None: print >> sys.stderr, "Error: word '%s' not found" % name return if not include_pronunciations or pronunciations == None: pronunciations = [] dump_properties(flags, verbose_level) if verbose_level > 2: if find_word(name) == 1: print " #" print " # (in backup dictionary only)" written, spoken = parse_word(name) properties = unpack_properties(flags & other_properties) print unparse_word_definition(written, spoken, properties, pronunciations)
def parse_input(self, input): # Not unicode (Python 2) or str (Python 3) if not isinstance(input, text_type): # DNS and Natlink provide recognized words as "Windows-1252" # encoded strings. Here we convert them to Unicode for internal # processing. input = text_type(input).encode("windows-1252") # The written and spoken forms of a word are separated by a "\" # character. index = input.rfind("\\") if index == -1: # Input doesn't contain a backslash, so written and spoken forms # are the same as the input. written = input spoken = input else: # Input contains one or more backslashes, so written and spoken # forms are separated by the last backslash. written = input[:index] spoken = input[index+1:] info = natlink.getWordInfo(input.encode("windows-1252")) word_flags = self.create_word_flags(info) word = Word(written, spoken, word_flags) self._log.debug("Parsed input {0!r} -> {1}".format(input, word)) # print ("Parsed input {0!r} -> {1}".format(input, word)) return word
def gotResults_inoops2(self, words, fullResults): if self.lastResObj: fstring = '' if self.hasCommon(words, 'Cancel'): natqh.Wait() self.cancelMode() natqh.returnFromMessagesWindow() return fNum = string.atoi(words[-1]) if fNum in FORMATS.keys(): fstring = FORMATS[fNum] else: print 'invalid paramter choosen: %s' % ` words ` fstring = '' if fstring and self.newWord: oldFormat = natlink.getWordInfo(self.newWord) if fstring == oldFormat: print 'format of %s is already: %x' % (self.newWord, fstring) else: print 'formatting word: %s from hex %x to hex: %x' % ( self.newWord, oldFormat, fstring) natlink.setWordInfo(self.newWord, fstring) self.newWord = "" time.sleep(1.0) self.cancelMode() natqh.returnFromMessagesWindow()
def getWordInfo10(word): """old getWordInfo function, extracts the word flags from the word properties and convert to a tuple of values """ wordInfo = natlink.getWordInfo(word) wordFlags = wordInfoToFlags(wordInfo) #print 'wordFlags of %s: %s'% (word, wordFlags) return wordFlags
def make_active_word(name, default_word_flags): flags = natlink.getWordInfo(name, 0) if flags != None: return # already an active word flags = natlink.getWordInfo(name, 1) if flags != None: default_word_flags = flags # currently in backup dictionary print "promoting '%s' from backup to active dictionary" % name else: default_word_flags |= USER_ADDED # new word, added by user print "adding new user word '%s'" % name if natlink.addWord(name, default_word_flags) == 1: return currentProns = natlink.getWordProns(name) natlink.addWord(name, default_word_flags, currentProns[0])
def make_active_word(name, default_word_flags): flags = natlink.getWordInfo(name, 0) if flags != None: return # already an active word flags = natlink.getWordInfo(name, 3) if flags != None: default_word_flags = flags # currently in backup dictionary print "promoting '%s' from backup to active dictionary" % name else: default_word_flags |= USER_ADDED # new word, added by user print "adding new user word '%s'" % name try: if natlink.addWord(name, default_word_flags) == 1: return except Exception, e: print " FAILED: " + type(e).__name__ + ": " + str(e) return
def detect_parser_class(self): engine = dragonfly.engines.get_engine() word = self.words_with_info.get(engine.language, ".\\dot") if PY2: info = natlink.getWordInfo(word.encode("windows-1252")) else: info = natlink.getWordInfo(word) if info == None: parser_class = WordParserDns11 else: parser_class = WordParserDns10 parser_class_string = parser_class.__name__ if info == None: info_string = "None" else: info_string = "0x" + format(info, "08x") self._log.info("Selected word parser class {0} because" " natlink.getWordInfo({1!r}) returned {2}".format( parser_class_string, word, info_string)) return parser_class
def _difficult_to_type(name): global STRICT_PARSER found_something_difficult_to_type = False capitals_changed_to_underscores = STRICT_PARSER.sub(r'_\1', name).lower() broken_by_underscores = capitals_changed_to_underscores.split("_") for name_piece in broken_by_underscores: if not name_piece == "" and len(name_piece) > 1: dragon_check = natlink.getWordInfo(name_piece, 7) if dragon_check is None: # only add letter combinations that Dragon doesn't recognize as words found_something_difficult_to_type = True break return found_something_difficult_to_type
def _difficult_to_type(name): global STRICT_PARSER found_something_difficult_to_type = False capitals_changed_to_underscores = STRICT_PARSER.sub(r'_\1', name).lower() broken_by_underscores = capitals_changed_to_underscores.split("_") for name_piece in broken_by_underscores: if not name_piece == "" and len(name_piece) > 1: dragon_check = natlink.getWordInfo(name_piece, 7) if dragon_check == None: # only add letter combinations that Dragon doesn't recognize as words found_something_difficult_to_type = True break return found_something_difficult_to_type
def __init__(self, word): if word in self._replacements: word, self._info = self._replacements[word] else: self._info = natlink.getWordInfo(word) self._word = word index = word.rfind("\\") if index == -1: self.written = word self.spoken = word else: self.written = word[:index] self.spoken = word[index + 1:] for name, bit in Word._flag_bits.items(): self.__dict__[name.replace(" ", "_")] = ((self._info & bit) != 0)
def __init__(self, word): if word in self._replacements: word, self._info = self._replacements[word] else: self._info = natlink.getWordInfo(word) self._word = word index = word.rfind("\\") if index == -1: self.written = word self.spoken = word else: self.written = word[:index] self.spoken = word[index+1:] for name, bit in Word._flag_bits.items(): self.__dict__[name.replace(" ", "_")] = ((self._info & bit) != 0)
def detect_parser_class(self): engine = dragonfly.engines.get_engine() word = self.words_with_info.get(engine.language, ".\\dot") info = natlink.getWordInfo(word.encode("windows-1252")) if info == None: parser_class = WordParserDns11 else: parser_class = WordParserDns10 parser_class_string = parser_class.__name__ if info == None: info_string = "None" else: info_string = "0x" + format(info, "08x") self._log.info("Selected word parser class {0} because" " natlink.getWordInfo({1!r}) returned {2}" .format(parser_class_string, word, info_string)) return parser_class
def gotResults_batch(self,words,fullResults): files = [f[:-4] for f in os.listdir(wordsFolder)] if files: print 'in folder: %s, files: %s'% (wordsFolder, files) else: print 'in folder: %s, no files found'% wordsFolder return for f in files: F = f + '.txt' if f == 'deleted words': print 'delete words!' for l in open(os.path.join(wordsFolder, F)): w = l.strip() if w.find('\\\\') > 0: w, p = w.split('\\\\') print f, ', word to delete :', w natqh.deleteWordIfNecessary(w) continue if f in FORMATS: formatting = FORMATS[f] print 'to formatting for file: %s: %x'% (f, formatting) else: print 'no formatting information for file: %s'% f formatting = 0 for l in open(os.path.join(wordsFolder, F)): p = 0 # possibly user defined properties w = l.strip() print f, ', word:', w if w.find('\\\\') > 0: w, p = w.split('\\\\') exec("p = %s"%p) ## pList = natqh.ListOfProperties(p) ## for pp in pList: ## print pp newFormat = p or formatting natqh.addWordIfNecessary(w) formatOld = natlink.getWordInfo(w) if formatOld == newFormat: print 'format already okay: %s (%x)'% (w, newFormat) else: natlink.setWordInfo(w, newFormat) print 'format set for %s: %x'% (w, newFormat)
def gotResults_batch(self, words, fullResults): files = [f[:-4] for f in os.listdir(wordsFolder)] if files: print 'in folder: %s, files: %s' % (wordsFolder, files) else: print 'in folder: %s, no files found' % wordsFolder return for f in files: F = f + '.txt' if f == 'deleted words': print 'delete words!' for l in open(os.path.join(wordsFolder, F)): w = l.strip() if w.find('\\\\') > 0: w, p = w.split('\\\\') print f, ', word to delete :', w natqh.deleteWordIfNecessary(w) continue if f in FORMATS: formatting = FORMATS[f] print 'to formatting for file: %s: %x' % (f, formatting) else: print 'no formatting information for file: %s' % f formatting = 0 for l in open(os.path.join(wordsFolder, F)): p = 0 # possibly user defined properties w = l.strip() print f, ', word:', w if w.find('\\\\') > 0: w, p = w.split('\\\\') exec("p = %s" % p) ## pList = natqh.ListOfProperties(p) ## for pp in pList: ## print pp newFormat = p or formatting natqh.addWordIfNecessary(w) formatOld = natlink.getWordInfo(w) if formatOld == newFormat: print 'format already okay: %s (%x)' % (w, newFormat) else: natlink.setWordInfo(w, newFormat) print 'format set for %s: %x' % (w, newFormat)
def __init__(self, word): if word in self._replacements: word, self._info = self._replacements[word] else: if isinstance(word, unicode): word = word.encode("windows-1252") self._info = natlink.getWordInfo(word) self._word = word index = word.rfind("\\") if index == -1: self.written = word self.spoken = word else: self.written = word[:index] self.spoken = word[index+1:] if not self._info: self._info = 0 for name, bit in Word._flag_bits.items(): self.__dict__[name] = ((self._info & bit) != 0)
def gotResults_choose(self, words, fullResults): self.nChoice = None if self.hasCommon(words[-1], 'Medium'): self.nChoice = choiceMiddle elif self.hasCommon(words[-1], 'Strong'): self.nChoice = choiceStrong elif self.hasCommon(words[-1], 'Weak'): self.nChoice = choiceWeak if self.nChoice: del words[-1] else: self.nChoice = choiceMiddle if words[-1] in ChooseList: choice = int(words[-1]) if not choice: print 'no valid choice given' natqh.Wait(0.2) self.cancelMode() natqh.returnFromMessagesWindow() return newWords = self.lastResObj.getWords(choice - 1) res = self.lastResObj.getResults(choice - 1) resCode = res[0][1] resCode = resCode & 0x7fffffff # formatting:=========================================== if 'Format' in words: if not DoFormatting: print 'formatting options invalid!' return if resCode: print 'no formatting can be done on a command!' time.sleep(1.5) elif len(newWords) > 1: print 'no formatting can be done on a list of words' time.sleep(1.5) else: self.newWord = newWords[0] fKeys = FORMATS.keys() fKeys.sort() fcKeys = FormatComments.keys() fcKeys.sort() if fKeys != fcKeys: print 'keys of FORMATS and FormatComments do not match' return numChoices = len(fKeys) if language == 'nld': print 'Formatteren van: %s' % self.newWord print 'Kies Format 1, ..., %i of zeg "Annuleren"' % numChoices elif language == 'enx': print 'Formating: %s' % self.newWord print 'Choose Format 1, ..., %i, or say "Cancel"' % numChoices else: print 'invalid language, skip this' self.cancelMode() return for n in range(numChoices): print '%s:\t%s' % (n + 1, FormatComments[n + 1]) # Entered the new exclusive grammar rules, for the right # format to be chosen self.oopsFlag = 3 self.activateSet(['inoops2'], exclusive=1) return # deleting:=========================================== elif self.hasCommon(words, ['Delete', 'Verwijder']): if resCode: print 'no delete of a command!' time.sleep(1.5) elif len(newWords) > 1: print 'no delete on a list of words' time.sleep(1.5) else: natlink.deleteWord(newWords[0]) print 'deleted: %s' % newWords[0] elif self.hasCommon(words, ['Properties', 'Eigenschappen']): if resCode: print 'no properties on a command!' time.sleep(1.0) elif len(newWords) > 1: print 'no properties of a list of words' time.sleep(1.0) else: self.newWord = newWords[0] props = natlink.getWordInfo(self.newWord) print 'properties of %s: %x' % (self.newWord, props) p = natqh.ListOfProperties(props) if p: for pp in p: print pp time.sleep(4.0) elif self.hasCommon(words, ['Choose', 'Kies', 'OK']): hadChoose = 1 print 'correcting: %s (%s times)' % (newWords, self.nChoice) for i in range(self.nChoice): result = self.lastResObj.correction(newWords) if not result: print 'correction failed' break else: print 'corrected %s times' % self.nChoice else: print 'invalid word in command: %s' % ` words ` time.sleep(2.0) time.sleep(1.0) self.cancelMode() natqh.returnFromMessagesWindow() # Like in DragonDictate, when the word was not a command but a # dictate word, the last phrase is scratched and replaced by the new # text or the new command. if hadChoose and self.FirstIsDictate: print 'mimic first: %s' % ScratchThatCommand natlink.recognitionMimic(ScratchThatCommand) print 'now mimic: %s' % newWords natlink.recognitionMimic(newWords)