Skip to content

Commit

Permalink
Merge pull request #51 from dougransom/check_unimacro_feb24
Browse files Browse the repository at this point in the history
Check unimacro feb24.   a few changes were never merged because they weren't comitted to the branch on the fork.  

There were some conflicts, did my best guess to resolve them.
  • Loading branch information
dougransom authored Aug 7, 2024
2 parents 5c040a5 + 9b027ee commit deacfbd
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 47 deletions.
5 changes: 4 additions & 1 deletion src/unimacro/UnimacroGrammars/_folders.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@
import win32gui
from win32com.client import Dispatch
import win32clipboard
from logging import Logger,getLogger
from io import StringIO

import natlink
from natlinkcore import readwritefile
Expand All @@ -78,7 +80,6 @@

# manipulating file names with env variables etc...
envvars = extenvvars.ExtEnvVars()

thisDir = str(Path(__file__).parent)
status = natlinkstatus.NatlinkStatus()
# for getting unicode explorer window titles:
Expand Down Expand Up @@ -236,6 +237,7 @@ def gotResultsInit(self,words,fullResults):
self.progInfo = unimacroutils.getProgInfo()



def handleTrackFilesAndFolders(self, activeFolder):
"""set or empty lists for activeFolder and set/reset self.activeFolder
"""
Expand Down Expand Up @@ -614,6 +616,7 @@ def getActiveFolder(self, hndle=None, className=None):
if not className:
return None
f = None

if className == "CabinetWClass":
f = mess.getFolderFromCabinetWClass(hndle)
elif className == '#32770':
Expand Down
17 changes: 12 additions & 5 deletions src/unimacro/_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,24 +32,30 @@

from unimacro import natlinkutilsbj as natbj
from unimacro import spokenforms
import importlib.metadata as meta
import sys

#from unimacro.logger import ulogger
status = natlinkstatus.NatlinkStatus()
natlinkmain = loader.NatlinkMain()

#a global logger for unimacro. perfectly reasonable to access by name instead.
import logging as l

#for some reason, importing amodule which does this doesn't work. Likely because natlinkmain must be started first for
#this sublogger natlink.unimacro to work correctly.
import unimacro as unimacro_l #bring in so we can add a variable ulogger to the namespace.
ulogger : l.Logger = l.getLogger(unimacro_l.logname())

unimacro_l.__dict__['ulogger']=ulogger
ulogger.debug("natlink.unimacro logger available")

#Loggers can be created for any module, and they can propogate to the parent Logger, or not.
#As an example, this module for the control grammar has its own child logger of unimacro.
#Note an entry point has to be defined as well, in pyproject.toml, so Loggers for various natlink components can be discovered.
control_logger=l.getLogger(unimacro_l.control_logger_name())


unimacro_l.__dict__['ulogger']=ulogger
ulogger.debug("natlink.unimacro logger available")
status = natlinkstatus.NatlinkStatus()
natlinkmain = loader.NatlinkMain()
control_logger=l.getLogger(unimacro_l.control_logger_name())



Expand Down Expand Up @@ -441,6 +447,7 @@ def gotResults_show(self,words,fullResults):
self.gotResults_showexclusive(words, fullResults)
return
if self.hasCommon(words,"loggers"):
self.info(f"Available Loggers: {self.loggers}")
L = ['\nAvailable Loggers apart from the root (natlink) logger:']
for key, loggerid in self.loggers.items():
logger=l.getLogger(loggerid)
Expand Down
52 changes: 23 additions & 29 deletions src/unimacro/natlinkutilsbj.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@
import logging
from logging import Logger
import win32com
import logging
from logging import Logger
import natlink
from natlinkcore import loader
from natlinkcore import gramparser # for translation with GramScannerReverse
Expand Down Expand Up @@ -196,40 +198,21 @@ def letterUppercase(l):
PythonServerExe=os.path.join(PythonwinPath, 'pserver1')

# returns the union of two lists
def Union(L1,L2):
def Union(L1,L2) -> list:
"""old fashioned union function of two lists
"""
if not isinstance(L1, list):
raise TypeError(f'function Union, first input variable not a list: {type(L1)}')
if not isinstance(L2, list):
raise TypeError(f'function Union, second input variable not a list: {type(L2)}')
L=L1[:]
for i in L2:
if not i in L1:
L.append(i)
return L
return list(set(L1).union(L2))

# returns the intersection of two lists
def Intersect(L1,L2):
"""old fashioned intersection function of two lists
"""
if not isinstance(L1, list):
raise TypeError(f'function Intersect, first input variable not a list: {type(L1)}')
if not isinstance(L2, list):
raise TypeError(f'function Intersect, second input variable not a list: {type(L2)}')
L=[]
for i in L2:
if i in L1:
L.append(i)
return L

def reverseDict(Dict):
return set(L1).intersection(L2)

def reverseDict(Dict : dict):
"""reverse a dict, ignoring multiple values of the original
"""
revDict={}
for key in list(Dict.keys()):
revDict[Dict[key]]=key
return revDict
return {val: key for (key, val) in Dict.items()}

