ipo_tables.html


001| """IPO Implementation -- Tables.
001| 
001| A "datum" is a list of tuple: (byte/char, datum_index, column_index, column_name)
001| 
001| Classes:
001|     ipo_input_table (ipo_input)                 ~Table Input class (abstract)
001|     ipo_input_tabfile (ipo_input_table)         ~TAB File Input class
001|     ipo_input_csvfile (ipo_input_table)         ~CSV File Input class
001| 
001|     ipo_output_table (ipo_output)               ~Table Output class (abstract)
001|     ipo_output_tabfile (ipo_output_table)       ~TAB File Output class
001|     ipo_output_csvfile (ipo_output_table)       ~CSV File Output class
001| 
001|     ipo_proc_html_table (ipo_process)           ~HtmlTabl Process subclass
001| 
001| """

002| ####################################################################################################
003| from logger import logger
004| from goodies import typename, KWARG
005| from files import EOL, tabfile, csvfile
006| from ipo_defs import ipo_token, ipo_input, ipo_process, ipo_output, EOL_TAG
007| ####################################################################################################
008| Log = logger('Tables')
009| 
010| 
011| ####################################################################################################
012| ## TABLE FILES
013| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
014| class ipo_input_table (ipo_input):
015|     """Table Input subclass (abstract)."""
016|     tag = 'Table'
017| 
018|     def __init__ (self, name, **kwargs):
019|         """New InputTable instance."""
020|         super().__init__(name, **kwargs)
021|         self.filename = KWARG('filename', 'ipo.in', str, kwargs)
022|         self.fobj = None
023|         self.use_hdrs = KWARG('hdrs', 1, int, kwargs)
024|         self.max_rows = KWARG('rmax', -1, int, kwargs)
025|         self.encoding = KWARG('encoding', 'utf8', str, kwargs)
026|         self.sort = KWARG('sort', 0, int, kwargs)
027|         self.rev = KWARG('rev', 0, int, kwargs)
028| 
029|     def __call__ (self):
030|         """Return next chunk of data."""
031|         if len(self.fobj.data) <= self.count:
032|             self.status = -1
033|             return None
034| 
035|         # Get current row...
036|         row = self.fobj.data[self.count]
037|         # Generate datum...
038|         datum = [ipo_token(t[0],self.count+1,ix+1,t[1][1]) for ix,t in enumerate(zip(row, self.cols))]
039|         # Add EOL...
040|         datum.append(ipo_token(EOL,self.count+1,0,EOL_TAG))
041|         return super().__call__(datum)
042| 
043|     def start (self, datum):
044|         """Initialize this object."""
045| 
046|         # Load (all!) input data...
047|         if hasattr(self, 'encoding'):
048|             self.fobj.load(encoding=self.encoding)
049|         else:
050|             self.fobj.load()
051| 
052|         # Extract headers (or use numbers)...
053|         if self.use_hdrs:
054|             self.cols = [(ix,nam) for ix,nam in enumerate(self.fobj.hdrs)]
055|         else:
056|             self.cols = [(ix,str(ix+1)) for ix in range(len(self.fobj[0]))]
057| 
058|         # Sort or Reverse data if requested...
059|         if self.sort:
060|             fk = lambda row:row[self.sort-1]
061|             self.fobj.data = list(sorted(self.fobj.data, key=fk))
062|         if self.rev:
063|             self.fobj.data = list(reversed(self.fobj.data))
064| 
065|         # Generate column-headers datum...
066|         datum = [ipo_token(hdr[1], 0,ix+1, hdr[1]) for ix,hdr in enumerate(self.cols)]
067|         # Add EOL...
068|         datum.append(ipo_token(EOL,self.count+1,0,EOL_TAG))
069|         return super().start(datum)
070| 
071| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
072| class ipo_output_table (ipo_output):
073|     """Table Output subclass (abstract)."""
074|     tag = 'Table'
075| 
076|     def __init__ (self, name, **kwargs):
077|         """New OutputTabFile instance."""
078|         super().__init__(name, **kwargs)
079|         self.filename = KWARG('filename', 'ipo.out', str, kwargs)
080|         self.fobj = None
081|         self.use_hdrs = KWARG('hdrs', 1, int, kwargs)
082|         self.max_rows = KWARG('rmax', -1, int, kwargs)
083|         self.encoding = KWARG('encoding', 'utf8', str, kwargs)
084|         self.sort = KWARG('sort', 0, int, kwargs)
085|         self.rev = KWARG('rev', 0, int, kwargs)
086| 
087|     def __call__ (self, datum):
088|         """Output next chunk of data."""
089|         if datum is None:
090|             self.status = -1
091|             return None
092|         if (self.status < 0) or (len(datum) == 0):
093|             return None
094|         super().__call__(datum)
095| 
096|         # Copy column headers from first datum...
097|         if len(self.cols) == 0:
098|             self.cols = [(d.col,d.colname) for d in datum]
099|             if self.cols[-1][1] == EOL_TAG:
100|                 self.cols.pop()
101|             Log.warn('Adjusting Output Column Map:')
102|             Log.warn(self.cols)
103| 
104|         # Write one row...
105|         self._write_datum(datum)
106|         return self.count
107| 
108|     def start (self, datum):
109|         """Initialize this object."""
110|         super().start(datum)
111|         if datum is not None:
112|             # Get column names...
113|             self.cols = [(d.col,d.colname) for d in datum]
114|             Log.info('Set Output Column Map:')
115|             Log.info(datum)
116|             Log.info(self.cols)
117|         return self.count
118| 
119|     def stop (self, datum):
120|         """Terminate Output."""
121|         if datum is not None:
122|             # Write datum to output...
123|             self._write_datum(datum)
124| 
125|         # Sort or Reverse data if requested...
126|         if self.sort:
127|             fk = lambda row:row[self.sort-1]
128|             self.fobj.data = list(sorted(self.fobj.data, key=fk))
129|         if self.rev:
130|             self.fobj.data = list(reversed(self.fobj.data))
131| 
132|         # Extract headers...
133|         if self.use_hdrs:
134|             self.fobj.hdrs = [col[1] for col in self.cols]
135| 
136|         # SAVE OUTPUT...
137|         if hasattr(self, 'encoding'):
138|             # Output encoding (if provided)...
139|             self.fobj.save(encoding=self.encoding)
140|         else:
141|             self.fobj.save()
142|         return super().stop(datum)
143| 
144|     def _write_datum (self, datum):
145|         """Process datum into row of columns and write to file."""
146|         row = [d() for d in datum]
147|         if row[-1] == EOL: row.pop()
148|         self.fobj.data.append(row)
149| 
150| 
151| ####################################################################################################
152| ## TAB-DELIMITED TABLE
153| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
154| class ipo_input_tabfile (ipo_input_table):
155|     """TAB File Input subclass."""
156| 
157|     def __init__ (self, **kwargs):
158|         """New InputTabFile instance."""
159|         super().__init__('TAB-FileIn', **kwargs)
160|         self.fobj = tabfile(self.filename, maxrows=self.max_rows, headers=self.use_hdrs)
161| 
162| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
163| class ipo_output_tabfile (ipo_output_table):
164|     """TAB File Output subclass."""
165| 
166|     def __init__ (self, **kwargs):
167|         """New OutputTabFile instance."""
168|         super().__init__('TAB-FileOut', **kwargs)
169|         self.fobj = tabfile(self.filename, maxrows=self.max_rows, headers=self.use_hdrs)
170| 
171| 
172| ####################################################################################################
173| ## CSV TABLE (COMMA-SEPARATED VALUES)
174| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
175| class ipo_input_csvfile (ipo_input_table):
176|     """CSV File Input subclass."""
177| 
178|     def __init__ (self, **kwargs):
179|         """New InputCSVFile instance."""
180|         super().__init__('CSV-FileIn', **kwargs)
181|         self.fobj = csvfile(self.filename, maxrows=self.max_rows, headers=self.use_hdrs)
182| 
183| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
184| class ipo_output_csvfile (ipo_output_table):
185|     """CSV File Output subclass."""
186| 
187|     def __init__ (self, **kwargs):
188|         """New OutputCSVFile instance."""
189|         super().__init__('CSV-FileOut', **kwargs)
190|         self.fobj = csvfile(self.filename, maxrows=self.max_rows, headers=self.use_hdrs)
191|         self.delimiter = KWARG('delim', '', str, kwargs)
192| 
193|     def start (self, datum):
194|         """Initialize this object."""
195|         super().start(datum)
196|         if self.delimiter:
197|             self.fobj.delim = self.delimiter
198|         return datum
199| 
200| 
201| ####################################################################################################
202| if __name__ == '__main__':
203|     print()
204|     ipos = []
205| 
206|     ipos.append(ipo_input_tabfile(**{'filename': r'C:\demo\input.tab'}))
207|     ipos.append(ipo_input_csvfile(**{'filename': r'C:\demo\input.csv'}))
208|     ipos.append(None)
209| 
210|     ipos.append(ipo_output_tabfile(**{'filename': r'C:\demo\output.tab'}))
211|     ipos.append(ipo_output_csvfile(**{'filename': r'C:\demo\output.csv'}))
212|     ipos.append(None)
213| 
214|     for ix,obj in enumerate(ipos):
215|         if obj is None:
216|             print()
217|             continue
218|         print(f'{ix:2d}: {obj!s}')
219|         obj.start(None)
220|     print()
221| ####################################################################################################
222| """eof"""
223|