@fractals.html
001| """Fractals. Utilities for Ultra-Fractal 6.
001|
001| Command:
001| html do_make_images_html_page ~create HTML page for $PICS/Fractals
001| scan do_scan_fractal_files ~generate JSON file from $UF/Fractals
001| parms do_scan_parameter_file ~generate JSON file from $UF/Parameters/<fname>
001| logs do_scan_render_log_files ~scan log files and save certain data
001| parser do_test_uf_parser ~test the Ultra-Fractal parameters parser
001| test do_test ~test
001|
001| """
002|
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from datetime import datetime
007| from json import dump as jsonsave, load as jsonload
008| from PIL import Image
009| from logger import logger,info,debug,trace, LogFilenameTimestamp
010| from goodies import KWARG, typename
011| from files import LF,CR, filefinder, datafile, linefile
012| from webpage import WebPage
013|
014| BasePath = r'C:\CJS\prj\Python\app'
015| PicsPath = r'C:\Users\chris\Pictures\Fractals'
016| FracBase = r'C:\Users\chris\Documents\Ultra Fractal 6'
017| DataPath = path.join(BasePath, 'dat')
018| FracPath = path.join(FracBase, 'Fractals')
019| ParmPath = path.join(FracBase, 'Parameters')
020| Log = logger('Fractals')
021|
022| CMND = ''
023| ARGS = {
024|
025|
026| }
027| OUT = []
028|
029|
030|
031| Example = '''2019-11-08A {
031| fractal:
031| title="2019-11-08 a" width=1600 height=900 layers=1
031| credits="Christopher Sonnack;10/9/2025" antialiasing=yes
031| layer:
031| caption="Background" opacity=100 method=multipass precision=50
031| mapping:
031| center=-0.749998543288645395/0.0023243861136039303 magn=6257189e21
031| angle=139.2494
031| formula:
031| maxiter=10000000 filename="Standard.ufm" entry="Mandelbrot"
031| p_start=0/0 p_power=2/0 p_bailout=128
031| inside:
031| transfer=none
031| outside:
031| transfer=cuberoot filename="Standard.ucl" entry="Smooth" p_power=2/0
031| p_bailout=128.0
031| gradient:
031| comments="Use with Lighting coloring algorithm." smooth=yes index=0
031| color=4521984 index=71 color=8609631 index=200 color=16777215
031| index=300 color=10644530
031| opacity:
031| smooth=no index=0 opacity=255
031| }
031| '''
032|
033|
034| ImagesCss = '''\
034| body {
034| color: black;
034| background-color: white;
034| font-family: "Verdana", "Arial", "Helvetica", sans-serif;
034| font-size: 9pt;
034| font-weight: normal;
034| font-style: normal;
034| line-height: 1.25;
034| text-decoration: none;
034| text-align: left;
034| vertical-align: top;
034| padding: 0;
034| border: 0;
034| margin: 0;
034| }
034| h1 {
034| color: #000000;
034| font-family: "Tahoma", "Verdana", "Arial", "Helvetica", sans-serif;
034| font-size: 18px;
034| font-weight: normal;
034| font-style: normal;
034| line-height: 1.0;
034| text-decoration: none;
034| text-align: left;
034| vertical-align: top;
034| padding: 0;
034| border: 0;
034| margin: 0;
034| }
034| h2 {padding:0; margin:0;}
034| div {padding:0; border:0; margin:0;}
034| #PageHead {
034| background-color: #cccccc;
034| padding: 10px 10px 15px 10px;
034| border-bottom: 2px solid black;
034| margin: 0;
034| }
034| #PageBody {
034| padding: 10px 10px 20px 10px;
034| margin: 0;
034| }
034| #PageFoot {
034| color: #808080;
034| background-color: #e0e0e0;
034| font-family: sans-serif;
034| font-size: xx-small;
034| font-weight: normal;
034| font-style: normal;
034| line-height: 1.0;
034| text-align: center;
034| padding: 4px 20px 6px 20px;
034| border-top: 3px solid black;
034| margin: 0;
034| }
034| #PageFoot .Lt {
034| float: left;
034| text-align: left;
034| }
034| #PageFoot .Rt {
034| float: right;
034| text-align: right;
034| }
034| #PageBody table {
034| font-size: 10px;
034| line-height: 1.0;
034| border-spacing: 0;
034| padding: 0;
034| border: 2px solid black;
034| margin: 10px;
034| }
034| #PageBody table tbody th {
034| color: #ffffff;
034| background-color: #000000;
034| font-size: 16px;
034| font-weight: bold;
034| text-align: center;
034| padding: 20px 5px 12px 5px;
034| }
034| #PageBody table tbody td {
034| text-align: center;
034| vertical-align: top;
034| }
034| #PageBody table tbody td div.Image {
034| text-align: center;
034| vertical-align: top;
034| border: 1px solid black;
034| margin: 3px 0;
034| }
034| #PageBody table tbody td div.Title {
034| font-family: sans-serif;
034| font-size: 12px;
034| text-align: center;
034| padding: 7px 5px 3px 5px;
034| }
034| #PageBody table tbody td div.Extra {
034| text-align: left;
034| padding: 3px 5px 7px 5px;
034| }
034| #PageBody table tbody td img {
034| padding: 0;
034| border: 0;
034| margin: 0;
034| }
034| '''
035| ImagesMainDiv = '''\
035| <div>
035| <div class="Image">{}</div>
035| <div class="Title">{}</div>
035| <div class="Extra">{}</div>
035| </div>
035| '''
036| ImagesImageDiv = '<a target="POVIMG" href="{0}"><img src="{1}" width="{2}"></a>'
037|
038|
039|
040| class FractalInfo (dict):
041| '''Subclassed dictionary for Fractal Information.'''
042|
043| Filename1 = path.join(PicsPath, 'Fractals.json')
044| Filename2 = path.join(PicsPath, 'Parameters.json')
045| DontUse = ['version', 'date-created', 'date-modified', 'comment']
046|
047| def __init__ (self):
048| '''New instance.'''
049|
050|
051| fn = type(self).Filename1
052| fp = open(fn, mode='r', encoding='utf8')
053| try:
054| data = jsonload(fp)
055| except:
056| raise
057| else:
058| Log.info(f'read: {fn}')
059| Log.info()
060| finally:
061| fp.close()
062|
063|
064| for key in data:
065| if key in type(self).DontUse:
066| continue
067| self[key] = {n:v for n,v in data[key].items()}
068|
069|
070| fn = type(self).Filename2
071| fp = open(fn, mode='r', encoding='utf8')
072| try:
073| data = jsonload(fp)
074| Log.info(f'read: {fn}')
075| Log.info()
076| except:
077| raise
078| finally:
079| fp.close()
080|
081|
082| for key in data:
083| if key in type(self).DontUse:
084| continue
085| if key in self:
086| Log.warn(f'Duplicate key ({key}) in Parameters.')
087| self[key] = {n:v for n,v in data[key].items()}
088|
089| def __missing__ (self, ix):
090| '''Look, Ma! No errors!'''
091| return None
092|
093| def __repr__ (self):
094| '''Debug string.'''
095| return f'<{typename(self)} @{id(self):08x}>'
096|
097|
098|
099| def filename_to_keyname (filename):
100| bname = path.basename(filename)
101| parts = path.splitext(bname)
102| return parts[0]
103|
104|
105| def ultra_fractal_properties_parser (text:str) -> dict:
106| '''Parse an Ultra-Fractal properties section.'''
107| props = dict()
108| state = 'initial'
109| tbuf = []
110| gbuf = {}
111|
112| for char in text:
113| Log.trace(f'{char=}, {state=}')
114|
115| match state:
116| case 'initial':
117| if char == '{':
118|
119| props['name'] = ''.join(tbuf)
120| state = 'body'
121| elif char.isspace():
122| props['name'] = ''.join(tbuf)
123| state = 'headspace'
124| else:
125| tbuf.append(char)
126|
127| case 'headspace':
128| if char == '{':
129|
130| state = 'body'
131| else:
132|
133| if not char.isspace():
134| raise SyntaxError(f'Unexpected character in headspace: "{char}"')
135|
136| case 'body':
137| if char == '}':
138|
139| state = 'endbody'
140| else:
141|
142| if not char.isspace():
143|
144| tbuf = [char]
145| state = 'bodytext'
146|
147| case 'bodytext':
148| if char == '"':
149|
150| state = 'quoted'
151| elif char == '\\':
152| state = 'wrapped.start'
153| else:
154| if char.isspace():
155| txt = ''.join(tbuf)
156|
157| if txt.endswith(':'):
158| txt = txt[0:-1]
159| Log.trace(f'Section-Name: {txt}')
160| gbuf = {}
161| props[txt] = gbuf
162| else:
163| name,_,value = txt.partition('=')
164| gbuf[name] = value
165| state = 'body'
166| else:
167| tbuf.append(char)
168|
169| case 'quoted':
170| if char == '"':
171| state = 'bodytext'
172| else:
173| tbuf.append(char)
174|
175| case 'wrapped.start':
176| if char not in [CR, LF]:
177| raise SyntaxError(f'Unexpected char following backslash: "{char}"')
178| state = 'wrapped'
179|
180| case 'wrapped':
181| if not char.isspace():
182| tbuf.append(char)
183| state = 'bodytext'
184|
185| case 'endbody':
186| ...
187|
188| case _:
189| raise RuntimeError(f'Unexpected state: {state}')
190|
191| return props
192|
193|
194|
195| def do_scan_fractal_files (**kwargs):
196| '''CMND: Scan the UF Fractal files and generate a JSON output.'''
197| dpath = KWARG('dpath', FracPath, str, kwargs)
198| fpath = KWARG('fpath', PicsPath, str, kwargs)
199| fname = KWARG('fname', 'Fractals.json', str, kwargs)
200| Log.info('scan-UF-fractal-files:: %s' % str(list(kwargs.keys())))
201| Log.debug(f'{dpath=}')
202| Log.debug(f'{fpath=}')
203| Log.debug(f'{fname=}')
204| Log.info()
205| jsonfilename = path.join(fpath,fname) if fpath else fname
206|
207|
208| ff = filefinder(dpath)
209| ff.add_include_item(r'\.ufr$')
210| ff.scan()
211| if not ff:
212| Log.info(f'No files found in "{dpath}"')
213| return (ff, [])
214| OUT.append(ff)
215|
216| json = {
217| "version":1,
218| "date-created":datetime.now().ctime()
219| }
220| OUT.append(json)
221|
222| for ix,filename in enumerate(ff, start=1):
223| Log.info(f'{ix}: {filename}')
224|
225|
226| fin = datafile(filename)
227| fin.load()
228|
229|
230| prefix = fin[0:64]
231|
232|
233| buf = []
234| text_ptr = 64
235| while 0 < fin[text_ptr]:
236| buf.append(chr(fin[text_ptr]))
237| text_ptr += 1
238|
239|
240| fractal_properties = ultra_fractal_properties_parser(''.join(buf))
241| fractal_properties['filename'] = filename
242| fractal_properties['prefix'] = prefix.hex('.')
243|
244| json[filename_to_keyname(filename)] = fractal_properties
245|
246|
247| jfile = open(jsonfilename, mode='w', encoding='utf8')
248| try:
249| jsonsave(json, jfile, indent=4)
250| except:
251| raise
252| else:
253| Log.info(f'wrote: {jsonfilename}')
254| Log.info()
255| finally:
256| jfile.close()
257|
258| Log.info()
259| return 'Done'
260|
261|
262| def do_scan_parameter_file (**kwargs):
263| '''CMND: Scan a UF Parameter file and generate a JSON output.'''
264| dpath = KWARG('dpath', ParmPath, str, kwargs)
265| dname = KWARG('dname', 'My Fractals.upr', str, kwargs)
266| fpath = KWARG('fpath', PicsPath, str, kwargs)
267| fname = KWARG('fname', 'Parameters.json', str, kwargs)
268| Log.info('scan-UF-parameter-file:: %s' % str(list(kwargs.keys())))
269| Log.debug(f'{dpath=}')
270| Log.debug(f'{dname=}')
271| Log.debug(f'{fpath=}')
272| Log.debug(f'{fname=}')
273| Log.info()
274| infilename = path.join(dpath,dname) if dpath else dname
275| jsonfilename = path.join(fpath,fname) if fpath else fname
276|
277| json = {
278| "version":1,
279| "date-created":datetime.now().ctime()
280| }
281| OUT.append(json)
282|
283|
284| fin = linefile(infilename)
285| fin.load()
286| Log.info(f'loaded: {infilename}')
287| Log.info()
288|
289| buf = []
290| state = 'alpha'
291| for line in fin:
292| Log.trace(line)
293|
294| match state:
295| case 'alpha':
296| if len(line) == 0:
297| continue
298| if line.endswith('{'):
299| buf = [line]
300| state = 'body'
301| continue
302| raise RuntimeError(f'Unexpected body text: "{line}"')
303|
304| case 'body':
305| buf.append(line)
306| if line.startswith('}'):
307| text = '\n'.join(buf)
308| params = ultra_fractal_properties_parser(text)
309| Log.trace(params)
310|
311| name = params['name']
312| if name != 'comment':
313|
314| title = params['fractal']['title']
315| params['filename'] = path.join(PicsPath, f'{title}.png')
316|
317|
318| json[name] = params
319|
320| state = 'alpha'
321| continue
322|
323| case _:
324| raise RuntimeError(f'Unexpected state: {state}')
325|
326| Log.trace()
327| Log.trace(json)
328| assert state == 'alpha', RuntimeError(f'Finished in wrong state: "{state}"')
329|
330| jfile = open(jsonfilename, mode='w', encoding='utf8')
331| try:
332| jsonsave(json, jfile, indent=4)
333| except:
334| raise
335| else:
336| Log.info(f'wrote: {jsonfilename}')
337| Log.info()
338| finally:
339| jfile.close()
340|
341| Log.info()
342| return 'Done'
343|
344|
345| def do_make_images_html_page (**kwargs):
346| '''CMND: create an HTML index page for fractal images.'''
347| fpath = KWARG('fpath', PicsPath, str, kwargs)
348| fname = KWARG('fname', 'index.html', str, kwargs)
349| width = KWARG('width', 350, int, kwargs)
350| ncols = KWARG('ncols', 5, int, kwargs)
351| Log.info('make-images-html-page:: %s' % str(list(kwargs.keys())))
352| Log.debug(f'{fpath=}')
353| Log.debug(f'{fname=}')
354| Log.debug(f'{width=}')
355| Log.debug(f'{ncols=}')
356| Log.info()
357|
358| fractals_info = FractalInfo()
359| OUT.append(fractals_info)
360| for key in fractals_info:
361| if 'filename' not in fractals_info[key]:
362| Log.error(f'{key}: No Filename!')
363| continue
364| Log.trace(f'{key}: {fractals_info[key]["filename"]}')
365| Log.trace()
366|
367|
368| f = lambda k: path.splitext(path.basename(fractals_info[k]['filename']))[0]
369| frac_list = {f(key):key for key in fractals_info}
370| Log.debug(frac_list)
371| Log.debug()
372|
373|
374| ff = filefinder(fpath)
375| ff.add_include_item(r'\.png$')
376| ff.add_include_item(r'\.jpg$')
377| ff.add_include_item(r'\.gif$')
378| ff.add_include_item(r'\.bmp$')
379| ff.add_exclude_folder('Thumbnails')
380| ff.scan()
381| if not ff:
382| Log.info(f'No files found in "{fpath}"')
383| return 'No files'
384| OUT.append(ff)
385|
386| props = dict(h1=fpath, h2='', h3='', csstxt=ImagesCss)
387| pg = WebPage('Fractals', **props)
388|
389|
390| pg.add()
391| pg.add('<table>')
392| pg.add('<tbody>')
393|
394| currpath = fpath
395| column = 0
396| pg.add('<tr>')
397| for ix,filename in enumerate(ff, start=1):
398| Log.info(f'{ix}: {filename}')
399| img_fpath,img_fname = path.split(filename)
400| img_name,img_ext = path.splitext(img_fname)
401|
402| img = Image.open(filename)
403| Log.trace(img.info)
404| img_width = img.width
405| img_height = img.height
406|
407| img.thumbnail((width,width), resample=Image.Resampling.LANCZOS)
408| thumb_width = img.width
409| thumb_height = img.height
410| thumb_filename = path.join(fpath, 'Thumbnails', img_fname)
411| img.save(thumb_filename)
412|
413| fracstats = fractals_info[img_name]
414| if fracstats is None:
415| fracstats = fractals_info[img_name.replace(' ','_')]
416| Log.debug(fracstats)
417|
418| if fracstats is not None:
419| section = fracstats['mapping']
420|
421| center = section['center']
422| parts = center.split('/')
423| x = parts[0][:25]
424| y = parts[1][:25]
425| if not x.startswith('-'):
426| x = f'+{x}'
427| if not y.startswith('-'):
428| y = f'+{y}'
429|
430| magn = section['magn'].lower()
431| xtra = f'x: {x}<br>y: {y}<br>magnification: {magn}'
432|
433| if 'angle' in section:
434| angle = section['angle']
435| xtra += f'<br>angle: {angle}'
436| else:
437| xtra = f''
438|
439| image_fpath = path.dirname(filename)
440| if image_fpath != currpath:
441| pg.add()
442| pg.add('</tr>')
443| pg.add(f'<tr><th colspan="{ncols}">{image_fpath}</th></tr>')
444| pg.add('<tr>')
445| pg.add()
446| currpath = image_fpath
447| column = 0
448|
449| cell = ImagesImageDiv.format(filename, thumb_filename, thumb_width)
450| name = f'<strong>{img_name}</strong> [{img_width}×{img_height}]'
451| pg.add(f'<td>{ImagesMainDiv.format(cell, name, xtra)}</td>')
452|
453| column += 1
454| if ncols <= column:
455| pg.add()
456| pg.add('</tr><tr>')
457| pg.add()
458| column = 0
459|
460| pg.add('</tr>')
461| Log.info()
462|
463| pg.add('</tbody>')
464| pg.add('</table>')
465|
466| outfile = path.join(fpath,fname) if fpath else fname
467| pg.save(outfile)
468| Log.info(f'wrote: {outfile}')
469| Log.info()
470| return 'Done'
471|
472|
473| def do_scan_render_log_files (**kwargs):
474| '''CMND: Scan log files from render and save certain data.'''
475| dpath = KWARG('dpath', PicsPath, str, kwargs)
476| fpath = KWARG('fpath', DataPath, str, kwargs)
477| fname = KWARG('fname', 'render-logs.json', str, kwargs)
478| Log.info('scan-render-logs:: %s' % str(list(kwargs.keys())))
479| Log.debug(f'{dpath=}')
480| Log.debug(f'{fpath=}')
481| Log.debug(f'{fname=}')
482| Log.info()
483|
484| jsonfilename = path.join(fpath,fname) if fpath else fname
485| jfile = open(jsonfilename, mode='r', encoding='utf8')
486| try:
487| json = jsonload(jfile)
488| except:
489| raise
490| else:
491| Log.info(f'read: {jsonfilename}')
492| Log.info()
493| finally:
494| jfile.close()
495|
496|
497| ff = filefinder(dpath)
498| ff.add_include_item(r'\.log$')
499| ff.scan()
500| if not ff:
501| Log.info(f'No files found in "{dpath}"')
502| return (ff, [])
503| OUT.append(ff)
504|
505|
506|
507| for ix,filename in enumerate(ff, start=1):
508| Log.info(f'{ix}: {filename}')
509| name,_ = path.splitext(path.basename(filename))
510|
511| if name in json:
512| jrecord = json[name]
513| else:
514| jrecord = {"file":'', "time":[]}
515|
516|
517| fin = linefile(filename)
518| fin.load()
519|
520|
521| for line in fin:
522| Log.trace(line)
523|
524| if 'Calculating ' in line:
525| cx = line.index('Calculating ')
526| img_filename = line[cx+12:-1]
527| Log.trace(f'file: {img_filename}')
528| if jrecord['file']:
529| if img_filename != jrecord['file']:
530| Log.error('Filename mismatch!')
531| Log.error(f'from logs: {img_filename}')
532| Log.error(f'from json: {jrecord["file"]}')
533| Log.error()
534| else:
535| jrecord['file'] = img_filename
536| continue
537|
538| if 'Finished calculation. ' in line:
539| cx = line.index('Time: ')
540| elapsed_time = line[cx+6:-1]
541| jrecord['time'].append(elapsed_time)
542| Log.trace(f'time: {elapsed_time}')
543| continue
544| Log.trace()
545|
546| jfile = open(jsonfilename, mode='w', encoding='utf8')
547| try:
548| jsonsave(json, jfile, indent=4, separators=(', ', ':'), sort_keys=True)
549| except:
550| raise
551| else:
552| Log.info(f'wrote: {jsonfilename}')
553| Log.info()
554| finally:
555| jfile.close()
556|
557| Log.info()
558| return 'Done'
559|
560|
561| def do_test_uf_parser (**kwargs):
562| '''CMND: Test the Ultra-Fractal parameters parser.'''
563| fpath = KWARG('fpath', BasePath, str, kwargs)
564| fname = KWARG('fname', 'parser.out', str, kwargs)
565| Log.info('test-ultra-fractal-parser:: %s' % str(list(kwargs.keys())))
566| Log.debug(f'{fpath=}')
567| Log.debug(f'{fname=}')
568| Log.info()
569|
570| fractal_properties = ultra_fractal_properties_parser(Example)
571|
572| Log.info(f'[[{fractal_properties["name"]}]]')
573| Log.info()
574|
575| for secname,secitems in fractal_properties.items():
576| if isinstance(secitems,dict):
577| Log.info(f'[{secname}]')
578|
579| for nam,val in secitems.items():
580| Log.info(f'{nam}: {val}')
581| Log.info()
582|
583| OUT.append(fractal_properties)
584|
585| Log.info()
586| return 'Done'
587|
588|
589| def do_test (**kwargs):
590| '''CMND: Do a test.'''
591| fpath = KWARG('fpath', BasePath, str, kwargs)
592| fname = KWARG('fname', 'test.out', str, kwargs)
593| Log.info(f'test:: {list(kwargs.keys())}')
594| Log.debug(f'{fpath=}')
595| Log.debug(f'{fname=}')
596| Log.info()
597| Log.info()
598| return 'Done'
599|
600| def dispatch (cmd, **kwargs):
601| '''Dispatch to a module function based on CMD.'''
602| Log.info(f'CMD: {cmd}')
603| for kw in kwargs:
604| Log.debug(f'argument[{kw}]: {kwargs[kw]}')
605| Log.info()
606| if cmd == 'html': return do_make_images_html_page(**kwargs)
607| if cmd == 'scan': return do_scan_fractal_files(**kwargs)
608| if cmd == 'parms': return do_scan_parameter_file(**kwargs)
609| if cmd == 'logs': return do_scan_render_log_files(**kwargs)
610| if cmd == 'parser': return do_test_uf_parser(**kwargs)
611| if cmd == 'test': return do_test(**kwargs)
612| return 'Nothing to do!'
613|
614| if __name__ == '__main__':
615| print(f'autorun: {argv[0]}')
616| Log.start(path.join(BasePath,'fractals.log'))
617| Log.level(info())
618| Log.info(argv[0])
619| Log.info()
620| cmd = argv[1] if 1 < len(argv) else CMND
621| kwargs = ARGS
622| for a in argv[2:]:
623| nv = a.split('=', 1)
624| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
625| Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
626| try:
627| print(f'CMD: {cmd}')
628| print()
629| obj = dispatch(cmd, **kwargs)
630| print()
631| print(obj)
632| Log.info()
633| Log.info(obj)
634| except:
635| etype, evalue, tb = exc_info()
636| ts = extract_tb(tb)
637| Log.error()
638| Log.error(f'{etype.__name__}: {evalue!s}')
639| Log.error()
640| for t in ts[-5:]:
641| Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
642| Log.error(f' {t[3]}')
643| Log.error()
644| raise
645| finally:
646| Log.end()
647|
648| '''eof'''
649|