thumbx.html


001| '''\
001| Thumbx -- Create index.html page with thumbnail images.
001| 
001| Given a configuration, generates a list of JPEG image "thumb" files for each
001| image file found in the specified folder. Then it uses that list to create an
001| index.html page listing them.
001| 
001| The process looks for an existing thumbnail image and creates a new one if it
001| can't find it.
001| 
001| The process uses the thumbx.xml configuration file specified at startup.
001| 
001| {{No good reason for the name "thumbx"; it was the working name, and it just stuck.}}
001| 
001| Developer@Sonnack.com
001| July 2017
001| November 2013
001| '''

002| ####################################################################################################
003| from sys import argv, exc_info, stdout
004| from traceback import extract_tb
005| from os import path, listdir, mkdir
006| from datetime import datetime
007| from PIL import Image
008| from logger import logger, info,debug,trace, LogFilenameTimestamp
009| from xml_sax import XmlHandlerConfigBase, Property, parse_xml_file
010| from files import filefinder
011| from goodies import KWARG
012| from webpage import WebPage
013| ####################################################################################################
014| BasePath = r'C:\CJS\prj\Python\app\thumbx'
015| XmlFileName = path.join(BasePath,'thumbx.xml')
016| Log = logger('thumbx')
017| 
018| CMND = '' ## do make list test
019| ARGS = {
020|     #'cfg': 'default',
021|     #'xml': XmlFileName,
022| }
023| 
024| ThumbFilePattern = '%s.jpg'
025| 
026| FileFilter = lambda fn: (fn[-4:] in ['.bmp','.gif','.jpg','.png']) and path.isfile(fn)
027| 
028| IsTrue = lambda s: (s.lower()[0] in 't1y')
029| 
030| CssPages = ['/basic.css', '/thumbx.css']
031| 
032| HtmlListBegin = '<table>'
033| HtmlListEnd   = '</table>'
034| HtmlListRowBegin = '<tr>'
035| HtmlListRowEnd   = '</tr>'
036| HtmlListItem = '''\
036| <td style="font-size:10pt;text-align:center;">
036|     <a target="bigpic" href="%s"><img src="thumbx/%s" width="%d" height="%d" style="%s"></a><br>
036|     <a target="bigpic" href="%s" style="%s">%s</a>
036| </td>
036| '''

