ipo.html
001| """IPO -- Input-Process-Output -- General file processor.
001|
001| IPO instances are configured with command line or text file parameters.
001| Three are required: the actual IPO functions:
001|
001| I = <ipo-class> | <module-name>.<class-name> ~input function
001| P = <ipo-class> | <module-name>.<class-name> ~process function
001| O = <ipo-class> | <module-name>.<class-name> ~output function
001|
001| Parameters for the three functions are specified:
001|
001| i.name = value ~input parameter
001| p.name = value ~process parameter
001| o.name = value ~output parameter
001|
001| General parameters for the IPO engine are specified:
001|
001| .name = value ~general IPO parameter
001|
001| Classes:
001| ipo_params ~IPO configuration class.
001|
001| Functions:
001| run_ipo_engine (cfg, kw_i, kw_p, kw_o)
001|
001| Module Commands:
001| cmd do_ipo_command ~IPO config from command line
001| file do_ipo_file ~IPO config from text file
001| list do_list_ipo_classes ~List known IPO classes to stdout
001| demo do_ipo_demo ~Simple IPO demo
001| test do_test ~for testing
001|
001| ATTN: Multiple Process instances (chained)?
001| ATTN: Multiple input files?
001| """
002|
003| from sys import argv, exc_info, modules
004| from traceback import extract_tb
005| from os import path
006| from importlib import import_module
007| from random import random
008| from logger import logger,info,debug,trace, LogFilenameTimestamp
009| from goodies import KWARG, typename
010| from files import linefile
011| from ipo_defs import IPO
012| from ipo_dir import ipo_classes
013|
014| BasePath = r'C:\CJS\prj\Python\app\ipo'
015| CnfgPath = path.join(BasePath, 'cfg')
016| ListPath = path.join(BasePath, 'out')
017| LogsPath = path.join(BasePath, 'log')
018| Log = logger('Main')
019|
020| CMND = ''
021| ARGS = {
022|
023|
024|
025|
026|
027|
028|
029|
030|
031|
032|
033|
034|
035|
036|
037|
038|
039|
040|
041|
042|
043|
044|
045|
046|
047|
048|
049|
050|
051|
052|
053|
054|
055|
056|
057|
058|
059|
060|
061|
062|
063|
064|
065|
066|
067|
068|
069| }
070|
071|
072|
073| class ipo_params:
074| """\
074| IPO Parameters class.
074|
074| Parses and holds I/P/O Function and IPO Engine configuration parameters.
074|
074| Properties:
074| spec_[i|p|o] ~[str] function spec
074| cls_[i|p|o] ~[ipo_object] function class
074| kw_[i|p|o] ~[dict] function arguments
074| config ~[dict] IPO Engine configuration
074|
074| Methods:
074| input_filename (filename) ~set input filename (i.filename)
074| output_filename (filename) ~set output filename (o.filename)
074|
074| """
075| def __init__ (self, **kwargs):
076| """New IPO Parameters instance. Process kwargs."""
077|
078| _kwargs = {k.lower():v for k,v in kwargs.items()}
079|
080|
081| assert 'i' in _kwargs, KeyError('IPO requires an input spec: I=<spec>')
082| assert 'p' in _kwargs, KeyError('IPO requires a process spec: P=<spec>')
083| assert 'o' in _kwargs, KeyError('IPO requires an output spec: O=<spec>')
084|
085|
086| self.spec_i = _kwargs['i']
087| self.spec_p = _kwargs['p']
088| self.spec_o = _kwargs['o']
089| self.cls_i = self._get_ipo_class(self.spec_i)
090| self.cls_p = self._get_ipo_class(self.spec_p)
091| self.cls_o = self._get_ipo_class(self.spec_o)
092|
093|
094| self.kw_i = {kw[2:]:_kwargs[kw] for kw in _kwargs if kw.startswith('i.')}
095| self.kw_p = {kw[2:]:_kwargs[kw] for kw in _kwargs if kw.startswith('p.')}
096| self.kw_o = {kw[2:]:_kwargs[kw] for kw in _kwargs if kw.startswith('o.')}
097|
098|
099| self.config = {'I':self.cls_i, 'P':self.cls_p, 'O':self.cls_o}
100|
101| for kw in _kwargs:
102| if kw.startswith('.'):
103| self.config[kw[1:]] = _kwargs[kw]
104| Log.debug()
105|
106| def input_filename (self, filename):
107| """Set the input filename explicitly."""
108| self.kw_i['filename'] = filename
109|
110| def output_filename (self, filename):
111| """Set the output filename explicitly."""
112| self.kw_o['filename'] = filename
113|
114| def __str__ (self):
115| """Return a nice string."""
116| cni = self.cls_i.__name__
117| cnp = self.cls_p.__name__
118| cno = self.cls_o.__name__
119| return f'IPO: {cni}|{cnp}|{cno}'
120|
121| def __repr__ (self):
122| """Return a JSON-like string."""
123| cni = self.cls_i.__name__
124| cnp = self.cls_p.__name__
125| cno = self.cls_o.__name__
126| return f'{ ipoParams:{ I:{cni}, P:{cnp}, O:{cno}, id:{id(self):08x}} } '
127|
128| def _get_ipo_class (self, spec):
129| """Parse spec to find and return an IPO class."""
130|
131|
132| if ':' in spec:
133| ftn = ipo_classes[spec]
134| Log.debug(f'using "{ftn.__name__}"')
135| return ftn
136|
137|
138| if '.' in spec:
139| mod_name,ftn_name = spec.split('.')
140|
141| if mod_name in modules:
142| mod = modules[mod_name]
143| ftn = mod.__dict__[ftn_name]
144| Log.debug(f'found "{ftn.__name__}" in "{mod.__name__}"')
145| return ftn
146|
147| mod = import_module(mod_name)
148| ftn = mod.__dict__[ftn_name]
149| Log.debug(f'imported "{ftn.__name__}" from "{mod.__name__}"')
150| return ftn
151|
152|
153| raise RuntimeError(f'Unrecognized IPO class spec: "{spec}"')
154|
155|
156|
157| def run_ipo_engine (cfg, kw_i, kw_p, kw_o):
158| """Run the IPO Engine given IO files plus classes and their arguments."""
159| Log.info('IPO-Engine::')
160|
161|
162| cls_i = cfg['I']
163| cls_p = cfg['P']
164| cls_o = cfg['O']
165| Log.info(f'I.class: {cls_i.__name__}')
166| Log.info(f'P.class: {cls_p.__name__}')
167| Log.info(f'O.class: {cls_o.__name__}')
168| Log.info()
169| psi = ', '.join(f'{k}={v}' for k,v in kw_i.items())
170| psp = ', '.join(f'{k}={v}' for k,v in kw_p.items())
171| pso = ', '.join(f'{k}={v}' for k,v in kw_o.items())
172| Log.info(f'I.args: {psi}')
173| Log.info(f'P.args: {psp}')
174| Log.info(f'O.args: {pso}')
175| Log.info()
176|
177|
178| ipo_i = cls_i(**kw_i)
179| ipo_p = cls_p(**kw_p)
180| ipo_o = cls_o(**kw_o)
181| Log.debug()
182| Log.debug(ipo_i)
183| Log.debug(ipo_p)
184| Log.debug(ipo_o)
185| Log.debug()
186|
187|
188| ipo_obj = IPO(ipo_i, ipo_p, ipo_o, **cfg)
189| Log.info(ipo_obj)
190| Log.info()
191|
192| try:
193|
194| ipo_obj.execute()
195| Log.info()
196| Log.info(ipo_obj)
197| Log.info()
198|
199| except RuntimeError as e:
200| etype, evalue, tb = exc_info()
201| ts = extract_tb(tb)
202| Log.error()
203| Log.error(f'{etype.__name__}: {str(evalue)}')
204| Log.error()
205| for t in ts[-3:]:
206| Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
207| Log.error(f' {t[3]}')
208| Log.error()
209|
210|
211| Log.info(ipo_i)
212| Log.info(ipo_p)
213| Log.info(ipo_o)
214| Log.info()
215| return ipo_obj
216|
217|
218| def do_ipo_file (**kwargs):
219| """CMND: IPO File. Get configuration from a text file."""
220| fpath = KWARG('fpath', CnfgPath, str, kwargs)
221| fname = KWARG('fname', 'ipo.in', str, kwargs)
222| Log.info('ipo-file:: %s' % str(list(kwargs.keys())))
223| Log.debug(f'{fpath=}')
224| Log.debug(f'{fname=}')
225| Log.info()
226|
227|
228| fn = path.join(fpath,fname) if fpath else fname
229| fo = linefile(fn)
230| fo.load()
231|
232| args = {}
233| for ix,line in enumerate(fo):
234| line = line.strip()
235| Log.debug(f'[{ix:03d}] {line}')
236|
237|
238| if len(line) == 0:
239| continue
240|
241|
242| if line.startswith('#'):
243| continue
244|
245|
246| if '=' not in line:
247| continue
248|
249|
250| key,val = (s.strip() for s in line.split('='))
251|
252| if val.startswith('"') and val.endswith('"'):
253| val = val[1:-1]
254|
255|
256| args[key] = val
257|
258|
259| params = ipo_params(**args)
260|
261|
262| kw_i = params.kw_i
263| kw_p = params.kw_p
264| kw_o = params.kw_o
265| ipo_obj = run_ipo_engine(params.config, kw_i, kw_p, kw_o)
266|
267| return 'Done'
268|
269|
270| def do_ipo_command (**kwargs):
271| """CMND: IPO Command Line. Get configuration from commandline arguments."""
272| ipath = KWARG('ipath', '', str, kwargs)
273| opath = KWARG('opath', '', str, kwargs)
274| iname = KWARG('iname', 'ipo.in', str, kwargs)
275| oname = KWARG('oname', 'ipo.out', str, kwargs)
276| Log.info('ipo-command:: %s' % str(list(kwargs.keys())))
277| Log.debug(f'{ipath=}')
278| Log.debug(f'{opath=}')
279| Log.debug(f'{iname=}')
280| Log.debug(f'{oname=}')
281| Log.info()
282|
283|
284| params = ipo_params(**kwargs)
285|
286|
287| params.input_filename(path.join(ipath,iname) if ipath else iname)
288| params.output_filename(path.join(opath,oname) if opath else oname)
289|
290|
291| kw_i = params.kw_i
292| kw_p = params.kw_p
293| kw_o = params.kw_o
294| ipo_obj = run_ipo_engine(params.config, kw_i, kw_p, kw_o)
295|
296| return 'Done'
297|
298|
299| def do_ipo_demo (**kwargs):
300| """CMND: IPO Demo."""
301| Log.info('ipo-demo:: %s' % str(list(kwargs.keys())))
302| Log.info()
303|
304|
305| kw_i = {'filename':path.join(CnfgPath,'ipo.in')}
306| kw_p = {}
307| kw_o = {'filename':path.join(ListPath,'ipo.out')}
308|
309|
310| cls_i = ipo_classes['I:line']
311| cls_p = ipo_classes['P:rot13']
312| cls_o = ipo_classes['O:line']
313|
314|
315| cfg = {'I':cls_i, 'P':cls_p, 'O':cls_o, 'max':0}
316|
317|
318| ipo_obj = run_ipo_engine(cfg, kw_i, kw_p, kw_o)
319| return 'Done'
320|
321|
322| def do_list_ipo_classes (**kwargs):
323| """CMND: List known IPO classes to stdout and log."""
324| opath = KWARG('opath', BasePath, str, kwargs)
325| oname = KWARG('oname', 'ipo-classes.list', str, kwargs)
326| Log.info('list-ipo-classes:: %s' % str(list(kwargs.keys())))
327| Log.debug(f'{opath=}')
328| Log.debug(f'{oname=}')
329| Log.info()
330| fn = path.join(opath,oname) if opath else oname
331| fo = linefile(fn)
332| fo.add('IPO Classes')
333| fo.add()
334|
335| for key,cls in ipo_classes.items():
336| s1 = f'{key}'
337| s2 = f'> {cls.__name__} ({cls.__module__})'
338| s3 = f'> {cls.__doc__}'
339|
340|
341| fo.add(s1)
342| fo.add(s2)
343| fo.add(s3)
344| fo.add()
345|
346| Log.info(s1)
347| Log.info(s2)
348| Log.info(s3)
349| Log.info()
350|
351| print(s1)
352| print(s2)
353| print(s3)
354| print()
355|
356|
357| fo.save()
358|
359| Log.info()
360| return 'Done'
361|
362|
363| def do_test (**kwargs):
364| """CMND: Do a test."""
365| ipath = KWARG('ipath', CnfgPath, str, kwargs)
366| opath = KWARG('opath', ListPath, str, kwargs)
367| iname = KWARG('iname', 'test.in', str, kwargs)
368| oname = KWARG('oname', 'test.out', str, kwargs)
369| Log.info('test:: %s' % str(list(kwargs.keys())))
370| Log.debug(f'{ipath=}')
371| Log.debug(f'{opath=}')
372| Log.debug(f'{iname=}')
373| Log.debug(f'{oname=}')
374| Log.info()
375|
376| Log.info()
377| return 'Done'
378|
379| def dispatch (cmd, **kwargs):
380| """Dispatch to a module function based on CMD."""
381| Log.info(f'CMD: {cmd}')
382| for kw in kwargs:
383| Log.debug(f'argument[{kw}]: {kwargs[kw]}')
384| Log.info()
385| if cmd == 'cmd' : return do_ipo_command(**kwargs)
386| if cmd == 'file': return do_ipo_file(**kwargs)
387| if cmd == 'demo': return do_ipo_demo(**kwargs)
388| if cmd == 'list': return do_list_ipo_classes(**kwargs)
389| if cmd == 'test': return do_test(**kwargs)
390| return 'Nothing to do!'
391|
392| if __name__ == '__main__':
393| print('autorun: %s' % argv[0])
394|
395| Log.start(path.join(LogsPath,LogFilenameTimestamp(f'ipo_%s-{int(random()*0xffff):04x}.log')))
396| Log.level(info())
397| Log.info(argv[0])
398| Log.info()
399| cmd = argv[1] if 1 < len(argv) else CMND
400| kwargs = ARGS
401| for a in argv[2:]:
402| nv = a.split('=', 1)
403| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
404| Log.trace('%s: "%s"' % (nv[0], kwargs[nv[0]]))
405| Log.trace()
406| try:
407| print(f'CMD: {cmd}')
408| print()
409| obj = dispatch(cmd, **kwargs)
410| print()
411| print(obj)
412| Log.info()
413| Log.info(obj)
414| except:
415| etype, evalue, tb = exc_info()
416| ts = extract_tb(tb)
417| Log.error()
418| Log.error('%s: %s' % (etype.__name__,str(evalue)))
419| Log.error()
420| for t in ts[-5:]:
421| Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
422| Log.error(' %s' % t[3])
423| Log.error()
424| raise
425| finally:
426| Log.end()
427|
428| '''eof'''
429|