ipo_html.html


001| """IPO Implementation -- HTML.
001| 
001| Classes:
001|     ipo_proc_html_safe (ipo_process)            ~HtmlSafe Process subclass
001|     ipo_proc_html_strip (ipo_process)           ~HtmlStrip Process subclass
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, SPC, tabfile, csvfile
006| from ipo_defs import ipo_token, ipo_input, ipo_process, ipo_output, EOL_TAG, SPC_TAG
007| ####################################################################################################
008| Log = logger('HTML')
009| 
010| 
011| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
012| class ipo_proc_html_safe (ipo_process):
013|     """HtmlSafe Process subclass. Turn text into valid text-like HTML."""
014|     tag = 'Text'
015| 
016|     def __init__ (self, **kwargs):
017|         """New HtmlSafe Process instance."""
018|         super().__init__('HtmlSafe')
019| 
020|     def __call__ (self, datum):
021|         """Process next chunk of data."""
022|         if datum is None:
023|             self.status = -1
024|             return None
025|         super().__call__(datum)
026|         return [self.charfunc(d) for d in datum]
027| 
028|     def charfunc (self, datum):
029|         match datum():
030|             case '&':
031|                 datum('&')
032|             case '<':
033|                 datum('&lt;')
034|             case '>':
035|                 datum('&gt;')
036|             case '"':
037|                 datum('&quot;')
038|             case '\n':
039|                 datum('<br>\n')
040|             case _:
041|                 pass
042| 
043|         return datum
044| 
045| 
046| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
047| class ipo_proc_html_strip (ipo_process):
048|     """HtmlStrip Process subclass. Remove HTML from text."""
049|     tag = 'Text'
050| 
051|     def __init__ (self, **kwargs):
052|         """New HtmlStrip Process instance."""
053|         super().__init__('HtmlStrip')
054|         self.delim = KWARG('delim', ' ', str, kwargs)
055|         self.state = 0
056| 
057|     def __call__ (self, datum):
058|         """Process next chunk of data."""
059|         if datum is None:
060|             self.status = -1
061|             return None
062|         super().__call__(datum)
063|         buf = []
064|         for d in datum:
065|             val = d()
066| 
067|             # Outside HTML...
068|             if self.state == 0:
069|                 # HTML begins...
070|                 if val == '<':
071|                     self.state = 1
072|                     continue
073|                 # Regular text...
074|                 buf.append(d)
075|                 continue
076| 
077|             # Inside HTML...
078|             if self.state == 1:
079|                 # HTML ends...
080|                 if val == '>':
081|                     buf.append(ipo_token(SPC, d.row,d.col, SPC_TAG))
082|                     self.state = 0
083|                     continue
084|                 # Quoted string within HTML; ignore any > chars...
085|                 if val == '"':
086|                     self.state = 2
087|                     continue
088|                 # HTML text; ignore...
089|                 continue
090| 
091|             # Inside a quoted string inside HTML...
092|             if self.state == 2:
093|                 # End of quoted string inside HTML...
094|                 if val == '"':
095|                     self.state = 1
096|                     continue
097|                 if val == '\\':
098|                     self.state = 3
099|                     continue
100|                 # Quoted string inside HTML; ignore...
101|                 continue
102| 
103|             # Backslash inside a quoted string inside HTML...
104|             if self.state == 3:
105|                 self.state = 2
106|                 continue
107| 
108|             # We should never get this far...
109|             raise RuntimeError(f'Illegal state: {self.state}')
110| 
111|         # Return stripped text (if any)...
112|         return buf
113| 
114| 
115| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
116| class ipo_proc_html_table (ipo_process):
117|     """HtmlTabl Process subclass."""
118|     tag = 'Table'
119|     html = '{html}'
120| 
121|     def __init__ (self, **kwargs):
122|         """New HtmlTabl Process instance."""
123|         super().__init__('HtmlTabl')
124|         self.font_size = KWARG('font-size', 14, int, kwargs)
125|         self.col_space = KWARG('col-space', 6, int, kwargs)
126|         self.title = KWARG('title', 'Table', str, kwargs)
127|         self.h3 = KWARG('h3', 'Table', str, kwargs)
128|         self.h3_style = KWARG('h3.style', '', str, kwargs)
129|         self.col_style = KWARG('col.style', '', str, kwargs)
130|         self.coln_style = {}
131|         for kw in kwargs:
132|             if kw.startswith('col') and kw[3:].isdigit():
133|                 cx = int(kw[3:])
134|                 self.coln_style[cx-1] = kwargs[kw]
135| 
136|     def __call__ (self, datum):
137|         """Process next chunk of data."""
138|         if datum is None:
139|             self.status = -1
140|             return None
141|         super().__call__(datum)
142| 
143|         if datum[-1]() == EOL:
144|             tail = datum.pop()
145| 
146|         row = [ipo_token('<tr>', self.count, 1, self.html)]
147|         for ix,d in enumerate(datum):
148|             css = self.coln_style[ix] if ix in self.coln_style else ''
149|             tok = f'<td style="{self.col_style} {css}">{d()}</td>'
150|             row.append(ipo_token(tok,self.count,ix+1,self.html))
151|         row.append(ipo_token('</tr>', self.count, len(row), self.html))
152|         row.append(ipo_token(EOL, self.count, len(row), EOL_TAG))
153|         return row
154| 
155|     def start (self, datum):
156|         """Initialize this object."""
157|         super().start(datum)
158|         if datum is not None:
159|             # Get column names...
160|             self.cols = [(d.col,d.colname) for d in datum if d.colname != EOL_TAG]
161|             Log.info('Set Output Column Map:')
162|             Log.info(datum)
163|             Log.info(self.cols)
164| 
165|         # Build HTML header...
166|         output_lines = [
167|             '<!DOCTYPE html>',
168|             '<html>',
169|             '<head>',
170|             '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">',
171|             f'<title>{self.title}</title>',
172|             '<style type="text/css">',
173|             'body {',
174|             'font-family: sans-serif;',
175|             'padding: 5px 10px;',
176|             'margin: 0;',
177|             '}',
178|             'table {',
179|             'font-family: sans-serif;',
180|             f'font-size: {self.font_size:d}px;',
181|             f'border-spacing: {self.col_space}px 4px;',
182|             'padding: 0;',
183|             'border: 1px solid black;',
184|             'margin: 10px;',
185|             '}',
186|             'table thead td {',
187|             'background-color: #000000;',
188|             'color: #ffffff;',
189|             'padding: 3px 6px;',
190|             '}',
191|             'table tbody td {',
192|             'padding: 3px 6px;',
193|             '}',
194|             '</style>',
195|             '</head>',
196|             '<body>',
197|             f'<h1 style="{self.h3_style}">{self.h3}</h1>',
198|             '<table>',
199|         ]
200|         # If we have column headers, emit a THEAD section...
201|         if len(self.cols):
202|             output_lines.append('<thead>')
203|             output_lines.append('<tr>')
204|             for col,hdr in self.cols:
205|                 output_lines.append(f'<td>{hdr}</td>')
206|             output_lines.append('</tr>')
207|             output_lines.append('</thead>')
208| 
209|         output_lines.append('<tbody>')
210|         datum = []
211|         for ix,line in enumerate(output_lines):
212|             d = ipo_token(f'{line}\n', ix+1, 1, self.html)
213|             datum.append(d)
214| 
215|         self.count = len(datum)
216|         return datum
217| 
218|     def stop (self, datum):
219|         """Terminate this object."""
220|         datum = [
221|             ipo_token('</tbody>\n',self.count+1, 1, self.html),
222|             ipo_token('</table>\n',self.count+2, 1, self.html),
223|             ipo_token('</body>\n' ,self.count+3, 1, self.html),
224|             ipo_token('</html>\n' ,self.count+4, 1, self.html),
225|         ]
226|         self.count += 4
227|         return super().stop(datum)
228| 
229| ####################################################################################################
230| if __name__ == '__main__':
231|     print()
232|     ipos = []
233| 
234|     ipos.append(ipo_proc_html_safe())
235|     ipos.append(ipo_proc_html_strip())
236|     ipos.append(ipo_proc_html_table())
237|     ipos.append(None)
238| 
239|     for ix,obj in enumerate(ipos):
240|         if obj is None:
241|             print()
242|             continue
243|         print(f'{ix:2d}: {obj!s}')
244|         obj.start(None)
245|     print()
246| ####################################################################################################
247| """eof"""
248|