def joinNestedStringLists(l):
"""nested lists of strings are "flattened" into one string
Expand Down Expand Up @@ -333,11 +316,22 @@ def fn(self,*args,**kwargs):
return fn

#add methods to delegate calls to logger, so we wave info, warn, etc.
wrapped_logger=[Logger.info,Logger.setLevel,Logger.debug,Logger.warning,Logger.error,Logger.exception,Logger.critical,Logger.log]
for n in wrapped_logger:
locals()[n.__name__]=wrapped_log(n)

#this would be the better way to do it, but we haven't found a way to get code completion
#wrapped_logger=[Logger.info,Logger.setLevel,Logger.debug,Logger.warning,Logger.error,Logger.exception,Logger.critical,Logger.log]
#for n in wrapped_logger:
# locals()[n.__name__]=wrapped_log(n)
#instead, copy and paste.


info=wrapped_log(Logger.info)
setLevel=wrapped_log(Logger.setLevel)
debug=wrapped_log(Logger.debug)
warning=wrapped_log(Logger.warning)
error=wrapped_log(Logger.error)
exception=wrapped_log(Logger.exception)
critical=wrapped_log(Logger.critical)
log=wrapped_log(Logger.log)

def getExclusiveGrammars(self):
"""return the dict of (name, grammarobject) of GrammarX objects that are exclusive
"""
Expand Down
25 changes: 13 additions & 12 deletions src/unimacro/sample_global_dictation/_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def gotBegin(self, moduleInfo):

def gotResultsInit(self,words,fullResults):
if self.mayBeSwitchedOn == 'exclusive':
print('recog controle, switch off mic: %s'% words)
self.warning('recog controle, switch off mic: %s', words)
natbj.SetMic('off')
if self.exclusive and self.doMessages:
self.DisplayMessage('<%s>'% ' '.join(words))
Expand Down Expand Up @@ -227,7 +227,7 @@ def restoreMode(self):
self.Mode = self.LastMode

def gotResults_trace(self,words,fullResults):
print('control, trace: %s'% words)
self.info('control, trace: %s', words)
if self.hasCommon(words, 'actions'):
if self.hasCommon(words, 'show'):
actions.debugActionsShow()
Expand All @@ -250,15 +250,16 @@ def gotResults_voicecode(self,words,fullResults):
wxmed = os.path.join(voicecodeHome, 'mediator', 'wxmediator.py')
if os.path.isfile(wxmed):
commandLine = r"%spython.exe %s > D:\foo1.txt >> D:\foo2.txt"% (sys.prefix, wxmed)
self.debug("commandLine : %s",commandLine)
os.system(commandLine)
else:
print('not a file: %s'% wxmed)
self.info('not a file: %s',wxmed)




def gotResults_switch(self,words,fullResults):
print('control, switch: %s'% words)
self.info('control, switch: %s', words)
if self.hasCommon(words, 'on'):
func = 'switchOn'
elif self.hasCommon(words, 'off'):
Expand All @@ -272,16 +273,16 @@ def gotResults_switch(self,words,fullResults):
self.DisplayMessage(t)
return
if self.hasCommon(words, 'all grammars'):
print('%s all grammars:'% func)
self.info('%s all grammars:', func)
natbj.CallAllGrammarObjects(func, ())
print("-"*10)
self.info("-"*10)
else:
gramname = self.hasCommon(words, list(natbj.allUnimacroGrammars.keys()))
if gramname:
gram = natbj.allUnimacroGrammars[gramname]
gram.callIfExists(func, ())
else:
print('no grammar name found: %s'% gramname)
self.warning('no grammar name found: %s'% gramname)

def gotResults_showexclusive(self,words,fullResults):
if natbj.exclusiveGrammars:
Expand Down Expand Up @@ -335,7 +336,7 @@ def gotResults_show(self,words,fullResults):
return

if natbj.exclusiveGrammars:
print('exclusive (+ control) are: %s'% ' '.join(list(natbj.exclusiveGrammars.keys())))
self.info('exclusive (+ control) are: %s', ' '.join(list(natbj.exclusiveGrammars.keys())))

grammars = natbj.allUnimacroGrammars
gramNames = list(grammars.keys())
Expand Down Expand Up @@ -379,7 +380,7 @@ def gotResults_show(self,words,fullResults):
Start=(' '.join(name),[])
else:
Start=()
print('start browsing with: %s'% All)
self.info('start browsing with: %s', All)
self.Browse(Start,All)


Expand Down Expand Up @@ -410,7 +411,7 @@ def gotResults_edit(self,words,fullResults):
self.DisplayMessage('grammar "%s" has no method "editInifile"'% gramName)
return
else:
print('no grammar name found')
self.info('no grammar name found')


def switchOff(self, **kw):
Expand Down Expand Up @@ -454,7 +455,7 @@ def __init__(self):
natlinkutils.DictGramBase.__init__(self)

def initialize(self):
print('initializing/loading DictGrammar!!')
self.info('initializing/loading DictGrammar!!')
self.load()
natbj.RegisterMessageObject(self)

Expand All @@ -464,7 +465,7 @@ def unload(self):

def gotResults(self, words):
## pass
print('messageDictGrammar: heard dictation: %s '% words)
self.info('messageDictGrammar: heard dictation: %s ', words)


# standard stuff Joel (adapted for possible empty gramSpec, QH, unimacro)
Expand Down

0 comments on commit deacfbd

Please sign in to comment.