@misc.html


001| """Miscellaneous App fragments.
001| 
001| Commands:
001|     words       do_word_counter                 ~Count words in text
001|     walk        do_going_for_a_walk             ~Determine MPH of a local walk
001|     dotw        do_get_weekday_list             ~Get list of DOTW-DOTM dates
001|     wells       do_wells_fargo_checking         ~Checking account chart
001|     401k        do_401k_chart                   ~401-K account chart
001|     spam        do_spam_counts                  ~Email spam statistics
001|     colors      do_image_colors_histogram       ~RGB histogram of an image file
001|     alpha       do_alpha_frequency_chart        ~Create an alphabet frequency histogram
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, listdir
006| from datetime import date, timedelta
007| import matplotlib.pyplot as plt
008| import matplotlib.ticker as mlticks
009| import matplotlib.dates as mldates
010| from PIL import Image
011| from logger import logger,info,debug,trace, LogFilenameTimestamp
012| from goodies import KWARG
013| from files import csvfile
014| from randtext import UCX, AlphaFreqs
015| ####################################################################################################
016| BasePath = r'C:\CJS\prj\Python\app'
017| DataPath = path.join(BasePath, 'dat')
018| ImgsPath = path.join(BasePath, 'img')
019| Log = logger('misc')
020| Now = date.today()
021| 
022| CMND = ''
023| ARGS = {
024|     #'walk': 'Lion Loop',
025|     #'mins': '45',
026|     #'secs': '42',
027|     #'wday': '4',
028|     #'mday': '13',
029|     #'year': '2026',
030|     #'iname': r"C:\CJS\prj\Python\ws\PIL\strawberries-1.jpg",
031|     #'opath': BasePath,
032|     #'roff': '50000',
033|     #'fname': 'misc.dat',
034|     #'fpath': path.join(BasePath, 'baseball'),
035|     #'dpath': path.join(BasePath, 'baseball'),
036| }
037| 
038| ##================================================================================================##
039| def do_word_counter (**kwargs):
040|     """CMND: Count words in text."""
041|     dpath = KWARG('dpath', BasePath, str, kwargs)
042|     fpath = KWARG('fpath', BasePath, str, kwargs)
043|     fname = KWARG('fname', 'words.out', str, kwargs)
044|     Log.info(f'word-counter:: {list(kwargs.keys())}')
045|     Log.debug(f'{dpath=}')
046|     Log.debug(f'{fpath=}')
047|     Log.debug(f'{fname=}')
048|     Log.info()
049| 
050|     filenames = [path.join(dpath,name) for name in listdir(dpath) if name.endswith('.py')]
051| 
052|     tot_files = 0
053|     tot_bytes = 0
054|     tot_lines = 0
055|     tot_words = 0
056|     word_buffer = []
057|     words = {}
058| 
059|     for ix,filename in enumerate(filenames, start=1):
060|         Log.debug(f'{ix:3d}: {filename}')
061| 
062|         tot_files += 1
063|         tot_bytes += path.getsize(filename)
064| 
065|         fp = open(filename, mode='r', encoding='utf-8')
066|         try:
067|             state = 0
068|             for ch in fp.read():
069|                 # Newline...
070|                 if ch == '\n':
071|                     tot_lines += 1
072|                     if state == 1:
073|                         tot_words += 1
074|                         w = ''.join(word_buffer)
075|                         if w not in words: words[w] = 0
076|                         words[w] += 1
077|                         word_buffer = []
078|                         state = 0
079|                     continue
080|                 # Space...
081|                 if (ch == ' ') or not ch.isalnum():
082|                     if state == 1:
083|                         tot_words += 1
084|                         w = ''.join(word_buffer)
085|                         if w not in words: words[w] = 0
086|                         words[w] += 1
087|                         word_buffer = []
088|                         state = 0
089|                     continue
090|                 # Character...
091|                 state = 1
092|                 word_buffer.append(ch)
093| 
094|         except:
095|             raise
096|         finally:
097|             fp.close()
098| 
099|     # (loop done)
100|     Log.debug()
101| 
102|     # Write results to a file...
103|     fn = path.join(fpath,fname) if fpath else fname
104|     fp = open(fn, mode='w', encoding='utf-8')
105|     try:
106|         print(f'Total Files: {tot_files:,}', file=fp)
107|         print(f'Total Bytes: {tot_bytes:,}', file=fp)
108|         print(f'Total Lines: {tot_lines:,}', file=fp)
109|         print(f'Total Words: {tot_words:,}', file=fp)
110|         print(file=fp)
111| 
112|         for ix,filename in enumerate(filenames, start=1):
113|             print(f'{ix:03d}: {filename}', file=fp)
114|         print(file=fp)
115| 
116|         for ix,w in enumerate(sorted(words), start=1):
117|             print(f'{ix:3d}: {w}', file=fp)
118|         print(file=fp)
119| 
120|         Log.info(f'wrote: {fn}')
121|         print(f'wrote: {fn}')
122|     except:
123|         raise
124|     finally:
125|         fp.close()
126| 
127|     Log.info()
128|     return 'Done'
129| ##================================================================================================##
130| def do_going_for_a_walk (**kwargs):
131|     '''CMND: Determine MPH of a local walk.'''
132|     walk = KWARG('walk', 'Middle Loop', str, kwargs)
133|     mins = KWARG('mins', 30, int, kwargs)
134|     secs = KWARG('secs', 0, int, kwargs)
135|     Log.info(f'going-for-a-walk:: {list(kwargs.keys())}')
136|     Log.debug(f'{walk=}')
137|     Log.debug(f'{mins=}')
138|     Log.debug(f'{secs=}')
139|     Log.info()
140| 
141|     Mileage = {
142|         'Middle Loop':  1.82,
143|         'SW Loop 1':    2.37,   # uses trail from 75th to 70th
144|         'SW Loop 2':    2.36,   # uses Bester to 73rd street
145|         'SW Loop 3':    2.37,   # all the way back to Blaine
146|         'SE Loop':      1.89,
147|         'Lion Loop':    2.46,
148|     }
149|     def minutes_to_hours (mins, secs):
150|         '''Convert minutes and seconds to hours.'''
151|         return ((mins/60.0) + (secs/3600.0))
152| 
153|     def miles_per_hour (walk, mins, secs):
154|         '''Determine speed of walk in MPH.'''
155|         hours = minutes_to_hours(mins, secs)
156|         return (Mileage[walk] / hours)
157| 
158|     mph = miles_per_hour(walk, mins, secs)
159|     print()
160|     print(f'{walk}: {mph:.3f} MPH ({Mileage[walk]} miles in {mins}:{secs:02d} mins)')
161|     print()
162|     input('Press [Enter] to continue...')
163|     print()
164| 
165|     Log.info()
166|     return 'Done'
167| 
168| ##================================================================================================##
169| def do_get_weekday_list (**kwargs):
170|     """CMND: Get a list of month dates (DOTM) that fall on a given weekday (DOTW)."""
171|     fpath = KWARG('fpath', BasePath, str, kwargs)
172|     fname = KWARG('fname', 'dotm-dotw.list', str, kwargs)
173|     dotw  = KWARG('wday', 0, int, kwargs)
174|     dotm  = KWARG('mday', 0, int, kwargs)
175|     year  = KWARG('year', Now.year, int, kwargs)
176|     Log.info(f'get-weekday-list:: {list(kwargs.keys())}')
177|     Log.debug(f'{fpath=}')
178|     Log.debug(f'{fname=}')
179|     Log.debug(f'{dotw=}')
180|     Log.debug(f'{dotm=}')
181|     Log.debug(f'{year=}')
182|     Log.info()
183|     one_day = timedelta(1.0)
184| 
185|     result = []
186|     dt = date(year,1,1)
187| 
188|     # Loop through the days of the year...
189|     while dt.year == year:
190| 
191|         # If it's the sought weekday...
192|         if dt.weekday() == dotw:
193| 
194|             # If we don't care about dates...
195|             if dotm == 0:
196|                 # Append matching weekday regardless...
197|                 result.append(dt)
198|             # Otherwise check the date...
199|             elif dt.day == dotm:
200|                 # Append only if it's the sought date...
201|                 result.append(dt)
202| 
203|         # Next day of the year...
204|         dt = dt + one_day
205| 
206|     # List what we found...
207|     for ix,dt in enumerate(result, start=1):
208|         s = f'{ix:2d}: {dt:%a %d (%b)}'
209|         print(s)
210|         Log.info(s)
211|     print()
212|     Log.info()
213| 
214|     return 'Done'
215| 
216| ##================================================================================================##
217| def do_wells_fargo_checking (**kwargs):
218|     """CMND: Generate chart for Wells Fargo checking account."""
219|     ipath = KWARG('ipath', DataPath, str, kwargs)
220|     iname = KWARG('iname', 'wellfarg.in', str, kwargs)
221|     opath = KWARG('opath', ImgsPath, str, kwargs)
222|     oname = KWARG('oname', 'wellfarg.png', str, kwargs)
223|     ymin  = KWARG('ymin', 10.0, float, kwargs)
224|     ymax  = KWARG('ymax', 80.0, float, kwargs)
225|     Log.info(f'checking-account-chart:: {list(kwargs.keys())}')
226|     Log.debug(f'{ipath=}')
227|     Log.debug(f'{iname=}')
228|     Log.debug(f'{opath=}')
229|     Log.debug(f'{oname=}')
230|     Log.info()
231|     data_filename = path.join(ipath,iname) if ipath else iname
232|     chart_filename = path.join(opath,oname) if opath else oname
233| 
234|     xmin, xmax = date(2017,1,1), date(2027,1,1)
235| 
236|     fo = csvfile(data_filename)
237|     fo.load()
238|     fo.delete_blank_lines()
239| 
240|     data = [(date(int(t[0]),int(t[1]),int(t[2])), int(t[3])) for t in reversed(fo)]
241| 
242|     dts  = [rcd[0] for rcd in data]
243|     amts = [rcd[1]/1000 for rcd in data]
244| 
245|     # Create Chart...
246|     fig, ax = plt.subplots()
247|     fig.set_figwidth(12.0)
248|     fig.set_figheight(5.0)
249|     fig.subplots_adjust(left=0.05, right=0.99, bottom=0.15, top=0.94)
250|     fig.suptitle('Wells Fargo Checking Account', fontweight='bold')
251| 
252|     ax.set_xlabel('Month-Year')
253|     ax.xaxis_date()
254|     ax.set_xlim(xmin, xmax)
255|     ax.xaxis.set_major_locator(mldates.MonthLocator(bymonth=(1,4,7,10)))
256|     ax.xaxis.set_minor_locator(mldates.MonthLocator())
257|     ax.xaxis.set_major_formatter(mldates.DateFormatter('%m-%y'))
258| 
259|     for tick in ax.xaxis.get_major_ticks():
260|         tick.label1.set_rotation('vertical')
261|         tick.label1.set_size(9)
262| 
263|     ax.set_ylabel('Amount (thousands)')
264|     ax.set_ylim(ymin, ymax)
265|     ax.yaxis.set_major_locator(mlticks.MultipleLocator(10))
266|     ax.yaxis.set_minor_locator(mlticks.MultipleLocator(1))
267|     ax.yaxis.set_major_formatter(mlticks.FormatStrFormatter('%dK'))
268| 
269|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
270|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
271|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
272|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
273| 
274|     ax.plot(dts,amts, color='red', lw=3.0, alpha=0.8, zorder=11)
275| 
276|     fig.savefig(chart_filename)
277|     Log.info(f'wrote: {chart_filename}')
278|     Log.info()
279|     return 'Done'
280| 
281| ##================================================================================================##
282| def do_401k_chart (**kwargs):
283|     """CMND: Generate chart for 401-K account."""
284|     ipath = KWARG('ipath', DataPath, str, kwargs)
285|     iname = KWARG('iname', '401k.in', str, kwargs)
286|     opath = KWARG('opath', ImgsPath, str, kwargs)
287|     oname = KWARG('oname', '401k.png', str, kwargs)
288|     Log.info(f'401K-account-chart:: {list(kwargs.keys())}')
289|     Log.debug(f'{ipath=}')
290|     Log.debug(f'{iname=}')
291|     Log.debug(f'{opath=}')
292|     Log.debug(f'{oname=}')
293|     Log.info()
294|     data_filename = path.join(ipath,iname) if ipath else iname
295|     chart_filename = path.join(opath,oname) if opath else oname
296| 
297|     xs = []
298|     ys = []
299| 
300|     fp = open(data_filename, mode='r', encoding='utf-8')
301|     try:
302|         for txt in fp:
303|             txt = txt.strip()
304|             if txt:
305|                 flds = txt.split('|')
306|                 assert len(flds)==3, RuntimeError('Invalid input line: "%s"' % txt)
307|                 yr = int(flds[0])
308|                 qtr = int(flds[1])-1
309|                 val = int(float(flds[2]) / 1000.0)
310|                 dt = date(yr, 1+(qtr*3), 1)
311|                 xs.append(dt)
312|                 ys.append(val)
313|     except:
314|         raise
315|     finally:
316|         fp.close()
317| 
318|     # Create Chart...
319|     fig, ax = plt.subplots()
320|     fig.set_figwidth(8.0)
321|     fig.set_figheight(6.0)
322|     fig.subplots_adjust(left=0.09, right=0.99, bottom=0.13, top=0.94)
323|     fig.suptitle('401-K', fontweight='bold')
324| 
325|     ax.set_xlabel('Years (by Quarter)')
326|     ax.xaxis_date()
327|     ax.set_xlim(date(2009,1,1), date(2022,4,1))
328|     ax.xaxis.set_major_locator(mldates.YearLocator(1))
329|     ax.xaxis.set_minor_locator(mldates.MonthLocator(bymonth=(4,7,10)))
330|     ax.xaxis.set_major_formatter(mldates.DateFormatter('%Y'))
331| 
332|     for tick in ax.xaxis.get_major_ticks():
333|         tick.label1.set_rotation('vertical')
334|         tick.label1.set_size(9)
335| 
336|     ax.set_ylabel('Fund Amount')
337|     ax.set_ylim(100.0, 600.0)
338|     ax.yaxis.set_major_locator(mlticks.MultipleLocator(100))
339|     ax.yaxis.set_minor_locator(mlticks.MultipleLocator(25))
340|     ax.yaxis.set_major_formatter(mlticks.FormatStrFormatter('%d'))
341| 
342|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
343|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
344|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
345|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
346| 
347|     ax.plot(xs,ys, color='red', lw=3.0, alpha=0.8, zorder=11)
348| 
349|     fig.savefig(chart_filename)
350|     Log.info(f'wrote: {chart_filename}')
351|     Log.info()
352|     return 'Done'
353| 
354| ##================================================================================================##
355| def do_spam_counts (**kwargs):
356|     '''CMND: Email spam statistics.'''
357|     fpath = KWARG('fpath', DataPath, str, kwargs)
358|     fname = KWARG('fname', 'spam-counts.txt', str, kwargs)
359|     Log.info(f'email-spam-statistics:: {list(kwargs.keys())}')
360|     Log.debug(f'{fpath=}')
361|     Log.debug(f'{fname=}')
362|     Log.info()
363| 
364|     # Load daily email spam data...
365|     fn = path.join(fpath,fname) if fpath else fname
366|     fo = csvfile(fn)
367|     fo.load()
368|     Log.debug(f'{len(fo)} lines')
369| 
370|     data = [(date(int(row[0]),int(row[1]),int(row[2])), int(row[3])) for row in fo if 1<len(row)]
371| 
372|     ndays = len(data)
373|     amts = [row[1] for row in data]
374|     total = sum(amts)
375|     avg = total/ndays
376| 
377|     # Maximum and minimum per day...
378|     maxday = max(data, key=lambda x:x[1])
379|     minday = min(data, key=lambda x:x[1])
380| 
381|     # Calculate median...
382|     # Odd: e.g. 9 -> 4,1: [0,1,2,3][4][5,6,7,8]
383|     # Even: e.g. 10 -> 5,0: [0,1,2,3][4,5][6,7,8,9]
384|     xs = sorted(amts)
385|     half,rem = divmod(len(xs), 2)
386|     med = float(xs[half]) if rem else float((xs[half-1]+xs[half]) / 2.0)
387| 
388|     # Calculate month stats...
389|     months = {}
390|     for dt,nbr_emails in data:
391|         key = (dt.year, dt.month)
392|         if key not in months: months[key] = 0
393|         months[key] += nbr_emails
394| 
395|     # Calculate daily count histogram...
396|     histo = {}
397|     for dt,nbr_emails in data:
398|         if nbr_emails not in histo: histo[nbr_emails] = 0
399|         histo[nbr_emails] += 1
400| 
401|     # Write stats to log...
402|     Log.info()
403|     Log.info('SPAM EMAIL REPORT:')
404|     Log.info(f'From {data[0][0]} through {data[-1][0]} ({ndays} days)')
405|     Log.info(f'Total: {total} emails')
406|     Log.info(f'Most: {maxday[1]} on {maxday[0]}')
407|     Log.info(f'Least: {minday[1]} on {minday[0]}')
408|     Log.info(f'Median: {med:.2f}')
409|     Log.info(f'Mean: {avg:.2f}')
410|     Log.info()
411|     Log.info('Monthly Stats:')
412|     for key in sorted(months):
413|         Log.info(f'{key[0]}-{key[1]:2d}: {months[key]:3d}')
414|     Log.info()
415|     Log.info('Daily Count Histogram:')
416|     for nbr_emails in sorted(histo):
417|         Log.info(f'{nbr_emails:2d}: {histo[nbr_emails]:3d}')
418|     Log.info()
419| 
420|     # Make monthly emails bar chart...
421|     xs = [date(yr,mon,1) for yr,mon in sorted(months)]
422|     ys = [months[(dt.year,dt.month)] for dt in xs]
423| 
424|     fig,ax = plt.subplots()
425|     fig.set_figwidth(8.00)
426|     fig.set_figheight(3.5)
427|     fig.subplots_adjust(left=0.08, right=0.99, bottom=0.22, top=0.92)
428|     fig.suptitle('Monthly Count of Spam Emails')
429| 
430|     ax.set_xlabel('Month')
431|     ax.xaxis_date()
432|     ax.set_xlim(min(xs)-timedelta(20), max(xs)+timedelta(20))
433|     ax.xaxis.set_major_locator(mldates.DayLocator(bymonthday=1))
434|     ax.xaxis.set_major_formatter(mldates.DateFormatter('%b %y'))
435| 
436|     for tick in ax.xaxis.get_major_ticks():
437|         tick.label1.set_rotation('vertical')
438|         tick.label1.set_size(9)
439| 
440|     ax.set_ylabel('Number of Emails')
441|     ax.set_ylim(0, (int(max(ys)/100)+1)*100)
442|     ax.yaxis.set_major_locator(mlticks.MultipleLocator(100))
443|     ax.yaxis.set_minor_locator(mlticks.MultipleLocator(25))
444|     ax.yaxis.set_major_formatter(mlticks.FormatStrFormatter('%d'))
445| 
446|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
447|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
448|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
449|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
450| 
451|     ax.bar(xs,ys, width=20, color='#ff3f3f', alpha=0.90, zorder=10)
452| 
453|     fn = path.join(ImgsPath, 'spams-monthly-count.png')
454|     fig.savefig(fn)
455|     Log.info(f'wrote: {fn}')
456|     plt.close(fig)
457|     fig,ax = None,None
458| 
459|     # Make daily counts histogram bar chart...
460|     xs = list(sorted(histo))
461|     ys = [histo[x] for x in xs]
462| 
463|     fig,ax = plt.subplots()
464|     fig.set_figwidth(8.00)
465|     fig.set_figheight(3.5)
466|     fig.subplots_adjust(left=0.08, right=0.99, bottom=0.15, top=0.90)
467|     fig.suptitle('Daily Spam Emails Count Histogram')
468| 
469|     ax.set_xlabel('Daily Email Count')
470|     ax.set_xlim(-1, max(xs)+1)
471|     ax.xaxis.set_major_locator(mlticks.MultipleLocator(5))
472|     ax.xaxis.set_minor_locator(mlticks.MultipleLocator(1))
473|     ax.xaxis.set_major_formatter(mlticks.FormatStrFormatter('%d'))
474| 
475|     for tick in ax.xaxis.get_major_ticks():
476|         tick.label1.set_rotation('vertical')
477|         tick.label1.set_size(9)
478| 
479|     ax.set_ylabel('Number of Occurrences')
480|     ax.set_ylim(0, (int(max(ys)/10)+1)*10)
481|     ax.yaxis.set_major_locator(mlticks.MultipleLocator(10))
482|     ax.yaxis.set_minor_locator(mlticks.MultipleLocator(1))
483|     ax.yaxis.set_major_formatter(mlticks.FormatStrFormatter('%d'))
484| 
485|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
486|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
487|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
488|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
489| 
490|     ax.bar(xs,ys, color='#ff3f3f', width=0.80, alpha=0.90, zorder=10)
491| 
492|     fn = path.join(ImgsPath, 'spams-daily-count-histo.png')
493|     fig.savefig(fn)
494|     Log.info(f'wrote: {fn}')
495|     plt.close(fig)
496|     fig,ax = None,None
497| 
498|     Log.info()
499|     return 'Done'
500| 
501| ##================================================================================================##
502| def do_image_colors_histogram (**kwargs):
503|     '''CMND: create an RGB histogram from an image file.'''
504|     ipath = KWARG('ipath', '', str, kwargs)
505|     iname = KWARG('iname', 'image.png', str, kwargs)
506|     opath = KWARG('opath', '', str, kwargs)
507|     oname = KWARG('oname', '{}-histo.png', str, kwargs)
508|     roff  = KWARG('roff', 10_000, int, kwargs)
509|     Log.info(f'image-colors-frequencies:: {list(kwargs.keys())}')
510|     Log.debug(f'{ipath=}')
511|     Log.debug(f'{iname=}')
512|     Log.debug(f'{opath=}')
513|     Log.debug(f'{oname=}')
514|     Log.debug(f'{roff=}')
515|     Log.info()
516|     histo = [[0]*256, [0]*256, [0]*256]
517| 
518|     if '{' in oname:
519|         fname = path.basename(iname)
520|         fnam,fext = path.splitext(fname)
521|         oname = oname.format(fnam)
522| 
523|     chart_filename = path.join(opath,oname) if opath else oname
524|     Log.debug(f'{chart_filename=}')
525|     Log.debug()
526| 
527|     # Load image...
528|     nam = path.join(ipath,iname) if ipath else iname
529|     img = Image.open(nam)
530|     dat = img.getdata()
531|     Log.debug(f'loaded: {nam}')
532|     Log.debug(f'mode={img.mode}, size={img.size}')
533|     Log.debug()
534| 
535|     # Generate histogram data...
536|     for ix,rgb in enumerate(dat):
537|         r = rgb[0]
538|         g = rgb[1]
539|         b = rgb[2]
540| 
541|         histo[0][r] += 1
542|         histo[1][g] += 1
543|         histo[2][b] += 1
544| 
545|     # Determine maximums...
546|     most = 0
547|     for ix,rgb in enumerate(zip(*histo)):
548|         Log.trace(f'{ix:3d}: {rgb[0]:5d}, {rgb[1]:5d}, {rgb[2]:5d}')
549|         if most < rgb[0]: most = rgb[0]
550|         if most < rgb[1]: most = rgb[1]
551|         if most < rgb[2]: most = rgb[2]
552|     ymax = ((most // roff) * roff) + roff
553|     Log.debug(f'{most=}, {ymax=}')
554|     Log.debug()
555| 
556|     # Create Chart...
557|     fig, ax = plt.subplots()
558|     fig.set_figwidth(10.0)
559|     fig.set_figheight(4.0)
560|     fig.subplots_adjust(left=0.085, right=0.98, bottom=0.125, top=0.93)
561| 
562|     ax.set_title(f'RGB Histogram for {iname}', fontsize='14', fontweight='bold')
563|     ax.set_xlabel('Pixel Value', fontweight='bold')
564|     ax.set_ylabel('# of Occurances', fontweight='bold')
565| 
566|     ax.set_xlim(0, 256)
567|     ax.xaxis.set_major_locator(mlticks.MultipleLocator(32))
568|     ax.xaxis.set_minor_locator(mlticks.MultipleLocator(4))
569|     ax.xaxis.set_major_formatter(mlticks.FormatStrFormatter('%d'))
570| 
571|     ax.set_ylim(0, ymax)
572|     ax.yaxis.set_major_locator(mlticks.MultipleLocator(ymax//10))
573|     ax.yaxis.set_minor_locator(mlticks.MultipleLocator(ymax//50))
574|     ax.yaxis.set_major_formatter(mlticks.FormatStrFormatter('%d'))
575| 
576|     ax.grid(which='major', axis='both', color='#cfcfcf', lw=1.4,ls='-',zorder=1, alpha=1.0)
577|     ax.grid(which='minor', axis='both', color='#cfcfcf', lw=0.5,ls='-',zorder=0, alpha=1.0)
578|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
579|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
580| 
581|     ax.plot(histo[0], color='#ff0000', lw=2.0, alpha=0.8, zorder=13)
582|     ax.plot(histo[1], color='#00cc00', lw=2.0, alpha=0.8, zorder=12)
583|     ax.plot(histo[2], color='#0000ff', lw=2.0, alpha=0.8, zorder=11)
584| 
585|     fig.savefig(chart_filename)
586|     Log.info(f'wrote: {chart_filename}')
587|     Log.info()
588|     return 'Done'
589| 
590| ##================================================================================================##
591| def do_alpha_frequency_chart (**kwargs):
592|     '''CMND: Create an alphabet frequency histogram.'''
593|     fpath = KWARG('fpath', ImgsPath, str, kwargs)
594|     fname = KWARG('fname', 'alpha-histo.png', str, kwargs)
595|     Log.info(f'alphabet-frequencies:: {list(kwargs.keys())}')
596|     Log.debug(f'{fpath=}')
597|     Log.debug(f'{fname=}')
598|     Log.info()
599| 
600|     tick_names = [chr(UCX+x) for x in range(26)]
601|     tick_marks = list(range(1,27))
602| 
603|     fig, ax = plt.subplots()
604|     ax.set_title('Alphabetic Frequencies')
605|     ax.set_xlabel('Alphabet')
606|     ax.set_ylabel('Frequency')
607| 
608|     ax.set_xlim(0.5, 26.5)
609|     ax.set_xticks(tick_marks)
610|     ax.set_xticklabels(tick_names)
611| 
612|     ax.set_ylim(0.0, 0.15)
613|     ax.yaxis.set_major_locator(mlticks.MultipleLocator(0.05))
614|     ax.yaxis.set_minor_locator(mlticks.MultipleLocator(0.01))
615|     ax.yaxis.set_major_formatter(mlticks.FormatStrFormatter('%.2f'))
616| 
617|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
618|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
619|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
620|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
621| 
622|     ax.bar(tick_marks,AlphaFreqs, label='frequency', zorder=10)
623|     ##ax.legend(loc='upper right', shadow=True)
624| 
625|     fig.set_figwidth(4.40)
626|     fig.set_figheight(3.0)
627|     fig.subplots_adjust(left=0.15, right=0.98, bottom=0.16, top=0.90)
628| 
629|     fn = path.join(fpath,fname) if fpath else fname
630|     fig.savefig(fn)
631|     Log.info(f'wrote: {fn}')
632| 
633|     Log.info()
634|     return 'Done'
635| 
636| ##================================================================================================##
637| def do_test (**kwargs):
638|     """CMND: Do a test."""
639|     fpath = KWARG('fpath', BasePath, str, kwargs)
640|     fname = KWARG('fname', 'test.out', str, kwargs)
641|     Log.info(f'test:: {list(kwargs.keys())}')
642|     Log.debug(f'{fpath=}')
643|     Log.debug(f'{fname=}')
644|     Log.info()
645|     Log.info()
646|     return 'Done'
647| ####################################################################################################
648| def dispatch (cmd, **kwargs):
649|     """Dispatch to a module function based on CMD."""
650|     Log.info(f'CMD: {cmd}')
651|     for kw in kwargs:
652|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
653|     Log.info()
654|     if cmd == 'words': return do_word_counter(**kwargs)
655|     if cmd == 'walk': return do_going_for_a_walk(**kwargs)
656|     if cmd == 'dotw': return do_get_weekday_list(**kwargs)
657|     if cmd == 'wells': return do_wells_fargo_checking(**kwargs)
658|     if cmd == '401k': return do_401k_chart(**kwargs)
659|     if cmd == 'spam': return do_spam_counts(**kwargs)
660|     if cmd == 'colors': return do_image_colors_histogram(**kwargs)
661|     if cmd == 'alpha': return do_alpha_frequency_chart(**kwargs)
662|     if cmd == 'test': return do_test(**kwargs)
663|     return 'Nothing to do!'
664| ####################################################################################################
665| if __name__ == '__main__':
666|     print(f'autorun: {argv[0]}')
667|     Log.start(path.join(BasePath,'misc.log'))
668|     #Log.start(path.join(BasePath,LogFilenameTimestamp('misc_%s.log')))
669|     Log.level(trace())
670|     Log.info(argv[0])
671|     Log.info()
672|     cmd = argv[1] if 1 < len(argv) else CMND
673|     kwargs = ARGS
674|     for a in argv[2:]:
675|         nv = a.split('=', 1)
676|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
677|         Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
678|     try:
679|         print(f'CMD: {cmd}')
680|         print()
681|         obj = dispatch(cmd, **kwargs)
682|         print()
683|         print(obj)
684|         Log.info()
685|         Log.info(obj)
686|     except:
687|         etype, evalue, tb = exc_info()
688|         ts = extract_tb(tb)
689|         Log.error()
690|         Log.error(f'{etype.__name__}: {evalue!s}')
691|         Log.error()
692|         for t in ts[-5:]:
693|             Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
694|             Log.error(f' {t[3]}')
695|             Log.error()
696|         raise
697|     finally:
698|         Log.end()
699| ####################################################################################################
700| '''eof'''
701|