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|     #'I': 'I:ftab',
023|     #'P': 'P:nop',
024|     #'O': 'O:tab',
025|     #'iname': 'ipo.in',
026|     #'oname': 'ipo-ftab.out',
027|     #'p.title': 'ESC Files',
028|     #'p.h3': 'ESC Files',
029|     #'p.h3.style': 'color:#3366cc;font-size:12px;font-weight:bold;',
030|     #'p.col.style': 'text-align:right;',
031|     #'p.col0': 'font-weight:bold;',
032|     #'p.col1': 'text-align:right;',
033|     #'i.sort': '14',
034|     #'i.rev': '1',
035|     #'i.hdrs': '0',
036|     #'i.encoding': 'utf8',
037|     #'i.fpath': r'C:\CJS\prj\Python\ws\ESC',
038|     #'i.mode': 0,
039|     #'i.find': '(bmp|png)',
040|     #'i.start': 'img_',
041|     #'i.end': '.png',
042|     #'p.find': 'DEBUG',
043|     #'p.case': 'uc',
044|     #'p.mask': str(0x7f),
045|     #'p.rev': '1',
046|     #'p.pct': '0.05',
047|     #'p.mode': 0,
048|     #'p.row': '24',
049|     #'p.size': '4',
050|     #'p.tabs': '12',
051|     #'p.delim': '_',
052|     #'p.addr': 'dec',
053|     #'p.data': 'dec',
054|     #'o.encoding': 'utf8',
055|     #'o.sort': '1',
056|     #'o.rev': '1',
057|     #'o.hdrs': '0',
058|     #'o.delim': '|',
059|     #'.max': '1000',
060|     #'iname': 'ipo.in', 'oname': 'ipo.out',
061|     #'iname': 'ipo-tab.in', 'oname': 'ipo-tab.out',
062|     #'iname': 'ipo-csv.in', 'oname': 'ipo-csv.out',
063|     #'iname': 'ipo-log.in', 'oname': 'ipo-log.out',
064|     #'iname': 'ipo-tab.in', 'oname': 'ipo-tab-csv.out',
065|     #'iname': 'ipo-csv.in', 'oname': 'ipo-csv-tab.out',
066|     #'ipath': BasePath,
067|     #'opath': BasePath,
068|     #'fpath': BasePath,
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|         # Ensure lowercase keywords...
078|         _kwargs = {k.lower():v for k,v in kwargs.items()}
079| 
080|         # Required parameters (all others optional)...
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|         # Get I/P/O specs and the classes they specify...
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|         # I/P/O function parameters...
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|         # IPO Engine configuration...
099|         self.config = {'I':self.cls_i, 'P':self.cls_p, 'O':self.cls_o}
100|         # Engine parameters...
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|         # A spec like "[IPO]:name" is a class key for a known class...
132|         if ':' in spec:
133|             ftn = ipo_classes[spec]
134|             Log.debug(f'using "{ftn.__name__}"')
135|             return ftn
136| 
137|         # A period indicates a "module-name.class-name" pair...
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|         # It should have been one of the above...
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|     # Get the I/P/O classes...
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|     # Get instances of the I/P/O classes...
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|     # The IPO engine instance...
188|     ipo_obj = IPO(ipo_i, ipo_p, ipo_o, **cfg)
189|     Log.info(ipo_obj)
190|     Log.info()
191| 
192|     try:
193|         # === Execute! ===
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|         #NOTE: No re-raise! Be sure to check the log for errors!
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|     # Load configuration file...
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|         # Ignore blank lines...
238|         if len(line) == 0:
239|             continue
240| 
241|         # Ignore comment lines...
242|         if line.startswith('#'):
243|             continue
244| 
245|         # Ignore lines lacking "key=value" format...
246|         if '=' not in line:
247|             continue
248| 
249|         # Parse "key = value" pair...
250|         key,val = (s.strip() for s in line.split('='))
251|         # Strip any double-quotes from value...
252|         if val.startswith('"') and val.endswith('"'):
253|             val = val[1:-1]
254| 
255|         # Add key:value to arguments...
256|         args[key] = val
257| 
258|     # Parse input parameters...
259|     params = ipo_params(**args)
260| 
261|     # Call the IPO engine...
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|     # Parse input parameters...
284|     params = ipo_params(**kwargs)
285| 
286|     # Input and output filenames...
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|     # Call the IPO engine...
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|     # Input and Output filenames...
305|     kw_i = {'filename':path.join(CnfgPath,'ipo.in')}
306|     kw_p = {}
307|     kw_o = {'filename':path.join(ListPath,'ipo.out')}
308| 
309|     # Get the I/P/O classes...
310|     cls_i = ipo_classes['I:line']
311|     cls_p = ipo_classes['P:rot13']
312|     cls_o = ipo_classes['O:line']
313| 
314|     # IPO engine configuration...
315|     cfg = {'I':cls_i, 'P':cls_p, 'O':cls_o, 'max':0}
316| 
317|     # Call the IPO engine...
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|         # Print to file...
341|         fo.add(s1)
342|         fo.add(s2)
343|         fo.add(s3)
344|         fo.add()
345|         # Print to log...
346|         Log.info(s1)
347|         Log.info(s2)
348|         Log.info(s3)
349|         Log.info()
350|         # Print to console...
351|         print(s1)
352|         print(s2)
353|         print(s3)
354|         print()
355| 
356|     # Save the list file...
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|     #Log.start(path.join(BasePath,'ipo.log'), mode='w')
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|