037| 
038| OldPaths = [
039|     r'C:\cjs\www\root\pub\pov\baseball',
040|     r'C:\cjs\www\root\pub\pov\machine',
041|     r'C:\cjs\www\root\pub\pov\ncc1701',
042|     r'C:\cjs\www\root\pub\pov\planets',
043|     r'C:\cjs\www\root\pub\pov\relativity',
044|     r'C:\cjs\www\root\pub\pov\stars',
045|     r'C:\cjs\www\root\pub\pov\studio',
046|     r'C:\cjs\www\root\pub\pov\tardis',
047|     r'C:\cjs\www\root\pub\pov\theatre',
048|     r'C:\cjs\www\root\pub\pov\xyz',
049|     r'C:\cjs\www\root\pub\pov\var',
050|     r'C:\cjs\www\root\pub\pov\etc',
051| ]
052| 
053| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
054| class ThumbFile (object):
055|     '''Thumbnail File Object class.'''
056|     def __init__ (self, name, order='', caption=''):
057|         self.name = name
058|         self.order = int(order) if order else -1
059|         self.caption = caption
060| 
061|     def __str__ (self):
062|         return 'ThumbFile(%s)' % self.text
063| 
064|     def __call__ (self):
065|         '''Our function is to return our name.'''
066|         return self.name
067| 
068| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
069| class XmlHandlerConfigThumbx (XmlHandlerConfigBase):
070|     '''XML Configuration File Parser class.'''
071| 
072|     class Config (object):
073|         '''XML Configuration Object class.'''
074|         def __init__ (self, name):
075|             self.name = name
076|             self.path = None
077|             self.thumbs = []
078|             self.title = None
079|             self.h1 = None
080|             self.h2 = None
081|             self.h3 = None
082|             self.descr = None
083|             self.columns = 4
084|             self.twidth = 200
085|             self.imgstyle = ''
086|             self.capstyle = ''
087|             self.refresh = False
088|             self.reverse = False
089|         def __str__ (self): return 'Config(%s)' % self.name
090|         def __call__ (self): return self.path
091|         def set_property (self, prop):
092|             if prop.name == 'path': self.path = prop.value; return
093|             if prop.name == 'title': self.title = prop.value; return
094|             if prop.name == 'h1': self.h1 = prop.value; return
095|             if prop.name == 'h2': self.h2 = prop.value; return
096|             if prop.name == 'h3': self.h3 = prop.value; return
097|             if prop.name == 'descr': self.descr = prop.value; return
098|             if prop.name == 'columns': self.columns = int(prop.value); return
099|             if prop.name == 'twidth': self.twidth = int(prop.value); return
100|             if prop.name == 'imgstyle': self.imgstyle = prop.value; return
101|             if prop.name == 'capstyle': self.capstyle = prop.value; return
102|             if prop.name == 'refresh': self.refresh = IsTrue(prop.value); return
103|             if prop.name == 'reverse': self.reverse = IsTrue(prop.value); return
104|         def find_thumb (self, name):
105|             n = name.lower()
106|             for t in self.thumbs:
107|                 if t.name.lower() == n:
108|                     Log.debug('matched: %s' % name)
109|                     return t
110|             return None
111| 
112|     def __init__ (self, name, fout=stdout, log=None):
113|         XmlHandlerConfigBase.__init__(self, name, fout, log)
114|         self.curr_thumb = None
115| 
116|     def new_config_object (self, name):
117|         return XmlHandlerConfigThumbx.Config(name)
118| 
119|     def localStart (self, name, attrs):
120|         '''Handle the parts of the XML config file that matter to us.'''
121|         # <Configuration> elements...
122|         if self.state == 100:
123|             # <info>...
124|             if name == 'info':
125|                 self.state = 101
126|                 return
127|             # <files>...
128|             if name == 'files':
129|                 reverse_order = self.get_attribute(attrs,'reverse')
130|                 if 0 < len(reverse_order):
131|                     self.curr_config.reverse = int(reverse_order)
132|                 self.state = 102
133|                 return
134|             return
135|         # <info> children: multiple <property> elements...
136|         if self.state == 101:
137|             if name == 'property':
138|                 attr_name = self.get_attribute(attrs,'name')
139|                 attr_value = self.get_attribute(attrs,'value')
140|                 attr_dtype = self.get_attribute(attrs,'type')
141|                 prop = Property(attr_name, attr_value, attr_dtype)
142|                 self.curr_config.set_property(prop)
143|                 self.state = 101
144|             return
145|         # <files>...
146|         if self.state == 102:
147|             if name == 'thumb':
148|                 attr_name = self.get_attribute(attrs,'name')
149|                 attr_order = self.get_attribute(attrs,'order')
150|                 self.curr_thumb = ThumbFile(attr_name, attr_order)
151|                 self.state = 103
152|             return
153|         # Let the parent handle any other states...
154|         XmlHandlerConfigBase.localStart(self, name, attrs)
155| 
156|     def localEnd (self, name):
157|         # </info...
158|         if self.state == 101:
159|             if name == 'info':
160|                 self.state = 100
161|             return
162|         # </files>...
163|         if self.state == 102:
164|             if name == 'files':
165|                 self.state = 100
166|             return
167|         # </thumb>...
168|         if self.state == 103:
169|             if name == 'thumb':
170|                 self.curr_thumb.text = self.text
171|                 self.curr_config.thumbs.append(self.curr_thumb)
172|                 self.state = 102
173|             return
174|         # Let the parent handle any other states...
175|         XmlHandlerConfigBase.localEnd(self, name)
176| 
177| 
178| ##================================================================================================##
179| def generate_thumb_files (cfg):
180|     '''Generate a set of thumbnail files using parameters from a Configuration object.'''
181|     Log.info('Config: %s' % cfg.name)
182|     Log.info('> path=%s' % cfg.path)
183|     Log.info('> title=%s' % cfg.title)
184|     Log.info('> refresh=%s' % cfg.refresh)
185|     Log.info('> reverse=%s' % cfg.reverse)
186|     Log.debug('> h1=%s' % cfg.h1)
187|     Log.debug('> h2=%s' % cfg.h1)
188|     Log.debug('> h3=%s' % cfg.h3)
189|     for ix,t in enumerate(cfg.thumbs):
190|         Log.trace('> [%3d] %-15s (%d) %s' % (ix, t.name, t.order, t.text))
191|     Log.info()
192| 
193|     # Generate the destination path for the thumbnails...
194|     # (Create the directory if necessary.)
195|     tdir = path.join(cfg.path, 'thumbx') #TODO: 'thumbx' should be a parameter!
196|     if not path.isdir(tdir):
197|         mkdir(tdir)
198| 
199|     # Get a list of files in the directory...
200|     file_names = [(n,path.join(cfg.path,n)) for n in listdir(cfg.path)]
201|     Log.debug('total files found: %d' % len(file_names))
202| 
203|     # Filter the list to get the image files...
204|     file_names = [fn for fn in file_names if FileFilter(fn[1])]
205|     Log.debug('images files found: %d' % len(file_names))
206| 
207|     # Generate a list of items for the index page...
208|     index_list = []
209|     for filename,fullname in file_names:
210|         name,ext = path.splitext(filename)
211|         Log.debug('full: %s' % fullname)
212|         Log.debug('file: %s' % filename)
213|         Log.debug('name: %s' % name)
214| 
215|         seq = 9999
216|         cap = name
217|         if 0 < len(cfg.thumbs):
218|             thumbx = cfg.find_thumb(name)
219|             if thumbx:
220|                 Log.debug('MATCHED: %s' % name)
221|                 seq = thumbx.order
222|                 cap = thumbx.text if thumbx.text else name
223|                 if cap == '#nocap': cap = ''
224| 
225|         # Create the thumbnail images (or not)...
226|         tn = ThumbFilePattern % name
227|         tname = path.join(tdir, tn)
228|         if cfg.refresh or not path.exists(tname): # TODO: Or Opts.refresh !!
229|             im = Image.open(fullname)
230|             if im.mode == 'RGBA':
231|                 im = im.convert(mode='RGB')
232|             im.thumbnail((cfg.twidth,cfg.twidth))
233|             im.save(tname, 'JPEG')
234|             Log.info('SAVE THUMB: %s' % tname)
235|         else:
236|             im = Image.open(tname)
237|             Log.info('load thumb: %s' % tname)
238| 
239|         # Add thumb to the output list...
240|         t = (seq, name, cap, filename, tn, im.size)
241|         index_list.append(t)
242| 
243|     # Sort the list...
244|     index_list.sort(key=lambda t: (t[0], t[1]), reverse=cfg.reverse)
245|     for ix,t in enumerate(index_list):
246|         Log.debug('[%4d] %s' % (ix,t))
247| 
248|     def build_page (pg):
249|         thumbs = list(index_list)
250|         if cfg.descr:
251|             pg.add(cfg.descr)
252|         pg.add('')
253|         pg.add(HtmlListBegin)
254|         # For every image file found, create an index entry...
255|         while 0 < len(thumbs):
256|             pg.add(HtmlListRowBegin)
257|             for cx in range(cfg.columns):
258|                 if 0 < len(thumbs):
259|                     seq, name, cap, fn, tn, sz = thumbs.pop(0)
260|                     # Write item in index...
261|                     t = (fn,tn, sz[0],sz[1], cfg.imgstyle, fn, cfg.capstyle, cap)
262|                     pg.add(HtmlListItem % t)
263|                 else:
264|                     break
265|             pg.add(HtmlListRowEnd)
266|         # We're done...
267|         pg.add(HtmlListEnd)
268|         pg.add('')
269| 
270|     # Save the HTML index file...
271|     fn = path.join(cfg.path, 'index.html')
272|     fp = open(fn, mode='w', encoding='utf-8')
273|     try:
274|         #pw = writer(cfg, index_list)
275|         page = WebPage(cfg.title, h1=cfg.h1, h2=cfg.h2, h3=cfg.h3, css=CssPages)
276|         build_page(page)
277|         page.write(fp)
278|     except:
279|         raise
280|     finally:
281|         fp.close()
282|         Log.info('wrote: %s' % fn)
283| 
284| 
285| ##================================================================================================##
286| def do_main (**kwargs):
287|     '''Do a config file job.'''
288|     xml_filename = KWARG('xml', XmlFileName, str, kwargs)
289|     config_name = KWARG('cfg', 'default', str, kwargs)
290|     Log.info('main:: %s' % str(list(kwargs.keys())))
291|     Log.debug('xml="%s"' % xml_filename)
292|     Log.debug('cfg="%s"' % config_name)
293|     Log.info()
294|     #
295|     cfgs = XmlHandlerConfigThumbx(xml_filename, stdout, Log)
296|     parse_xml_file(xml_filename, cfgs)
297|     Log.info()
298|     #
299|     cfg = cfgs.find_configuration(config_name)
300|     if cfg:
301|         print(cfg)
302|         generate_thumb_files(cfg)
303|     else:
304|         msg = ('Configuration Not Found: "%s"' % config_name)
305|         print('\n%s\n' % msg)
306|         Log.info('\n%s\n' % msg)
307|     #
308|     Log.info()
309|     return 'Done'
310| ##================================================================================================##
311| def do_list (**kwargs):
312|     '''Do a config file listing.'''
313|     xml_filename = KWARG('xml', XmlFileName, str, kwargs)
314|     config_name = KWARG('cfg', 'demo', str, kwargs)
315|     Log.info('list:: %s' % str(list(kwargs.keys())))
316|     Log.debug('xml="%s"' % xml_filename)
317|     Log.debug('cfg="%s"' % config_name)
318|     Log.info()
319|     #
320|     cfgs = XmlHandlerConfigThumbx(xml_filename, stdout, Log)
321|     parse_xml_file(xml_filename, cfgs)
322|     print()
323|     Log.info()
324|     #
325|     for cfg in cfgs:
326|         print('%s: %s' % (cfg.name, cfg.path))
327|         Log.info('%s: %s' % (cfg.name, cfg.path))
328|     print()
329|     #
330|     Log.info()
331|     return 'Done'
332| ##================================================================================================##
333| OutputFormat = ' <thumb order="%03d" name="%s">%s</thumb>'
334| #OutputFormat = ' <thumb order="%03d" name="%s">#nocap</thumb>'
335| #OutputFormat = '<td><img id="img%04d" src="%s"></td>'
336| #OutputFormat = '<div class="Section"><img id="img%d" src="%s"></div>'
337| ##------------------------------------------------------------------------------------------------##
338| def do_make_list (**kwargs):
339|     '''Do a file list for the config file.'''
340|     fout = KWARG('fout', BasePath, str, kwargs)
341|     fdir = KWARG('dir', BasePath, str, kwargs)
342|     Log.info('make-list:: %s' % str(list(kwargs.keys())))
343|     Log.debug('fout="%s"' % fout)
344|     Log.debug('fdir="%s"' % fdir)
345|     Log.info()
346| 
347|     # Get a list of files in the target directory...
348|     files = filefinder(fdir, subs=0)
349|     files.add_exclude_item('index.html')
350|     files.add_exclude_item('puppy.jpg')
351|     files.scan()
352| 
353|     # List files to output...
354|     filename = path.join(fout, 'ls.out')
355|     fp = open(filename, mode='w', encoding='utf-8')
356|     try:
357|         for ix,fn in enumerate(reversed(files)):
358|             bn = path.basename(fn)
359|             ns = path.splitext(bn)
360|             nm = ns[0].replace('_',' ')
361|             print(OutputFormat % (1000+ix, ns[0], nm), file=fp)
362|             #print(OutputFormat % (ix, ns[0]), file=fp)
363|             #print(OutputFormat % (ix, bn), file=fp)
364|         print(file=fp)
365|     except:
366|         raise
367|     finally:
368|         fp.close()
369|         print('wrote: %s' % filename)
370|     #
371|     Log.info()
372|     return 'Done'
373| ##================================================================================================##
374| def do_test (**kwargs):
375|     '''Do a test.'''
376|     xml_filename = KWARG('xml', XmlFileName, str, kwargs)
377|     config_name = KWARG('cfg', 'demo', str, kwargs)
378|     Log.info('test:: %s' % str(list(kwargs.keys())))
379|     Log.debug('xml="%s"' % xml_filename)
380|     Log.debug('cfg="%s"' % config_name)
381|     Log.info()
382|     #
383|     cfgs = XmlHandlerConfigThumbx(xml_filename, stdout, Log)
384|     parse_xml_file(xml_filename, cfgs)
385|     Log.info()
386|     #
387|     cfg = cfgs.find_configuration(config_name)
388|     if cfg:
389|         print('name: %s' % cfg.name)
390|         print('title: %s' % cfg.title)
391|         print('path: %s' % cfg.path)
392|         print('H1: %s' % cfg.h1)
393|         print('H2: %s' % cfg.h2)
394|         print('H3: %s' % cfg.h3)
395|         print('descrip: %s' % cfg.descr)
396|         print('columns: %s' % cfg.columns)
397|         print('t.width: %s' % cfg.twidth)
398|         print('img.style: %s' % cfg.imgstyle)
399|         print('cap.style: %s' % cfg.capstyle)
400|         print('refresh: %s' % cfg.refresh)
401|         print('reverse: %s' % cfg.reverse)
402|         print()
403|         for ix,t in enumerate(cfg.thumbs):
404|             print('%2d: %s' % (ix,t))
405|         print()
406|         Log.info('name: %s' % cfg.name)
407|         Log.info('title: %s' % cfg.title)
408|         Log.info('path: %s' % cfg.path)
409|         Log.info('H1: %s' % cfg.h1)
410|         Log.info('H2: %s' % cfg.h2)
411|         Log.info('H3: %s' % cfg.h3)
412|         Log.info('descrip: %s' % cfg.descr)
413|         Log.info('columns: %s' % cfg.columns)
414|         Log.info('t.width: %s' % cfg.twidth)
415|         Log.info('img.style: %s' % cfg.imgstyle)
416|         Log.info('cap.style: %s' % cfg.capstyle)
417|         Log.info('refresh: %s' % cfg.refresh)
418|         Log.info('reverse: %s' % cfg.reverse)
419|         Log.info()
420|         for ix,t in enumerate(cfg.thumbs):
421|             Log.info('%2d: %s' % (ix,t))
422|         Log.info()
423|     else:
424|         msg = ('Configuration Not Found: "%s"' % config_name)
425|         print('\n%s\n' % msg)
426|         Log.info('\n%s\n' % msg)
427|     #
428|     Log.info()
429|     return 'Done'
430| ####################################################################################################
431| def dispatch (cmd, **kwargs):
432|     '''Dispatch to a module function based on CMD.'''
433|     Log.info('CMD: %s' % cmd)
434|     for kw in kwargs:
435|         Log.debug('argument[%s]: %s' % (kw,kwargs[kw]))
436|     Log.info()
437|     if cmd == 'do': return do_main(**kwargs)
438|     if cmd == 'make': return do_make_list(**kwargs)
439|     if cmd == 'list': return do_list(**kwargs)
440|     if cmd == 'test': return do_test(**kwargs)
441|     return 'Nothing to do!'
442| ####################################################################################################
443| if __name__ == '__main__':
444|     print('autorun: %s' % argv[0])
445|     #Log.start(path.join(BasePath,LogFilenameTimestamp('thumbx_%s.log')))
446|     Log.start(path.join(BasePath,'thumbx.log'))
447|     Log.level(info())
448|     Log.info(argv[0])
449|     Log.info()
450|     cmd = argv[1] if 1 < len(argv) else CMND
451|     kwargs = ARGS
452|     for a in argv[2:]:
453|         nv = a.split('=', 1)
454|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
455|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
456|     try:
457|         print('CMD: %s' % cmd)
458|         print()
459|         obj = dispatch(cmd, **kwargs)
460|         print()
461|         print(obj)
462|         Log.info()
463|         Log.info(obj)
464|     except:
465|         etype, evalue, tb = exc_info()
466|         ts = extract_tb(tb)
467|         Log.error()
468|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
469|         Log.error()
470|         for t in ts[-5:]:
471|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
472|             Log.error(' %s' % t[3])
473|             Log.error()
474|         raise
475|     finally:
476|         Log.end()
477| ####################################################################################################
478| '''eof'''
479|