pages-and-charts.html
001| '''Blog Charts.
001|
001| Functions:
001| PostStatsData_totals Report on stats.blog_stats
001| PostsPerMonth_test Report on stats.posts
001| Reporter Decorator for ygrid_selection
001| ygrid_selection Determine appropriate Y-grids
001| chart_initialize Selected Posts: initialize chart
001| chart_save Selected Posts: save chart
001| chart_one_post Selected Posts: make chart
001|
001| Commands:
001| b:cats.list do_blog_categories_list Categories HTML page
001|
001| p:page.over do_stats_overview_page Blog Stats HTML page
001| p:page.hits do_page_hits_page Page Views HTML page
001| p:top.posts do_top_posts_page Top Posts HTML page
001| p:charts do_charts_list_page Charts HTML page
001|
001| c:hits.year do_page_hits_by_year_chart Page Views per Year chart
001| c:posts.yr do_posts_per_year_chart Posts per Year chart
001| c:posts.mo do_posts_per_month_chart Posts per Month chart
001| c:words.posts do_words_per_post_chart Words per Post chart
001| c:visit1 do_visitors_per_month_chart Number of visitors per month
001| c:visit2 do_avg_visitors_per_day_chart Average #of visitors per day (by month)
001| c:views do_views_and_visitors_chart Number of views & visitors
001| c:views.avg do_avg_views_per_day_chart Number of views/day (average)
001|
001| c:post.hits do_post_hits_by_year_chart Number of hits on a post per year
001| csv.update do_update_csv_hits_files Convert http: to https: in CSV files
001|
001| sel.check do_check_selected_posts SELECTED POSTS DB...
001| p:sel.posts do_selected_posts_page Selected Posts HTML page
001| c:sel.all do_all_post_charts Do all the charts
001| c:sel.one do_one_post_chart Do one chart
001| c:sel.over do_overlay_posts_chart Meh
001| c:sel.comb do_combined_posts_chart Meh
001| sel.links do_selected_posts_links_page Generate stats-page links page
001|
001| test do_test
001| '''
002|
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path, rename
006| from datetime import date, datetime
007| import matplotlib.pyplot as plt
008| from matplotlib.ticker import NullLocator, MultipleLocator, NullFormatter, FormatStrFormatter
009| from matplotlib.dates import DayLocator, MonthLocator, YearLocator, DateFormatter
010| from logger import logger, info, debug, trace
011| from files import filefinder, linefile, tabfile, jsonfile
012| from mlchart import mlchart, mlmonthchart
013| from webpage import WebPage
014| from goodies import KWARG, safediv, add_commas
015| from wordpress import BlogStatsPage, BlogPageHitsPage, BlogPageHitsData
016| from wordpress import RealCategoryData, SelectedPosts
017|
018| Log = logger('Blog')
019| BasePath = r'C:\CJS\prj\Python\blog\hcc'
020| HtmlPath = r'C:\CJS\www\root\cjs\blog\hcc'
021| DataPath = path.join(BasePath, 'dat')
022| ImgsPath = path.join(BasePath, 'img')
023| BlogName = 'The Hard-Cord Coder'
024| BlogCode = 'HCC'
025| BlogLink = 'https://thehardcorecoder.com'
026| SlugName = 'thehardcorecoder'
027|
028| CMND = ''
029| ARGS = {
030|
031|
032|
033|
034|
035|
036|
037|
038|
039| }
040|
041|
042| Year0,YearN = 2014, 2025
043| Year0float = 13.5
044| YearNfloat = 25.5
045| StartDate = date(Year0, 1, 1)
046|
047| StatsFile = path.join(DataPath, 'stats.json')
048|
049| PostStatsHdrs = ['Year','Posts','Cmnts','AvgCmnts','TotLikes','AvgLikes','TotWords','AvgWords' ,'AvgPosts']
050| PostStatsCols = [0, 1, 1, 2, 1, 2, 1, 1, 2]
051|
052|
053| SafeName = lambda n: ''.join([c for c in n if c.isalpha() or c.isnumeric()])
054|
055| SpecialK = lambda s: (int(1000*float(s[0:-1])) if s.endswith('K') else int(s))
056|
057|
058|
059| class Stats (jsonfile):
060| def __init__ (self):
061| super().__init__(StatsFile, log=Log)
062| self.hits_all = []
063| self.hits_home = []
064| self.visitors = []
065| self.blog_stats = []
066| self.files = []
067| self.posts = {}
068| self.views_avg = {}
069| self.load()
070|
071| def load (self):
072| super().load()
073| self.hits_all = self.data['hit.stats']['page.hits.all']
074| self.hits_home = self.data['hit.stats']['page.hits.home']
075| self.visitors = self.data['hit.stats']['visitor.hits']
076| self.blog_stats = self.data['post.stats']
077| self.files = self.data['year.files']
078| self.posts = {int(k):v for k,v in self.data['posts.per.month'].items()}
079| self.views_avg = {int(k):v for k,v in self.data['views.per.day.avg'].items()}
080|
081| def save (self):
082| raise NotImplementedError('Save not enabled.')
083|
084|
085| def PostStatsData_totals():
086| stats = Stats()
087| tot_posts = 0
088| tot_words = 0
089| for yr,np,_,_,_,_,nw,_ in stats.blog_stats:
090| if np == 0: continue
091| print('%d: %3d %6d %7.2f' % (yr,np,nw,nw/np))
092| tot_posts += int(np)
093| tot_words += int(nw)
094| print()
095| print('Total # Posts: %7d' % tot_posts)
096| print('Total # Words: %7d' % tot_words)
097| print('Av Words/Post: %7.2f' % (tot_words/tot_posts))
098| print()
099|
100|
101| def PostsPerMonth_test ():
102| stats = Stats()
103| for yr,row in stats.posts.items():
104| print(row)
105| tot = 0
106| for mon in row[0:12]:
107| tot += mon
108| assert tot == row[12]
109| print('Ok!')
110|
111|
112|
113| def Reporter (function):
114| def wrapper (ceiling):
115| Log.debug(f'Y-Grid Input: {ceiling}')
116| rv = function(ceiling)
117| Log.debug(f'Y-Grid Output: {rv}')
118| Log.debug()
119| return rv
120| return wrapper
121|
122| @Reporter
123| def ygrid_selection (ymax):
124| '''Return appropriate Y grid spacing tuple base on ymax.'''
125| if 1000 < ymax:
126| return (1000, 250)
127| if 800 <= ymax:
128| return (200, 50)
129| if 400 <= ymax:
130| return (100, 50)
131| if 100 <= ymax:
132| return (100, 25)
133|
134| return (10, 5)
135|
136|
137|
138| def do_blog_categories_list (**kwargs):
139| """CMND: Do Blog Categories List."""
140| fpath = KWARG('fpath', BasePath, str, kwargs)
141| fname = KWARG('fname', 'categories.html', str, kwargs)
142| dpath = KWARG('dpath', DataPath, str, kwargs)
143| dname = KWARG('dname', 'categories.tab', str, kwargs)
144| Log.info('BLOG-CATEGORIES-LIST:: %s' % str(list(kwargs.keys())))
145| Log.info('fpath="%s"' % fpath)
146| Log.info('fname="%s"' % fname)
147| Log.info()
148| catdat = RealCategoryData(fname=dname, fpath=dpath)
149|
150| filename = path.join(fpath, fname)
151| html_li = '<div style="margin: 5px 9pt 5px 6pt;">%s — <em>%s</em> — (%d)</div>'
152| html_url = '<a href="%s/category/%s"><strong>%s</strong></a>'
153|
154| fout = linefile(filename)
155| fout.add('<h3>Categories</h3>')
156| fout.add()
157| for name,desc,url,n in sorted(catdat, key=lambda x:x[3], reverse=True):
158| link = html_url % (BlogLink, url, name)
159| fout.add(html_li % (link, desc, int(n)))
160| fout.add()
161| fout.save()
162|
163| Log.info()
164| return 'Done'
165|
166|
167| def do_views_and_visitors_chart (**kwargs):
168| """CMND: Do Views and Visitors chart."""
169| ipath = KWARG('ipath', ImgsPath, str, kwargs)
170| iname = KWARG('iname', 'views-and-visitors.png', str, kwargs)
171| dpath = KWARG('dpath', DataPath, str, kwargs)
172| dname = KWARG('dname', SelectedPosts.FileName, str, kwargs)
173| Log.info(f'POST-HITS-BY-YEAR:: {list(kwargs.keys())}')
174| Log.info(f'ipath="{ipath}"')
175| Log.info(f'iname="{iname}"')
176| Log.info(f'dpath="{dpath}"')
177| Log.info(f'dname="{dname}"')
178| Log.info()
179|
180| posts = SelectedPosts(fname=dname, fpath=dpath, exclude='~')
181| views = posts('__Views__')
182| visitors = posts('__Visitors__')
183| Log.info(views)
184| Log.info(visitors)
185| Log.info()
186|
187| class views_and_visitors (mlchart):
188| def __init__ (self, data=None, **kwargs):
189| super().__init__((8.8, 3.0), **kwargs)
190| self.data = data
191| self.title = 'Views and Visitors'
192| self.x_title = 'Date (by Month)'
193| self.y_title = 'Number'
194| self.x_limit = (date(Year0,1,1), date(2026,1,1))
195| self.y_limit = (0, +1000)
196| self.x_grids = (None, None)
197| self.y_grids = (200, 50)
198| self.x_tickf = '%Y'
199| self.y_tickf = '%d'
200| self.x_tickr = False
201| self.x_dates = False
202| self.title_kw['fontsize'] = 16
203| self.title_kw['fontweight'] = 'bold'
204| self.x_title_kw['fontsize'] = 12
205| self.y_title_kw['fontsize'] = 12
206| self.fpath = ipath
207| self.fname = iname
208| self.margins = dict(left=0.085, right=0.975, bottom=0.18, top=0.91)
209|
210| def plotter (self):
211| xs = self.data[0]
212| ys1 = self.data[1]
213| ys2 = self.data[2]
214| self.ax.fill_between(xs, 0,ys1, label='Views' , color='#3399cc', edgecolor='#003366', lw=2, alpha=0.8, zorder=12)
215| self.ax.fill_between(xs, 0,ys2, label='Visitors', color='#cc9933', edgecolor='#663300', lw=2, alpha=0.8, zorder=11)
216|
217| def make_x_axis_spcl (self):
218| self.ax.xaxis_date()
219|
220| self.ax.xaxis.set_major_locator(YearLocator())
221| self.ax.xaxis.set_minor_locator(MonthLocator(interval=2))
222|
223| self.ax.xaxis.set_major_formatter(DateFormatter(self.x_tickf))
224| self.ax.xaxis.set_minor_formatter(NullFormatter())
225|
226| data = {}
227|
228| Log.info('Visitors...')
229| for yr,tot,mons in visitors.hits:
230| Log.info(f'{yr}: {tot:,d}')
231| if tot == 0:
232| continue
233| for mx,mon in enumerate(mons):
234| dt = date(yr,mx+1,1)
235| t = (dt, mon)
236| data[dt] = [mon]
237| Log.info()
238|
239| Log.info('Views...')
240| for yr,tot,mons in views.hits:
241| Log.info(f'{yr}: {tot:,d}')
242| if tot == 0:
243| continue
244| for mx,mon in enumerate(mons):
245| dt = date(yr,mx+1,1)
246| t = (dt, mon)
247| if dt not in data:
248| data[dt] = [0]
249| data[dt].append(mon)
250| Log.info()
251|
252| xs = []
253| ys0 = []
254| ys1 = []
255| for dt,hits in sorted(data.items(), key=lambda t:t[0]):
256| xs.append(dt)
257| ys0.append(hits[0])
258| ys1.append(hits[1])
259|
260| cht = views_and_visitors([xs, ys0, ys1])
261| cht.make()
262| Log.info('wrote: %s' % path.join(cht.fpath, cht.fname))
263| Log.info()
264| return 'Done'
265|
266|
267| def do_avg_views_per_day_chart (**kwargs):
268| """CMND: Do average views per day chart."""
269| ipath = KWARG('ipath', ImgsPath, str, kwargs)
270| iname = KWARG('iname', 'avg-views-per-day.png', str, kwargs)
271| Log.info(f'AVERAGE-VIEWS-PER-DAY:: {list(kwargs.keys())}')
272| Log.info(f'ipath="{ipath}"')
273| Log.info(f'iname="{iname}"')
274| Log.info()
275| filename = path.join(ipath,iname) if ipath else iname
276| stats = Stats()
277|
278|
279| fig, ax = plt.subplots()
280| fig.set_figwidth(8.0)
281| fig.set_figheight(4.0)
282| fig.subplots_adjust(left=0.070, right=0.990, bottom=0.18, top=0.92)
283| fig.suptitle(f'{BlogName}, Average Views per Day', fontsize=14, fontweight='bold')
284|
285| ax.xaxis_date()
286| ax.set_xlabel('Month', fontsize=12, fontweight='bold')
287| ax.set_xlim(date(Year0,1,1), date(YearN+1,1,1))
288| ax.xaxis.set_major_locator(MonthLocator(interval=12))
289| ax.xaxis.set_minor_locator(MonthLocator(interval=3))
290| ax.xaxis.set_major_formatter(DateFormatter('%b %y'))
291|
292| for tick in ax.xaxis.get_major_ticks():
293| tick.label1.set_rotation('vertical')
294| tick.label1.set_size(9)
295|
296| ax.set_ylabel('Avg Views/Day', fontsize=12, fontweight='bold')
297| ax.set_ylim(0, 40)
298| ax.yaxis.set_major_locator(MultipleLocator(10))
299| ax.yaxis.set_minor_locator(MultipleLocator( 1))
300| ax.yaxis.set_major_formatter(FormatStrFormatter('%d'))
301|
302| ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
303| ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
304| ax.tick_params(which='major', axis='both', direction='out', color='#000000')
305| ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
306|
307| data = [
308| (date(yr,ix+1,1), views)
309| for yr,row in sorted(stats.views_avg.items(), key=lambda t:t[0])
310| for ix,views in enumerate(row[0:12]) if views
311| ]
312| xs = [d[0] for d in data]
313| ys = [d[1] for d in data]
314| ax.plot(xs,ys, label='Avg Views/Day', c='#0000ff', zorder=11, alpha=0.80, lw=2.0)
315|
316| fig.savefig(filename)
317| Log.info(f'wrote: {filename}')
318| Log.info()
319| return 'Done'
320|
321|
322| def do_post_hits_by_year_chart (**kwargs):
323| """CMND: Do post views (by year) chart. (Uses the annual posts views CSV files.)"""
324| ipath = KWARG('ipath', ImgsPath, str, kwargs)
325| pname = KWARG('post', '', str, kwargs)
326| dpath = KWARG('dpath', DataPath, str, kwargs)
327| dname = KWARG('dname', '', str, kwargs)
328| ymax = KWARG('ymax', 800, int, kwargs)
329| Log.info('POST-HITS-BY-YEAR:: %s' % str(list(kwargs.keys())))
330| Log.info('ipath="%s"' % ipath)
331| Log.info('post="%s"' % pname)
332| Log.info('dpath="%s"' % dpath)
333| Log.info('dname="%s"' % dname)
334| Log.info('max-y=%d' % ymax)
335| Log.info()
336|
337|
338| roundup = lambda n,s: ((1+int(max(n)/s))*s)
339|
340| class hits_per_year_chart (mlchart):
341| def __init__ (self, title, data, ytop=2000, **kwargs):
342| super().__init__(**kwargs)
343| self.title = title
344| self.xs = [t[0]-2000 for t in data]
345| self.ys = [t[1] for t in data]
346| ceiling = min(max(100,roundup(self.ys,100)), ytop)
347| self.dims = (6.0, 2.0)
348| self.margins = dict(left=0.12, right=0.995, bottom=0.25, top=0.89)
349| self.x_title = 'Blog Year'
350| self.y_title = 'Page Views'
351| self.x_limit = (Year0float, YearNfloat)
352| self.y_limit = (0, ceiling)
353| self.x_grids = (1.0, None)
354| self.y_grids = ygrid_selection(ceiling)
355| self.x_tickf = '\'%d'
356| self.y_tickf = '%d'
357| self.title_kw = {}
358| self.x_title_kw = {'fontsize':12}
359| self.y_title_kw = {'fontsize':12}
360|
361| def plotter (self):
362| Log.debug()
363| self.ax.bar(self.xs, self.ys, color='#336699', width=0.75, alpha=1.00, zorder=11)
364| for x,y in zip(self.xs, self.ys):
365| if self.y_limit[1] < y:
366| Log.debug('@ %s: Bar value is over the max. (%s < %s)' % (x, self.y_limit[1], y))
367| self.ax.text(x, (self.y_limit[1] * 0.9), str(y), c='#ffff7f', fontsize=8, ha='center', zorder=21)
368|
369|
370| def make_chart (post_name, post, ytop):
371| pfile,tot,hits = post
372| Log.info('POST: "%s"' % post_name)
373| Log.info('file: "%s"' % pfile)
374| Log.info('total-views: %d' % tot)
375| pnm = '%s (%d views)' % (post_name,tot)
376| fnm = '%s.png' % SafeName(post_name)
377| cht = hits_per_year_chart(pnm, hits, ytop=ytop, fname=fnm, fpath=ipath)
378| cht.make()
379| Log.info('wrote: %s (in: %s)' % (fnm,ipath))
380| Log.info()
381| plt.close(cht.fig)
382|
383| stats = Stats()
384| data = BlogPageHitsData(stats.files, fpath=dpath)
385| Log.info('Blog Page Views Data: %d posts' % len(data))
386| Log.info()
387|
388|
389| def search_for_matches (pnam):
390| _n = pnam.lower()
391| ns = list(data.data.keys())
392|
393| for n in ns:
394| if n.lower().startswith(_n):
395| make_chart(n, data[n], ymax)
396| return True
397|
398| for n in ns:
399| if _n in n.lower():
400| make_chart(n, data[n], ymax)
401| return True
402|
403| return False
404|
405| if pname:
406|
407| if pname in data:
408|
409| make_chart(pname, data[pname], ymax)
410| else:
411|
412| found = search_for_matches(pname)
413| if not found:
414| Log.warn(f'No match found for pname={pname}.')
415| elif dname:
416|
417| fn = path.join(dpath,dname) if dpath else dname
418| fo = tabfile(fn)
419| fo.load()
420| Log.info('read: %d lines' % len(fo))
421| Log.info()
422| nms = [(t[0],int(t[1]) if 1<len(t) else 0) for t in fo if 0<len(t[0])]
423| for nm,ytop in nms:
424| Log.info('list-entry: "%s" (%d)' % (nm,ytop))
425| if nm.startswith('#'): continue
426| print(nm)
427| try:
428| make_chart(nm, data[nm], ytop if ytop else ymax)
429| except Exception as e:
430| Log.error(e)
431| Log.error()
432| else:
433| raise RuntimeError('Must use the post or dname parameter!')
434|
435| Log.info()
436| return 'Done'
437|
438|
439| def do_page_hits_page (**kwargs):
440| """CMND: Do Blog Page Views HTML Page."""
441| fpath = KWARG('fpath', HtmlPath, str, kwargs)
442| fname = KWARG('fname', 'page_hits_all.html', str, kwargs)
443| dpath = KWARG('dpath', DataPath, str, kwargs)
444| dname = KWARG('dname', '', str, kwargs)
445| Log.info('PAGE-HITS-PAGE:: %s' % str(list(kwargs.keys())))
446| Log.info('fpath="%s"' % fpath)
447| Log.info('fname="%s"' % fname)
448| Log.info('dpath="%s"' % dpath)
449| Log.info('dname="%s"' % dname)
450| Log.info()
451|
452| stats = Stats()
453| page = BlogPageHitsPage(stats.files, Year0, YearN, fpath=dpath)
454| page.save(fname, fpath)
455| Log.info(page)
456| Log.info()
457| return 'Done'
458|
459|
460| def do_top_posts_page (**kwargs):
461| """CMND: Do Top Blog Posts HTML Page."""
462| fpath = KWARG('fpath', HtmlPath, str, kwargs)
463| fname = KWARG('fname', 'top_posts.html', str, kwargs)
464| dpath = KWARG('dpath', DataPath, str, kwargs)
465| Log.info('TOP-POSTS-PAGE:: %s' % str(list(kwargs.keys())))
466| Log.info('fpath="%s"' % fpath)
467| Log.info('fname="%s"' % fname)
468| Log.info('dpath="%s"' % dpath)
469| Log.info()
470| css_tab = 'font-size:13px;border-spacing:10px 1px;padding:0;border:0;margin:5px 25px 10px 10px;'
471| css_h4 = 'font-size:17px;margin-top:20px;margin-bottom:5px;'
472| css_td0 = 'text-align:right;font-weight:bold;padding:1px 6px;'
473| css_td1 = 'text-align:right;font-weight:bold;padding:1px 6px;'
474| css_td2 = 'font-size:15px;padding:1px 5px;'
475| css_div = 'font-size:9px;font-style:italic;padding:30px 0 10px 5px;'
476| filename = path.join(fpath, fname)
477|
478|
479| stats = Stats()
480| views = BlogPageHitsData(stats.files, fpath=dpath)
481| data = list(views.items())
482| nams = [d[0] for d in data]
483| urls = [d[1][0] for d in data]
484| tots = [d[1][1] for d in data]
485| yrss = [d[1][2] for d in data]
486| Log.info('data.length=%d' % len(data))
487| Log.info()
488|
489| pg = WebPage('Top Posts', h1=BlogName, h2='Stats', css=['/basic.css'])
490| pg.add()
491|
492|
493| pg.add('<h4 style="%s">%d–%d</h4>' % (css_h4,Year0,YearN))
494| pg.add('<table style="%s">' % css_tab)
495| pg.add('<tbody>')
496| for ix,t in enumerate(sorted(data, key=lambda x:x[1][1], reverse=True)):
497| name,info = t
498| if info[1] < 200:
499| break
500| pg.add('<tr>')
501| pg.add('<td style="%s">%d</td>' % (css_td0,ix))
502| pg.add('<td style="%s">%s</td>' % (css_td1,add_commas(info[1])))
503| pg.add('<td style="%s"><a target="_blank" href="%s">%s</a></td>' % (css_td2,info[0],name))
504| pg.add('</tr>')
505| pg.add('</tbody>')
506| pg.add('</table>')
507| pg.add()
508|
509| def print_year (year):
510| yrs = []
511| for post in yrss:
512| n = 0
513| for yr in post:
514| if yr[0] == year:
515| n = yr[1]
516| yrs.append(n)
517|
518| pg.add('<h4 style="%s">%d</h4>' % (css_h4,year))
519| pg.add('<table style="%s">' % css_tab)
520| pg.add('<tbody>')
521| for ix,t in enumerate(sorted(zip(yrs,nams,urls), key=lambda x:x[0], reverse=True)):
522| if t[0] < 50:
523| break
524| pg.add('<tr>')
525| pg.add('<td style="%s">%d</td>' % (css_td0,ix))
526| pg.add('<td style="%s">%s</td>' % (css_td1,add_commas(t[0])))
527| pg.add('<td style="%s"><a target="_blank" href="%s">%s</a></td>' % (css_td2,t[2],t[1]))
528| pg.add('</tr>')
529| pg.add('</tbody>')
530| pg.add('</table>')
531| pg.add()
532|
533|
534| for yr in range(YearN, Year0-1, -1):
535| print_year(yr)
536|
537|
538| pg.add('<div style="%s">%s</div>' % (css_div,views))
539| pg.add()
540|
541|
542| pg.save(filename, log=Log)
543|
544| Log.info()
545| return 'Done'
546|
547|
548| def do_stats_overview_page (**kwargs):
549| """CMND: Do Stats Overview HTML Page."""
550| fpath = KWARG('fpath', HtmlPath, str, kwargs)
551| fname = KWARG('fname', 'blog_stats.html', str, kwargs)
552| Log.info('STATS-OVERVIEW-PAGE:: %s' % str(list(kwargs.keys())))
553| Log.info('fpath="%s"' % fpath)
554| Log.info('fname="%s"' % fname)
555| Log.info()
556|
557| stats = Stats()
558| page = BlogStatsPage(stats.blog_stats, PostStatsHdrs, PostStatsCols)
559| page.save(fname, fpath)
560| Log.info(page)
561| Log.info()
562| page.stats_save(fpath=BasePath)
563| Log.info()
564| return 'Done'
565|
566|
567| def do_charts_list_page (**kwargs):
568| """CMND: Do Blog Charts List HTML Page."""
569| fpath = KWARG('fpath', path.join(HtmlPath,'charts'), str, kwargs)
570| fname = KWARG('fname', 'index.html', str, kwargs)
571| dpath = KWARG('dpath', DataPath, str, kwargs)
572| dname = KWARG('dname', SelectedPosts.FileName, str, kwargs)
573| Log.info('CHARTS-LIST-PAGE:: %s' % str(list(kwargs.keys())))
574| Log.info('fpath="%s"' % fpath)
575| Log.info('fname="%s"' % fname)
576| Log.info('dname="%s"' % dname)
577| Log.info('dpath="%s"' % dpath)
578| Log.info()
579|
580| posts = SelectedPosts(fname=dname, fpath=dpath)
581| Log.debug(posts)
582| Log.debug()
583|
584| configname = path.join(dpath, 'selected-posts-config.json')
585| config = jsonfile(configname)
586| config.load()
587| Log.debug(config.data)
588| Log.debug()
589|
590|
591| pg = WebPage('Charts', h1=BlogName, h2='Stats', css=['/basic.css','/index.css'])
592| pg.add('<table>')
593| pg.add('<tbody>')
594|
595| pg.add()
596| pg.add('<tr><td style="text-align:center;"><img src="views-and-visitors.png" alt="[views-and-visitors.png]" width="600"></td></tr>')
597| pg.add('<tr><td style="text-align:center;"><img src="avg-views-per-day.png" alt="[avg-views-per-day.png]" width="600"></td></tr>')
598| pg.add('<tr><td style="text-align:center;"><img src="page-hits-by-year.png" alt="[page-hits-by-year.png]" width="600"></td></tr>')
599| pg.add('<tr><td style="text-align:center;"><img src="posts-per-year.png" alt="[posts-per-year.png]" width="300"><img src="words-per-post.png" alt="[words-per-post.png]" width="300"></td></tr>')
600| pg.add('<tr><td style="text-align:center;"><img src="posts-per-month.png" alt="[posts-per-month.png]" width="600"></td></tr>')
601| pg.add()
602| for filename in config.data['main']:
603| pg.add(f'<tr><td style="text-align:center;"><img src="{filename}" alt="[{filename}]" width="600"></td></tr>')
604| pg.add()
605|
606| pg.add('<tr><th>Key Posts (and some Pages)</th></tr>')
607| pg.add('<tr><td><img src="Home.png" alt="[Home.png]" width="600"></td></tr>')
608| pg.add('<tr><td><img src="About.png" alt="[About.png]" width="600"></td></tr>')
609| if posts('Who?') is not None:
610| pg.add('<tr><td><img src="Who.png" alt="[Who.png]" width="600"></td></tr>')
611| if posts('Why?') is not None:
612| pg.add('<tr><td><img src="Why.png" alt="[Why.png]" width="600"></td></tr>')
613| pg.add()
614| for filename in config.data['special']:
615| pg.add(f'<tr><td style="text-align:center;"><img src="{filename}" alt="[{filename}]" width="600"></td></tr>')
616| pg.add('<tr><td></td></tr>')
617| pg.add()
618|
619|
620| for ix,post in enumerate(sorted(posts)):
621| if post.name in ['Home','About','Why?','Who?']:
622| continue
623| Log.info('%2d: %s (%d views)' % (ix, post.name, post.total))
624| pn = SafeName(post.name)
625| pg.add('<tr><td><img src="%s.png" alt="[%s.png]" width="600"></td></tr>' % (pn, pn))
626| Log.info()
627|
628| pg.add('<tr><th>Miscellaneous</th></tr>')
629| pg.add('<tr><td><img src="sel-posts-combined.png" alt="[sel-posts-combined.png]" width="600"></td></tr>')
630| pg.add('<tr><td><img src="sel-posts-overlay.png" alt="[sel-posts-overlay.png]" width="600"></td></tr>')
631| pg.add()
632| for filename in config.data['tail']:
633| pg.add(f'<tr><td style="text-align:center;"><img src="{filename}" alt="[{filename}]" width="600"></td></tr>')
634| pg.add()
635|
636| pg.add('</tbody>')
637| pg.add('</table>')
638| pg.add()
639|
640|
641| filename = path.join(fpath, fname)
642| pg.save(filename, log=Log)
643|
644| Log.info()
645| return 'Done'
646|
647|
648|
649| def do_words_per_post_chart (**kwargs):
650| """CMND: Do Average Words per Post Chart."""
651| fpath = KWARG('fpath', ImgsPath, str, kwargs)
652| fname = KWARG('fname', 'words-per-post.png', str, kwargs)
653| Log.info('WORDS-PER-POST:: %s' % str(list(kwargs.keys())))
654| Log.info('fpath="%s"' % fpath)
655| Log.info('fname="%s"' % fname)
656| Log.info()
657| stats = Stats()
658|
659| class words_per_post_chart (mlchart):
660| def __init__ (self, **kwargs):
661| super().__init__(**kwargs)
662| self.dims = (6.0, 3.0)
663| self.title = f'{BlogName}: Average Words per Post'
664| self.x_title = 'Year'
665| self.x_limit = (Year0float, YearNfloat)
666| self.x_grids = (1.0, None)
667| self.y_title = 'Number of Words'
668| self.y_limit = (0, 3000)
669| self.y_grids = (1000, 100)
670| self.x_tickf = '\'%d'
671| self.y_tickf = '%d'
672| self.margins = dict(left=0.12, right=0.99, bottom=0.15, top=0.90)
673| def plotter (self):
674| xs,ys = [],[]
675| for row in stats.blog_stats:
676| yr = row[PostStatsHdrs.index('Year')]
677| nposts = row[PostStatsHdrs.index('Posts')]
678| nwords = row[PostStatsHdrs.index('TotWords')]
679| xs.append(yr-2000)
680| ys.append(safediv(float(nwords),float(nposts)))
681| Log.debug('%d: %.3f' % (ys[-1], xs[-1]))
682| Log.debug()
683| self.ax.bar(xs,ys, label='per Year', color='#cc6600', width=0.75, alpha=1.00, zorder=11)
684|
685| cht = words_per_post_chart(fname=fname, fpath=fpath)
686| cht.make()
687| Log.info('wrote: %s' % path.join(cht.fpath,cht.fname))
688| Log.info()
689| return 'Done'
690|
691|
692| def do_posts_per_year_chart (**kwargs):
693| """CMND: Do Posts per Year chart."""
694| fpath = KWARG('fpath', ImgsPath, str, kwargs)
695| fname = KWARG('fname', 'posts-per-year.png', str, kwargs)
696| title = KWARG('title', f'{BlogName}: Posts per Year', str, kwargs)
697| Log.info('POSTS-PER-YEAR-CHART:: %s' % str(list(kwargs.keys())))
698| Log.info('fpath="%s"' % fpath)
699| Log.info('fname="%s"' % fname)
700| Log.info('title="%s"' % title)
701| Log.info()
702| stats = Stats()
703|
704| class posts_per_year_chart (mlchart):
705| def __init__ (self, **kwargs):
706| super().__init__(**kwargs)
707| self.dims = (6.0, 3.0)
708| self.title = title
709| self.x_title = 'Year'
710| self.x_limit = (Year0float, YearNfloat)
711| self.x_grids = (1.0, None)
712| self.y_title = 'Number of Posts'
713| self.y_limit = (0, 30)
714| self.y_grids = (10, 2)
715| self.x_tickf = '\'%d'
716| self.y_tickf = '%d'
717| self.margins = dict(left=0.09, right=0.99, bottom=0.15, top=0.91)
718| def make (self, **kwargs):
719| super().make(**kwargs)
720|
721|
722|
723|
724| def plotter (self):
725| yrs = list(sorted(stats.posts))
726| xs = [yr-2000 for yr in yrs]
727| ys = [int(stats.posts[yr][12]) for yr in yrs]
728|
729| self.ax.bar(xs,ys, color='#3f7fbf', width=0.75, alpha=1.00, zorder=10)
730|
731| cht = posts_per_year_chart(fname=fname, fpath=fpath)
732| cht.make()
733| Log.info('wrote: %s' % path.join(cht.fpath,cht.fname))
734| Log.info()
735| return 'Done'
736|
737|
738| def do_posts_per_month_chart (**kwargs):
739| """CMND: Do Posts per Month chart."""
740| fpath = KWARG('fpath', ImgsPath, str, kwargs)
741| fname = KWARG('fname', 'posts-per-month.png', str, kwargs)
742| title = KWARG('title', f'{BlogName}: Posts per Month', str, kwargs)
743| Log.info('POSTS-PER-MONTH-CHART:: %s' % str(list(kwargs.keys())))
744| Log.info('fpath="%s"' % fpath)
745| Log.info('fname="%s"' % fname)
746| Log.info('title="%s"' % title)
747| Log.info()
748| stats = Stats()
749|
750| bbprops = dict(facecolor='white', capstyle='round', alpha=1.0)
751| ssprops = dict(fontname='monospace', horizontalalignment='left', verticalalignment='top', bbox=bbprops)
752| ss = ['Year Totals','-'*11]
753| xs = []
754| ys = []
755| for yr in sorted(stats.posts.keys()):
756| data = stats.posts[yr]
757| for mx,d in enumerate(data[0:12]):
758| xs.append(date(yr,1+mx,1))
759| ys.append(int(d))
760| ss.append('%d: %5d' % (yr,int(data[12])))
761| sstext = '\n'.join(ss)
762|
763|
764| fig, ax = plt.subplots()
765| ax.set_title(title, fontsize=13)
766|
767| ax.set_ylabel('Number of Posts', fontsize=11)
768|
769| ax.xaxis_date()
770| ax.set_xlim(date(Year0,1,1), date(YearN+1,1,1))
771| ax.xaxis.set_major_locator(YearLocator())
772| ax.xaxis.set_major_formatter(DateFormatter('%b \'%y'))
773| ax.xaxis.set_minor_locator(MonthLocator(interval=1))
774| ax.xaxis.set_minor_formatter(NullFormatter())
775| for tick in ax.xaxis.get_major_ticks():
776| tick.label1.set_rotation('vertical')
777| tick.label1.set_size(9)
778|
779| ax.set_ylim(0, 12)
780| ax.yaxis.set_major_locator(MultipleLocator(2))
781| ax.yaxis.set_minor_locator(MultipleLocator(1))
782| ax.yaxis.set_major_formatter(FormatStrFormatter('%d'))
783|
784| ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.0,ls='-', alpha=1.0, zorder=1)
785| ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.5,ls='-', alpha=1.0, zorder=0)
786|
787| ax.bar(xs,ys, color='#3366cc', width=25, alpha=0.75, zorder=10)
788| ax.text(date(2017,6,1),11, sstext, **ssprops)
789|
790| fig.set_figwidth(12.0)
791| fig.set_figheight(4.8)
792| fig.subplots_adjust(left=0.05, right=0.99, bottom=0.13, top=0.94)
793| filename = path.join(fpath, fname)
794| fig.savefig(filename)
795| Log.info(f'wrote: {filename}')
796| Log.info()
797| return 'Done'
798|
799|
800| def do_page_hits_by_year_chart (title=f'{BlogName}: Page Views by Year', fname='.png', fpath=ImgsPath):
801| """CMND: Do Page Views chart."""
802| fpath = KWARG('fpath', ImgsPath, str, kwargs)
803| fname = KWARG('fname', 'page-hits-by-year.png', str, kwargs)
804| Log.info('PAGE-HITS-BY-YEAR-CHART:: %s' % str(list(kwargs.keys())))
805| Log.info('fpath="%s"' % fpath)
806| Log.info('fname="%s"' % fname)
807| Log.info()
808| stats = Stats()
809|
810| xs1 = [date(yr,1,1) for yr in range(Year0, YearN+1)]
811| xs2 = [date(yr,2,1) for yr in range(Year0, YearN+1)]
812| ys1 = stats.hits_all
813| ys2 = [t[0]-t[1] for t in zip(stats.hits_all, stats.hits_home)]
814| ys3 = stats.visitors
815|
816| fig, ax = plt.subplots()
817| ax.set_title(title, loc='right', fontsize=13, fontweight='bold')
818| ax.set_ylabel('Number of Page Views', fontsize=10, fontweight='bold')
819|
820| ax.xaxis_date()
821| ax.set_xlim(date(Year0-1,7,1), date(YearN+1,7,1))
822| ax.xaxis.set_major_locator(MonthLocator(bymonth=1, interval=1))
823| ax.xaxis.set_minor_locator(NullLocator())
824| ax.xaxis.set_major_formatter(DateFormatter('\'%y'))
825|
826| ax.set_ylim(0, 4000)
827| ax.yaxis.set_major_locator(MultipleLocator(1000))
828| ax.yaxis.set_minor_locator(MultipleLocator(250))
829| ax.yaxis.set_major_formatter(FormatStrFormatter('%d'))
830|
831| ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.0,ls='-', alpha=1.0, zorder=1)
832| ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.5,ls='-', alpha=1.0, zorder=0)
833|
834| ax.bar(xs1,ys1, label='Views', color='#0066cc', width=300, alpha=0.75, zorder=10)
835| ax.bar(xs1,ys3, label='Visitors', color='#003f7f', width=200, alpha=0.75, zorder=11)
836| ax.plot(xs2,ys2, label='Home', color='#000000', lw=3.0, alpha=0.50, zorder=12)
837| ax.legend(bbox_to_anchor=(0.0,1.00), loc='upper left', shadow=True)
838|
839| fig.set_figwidth(6.0)
840| fig.set_figheight(3.0)
841| fig.subplots_adjust(left=0.13, right=0.98, bottom=0.10, top=0.90)
842| filename = path.join(fpath, fname)
843| fig.savefig(filename)
844| Log.info(f'wrote: {filename}')
845| Log.info()
846| return 'Done'
847|
848|
849| def chart_initialize (title, ymin=0, ymax=200, xmin=StartDate, xmax=date(YearN+1,1,1)):
850| """Chart Fragment: Initialize Chart."""
851|
852| fig, ax = plt.subplots()
853| ax.set_title(title, fontsize=13)
854|
855|
856|
857| ax.xaxis_date()
858| ax.set_xlim(xmin, xmax)
859| ax.xaxis.set_major_locator(MonthLocator(bymonth=1, interval=1))
860| ax.xaxis.set_minor_locator(MonthLocator())
861| ax.xaxis.set_major_formatter(DateFormatter('%b \'%y'))
862| for tick in ax.xaxis.get_major_ticks():
863| tick.label1.set_rotation('vertical')
864| tick.label1.set_size(9)
865|
866| ax.set_ylim(ymin, ymax)
867|
868| ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.0,ls='-', alpha=1.0, zorder=1)
869| ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.5,ls='-', alpha=1.0, zorder=0)
870| return fig,ax
871|
872| def chart_save (fig, filename, width=12.0, height=4.8, left=0.04, right=0.99, bottom=0.13, top=0.94):
873| """Chart Fragment: Save Image."""
874| fig.set_figwidth(width)
875| fig.set_figheight(height)
876| fig.subplots_adjust(left=left, right=right, bottom=bottom, top=top)
877| fig.savefig(filename)
878| Log.info('wrote: %s' % filename)
879|
880| def chart_one_post (post, fname, fpath=ImgsPath, xmin=StartDate):
881| """Create a Chart for a Post."""
882| Log.info('CHART-ONE-POST:: "%s"' % post)
883| Log.info('fpath="%s"' % fpath)
884| Log.info('fname="%s"' % fname)
885| Log.info()
886| xs = []
887| ys = []
888| for yr,_,hitdata in post.hits:
889| for mx,h in enumerate(hitdata):
890| xs.append(date(yr,1+mx,1))
891| ys.append(int(h))
892|
893| Log.info('max(ys)=%s' % max(ys))
894| ymax = post.chart_max if post.chart_max else (((max(ys)//50)+1)*50)
895| Log.info('ymax=%d' % ymax)
896|
897| title = f'{post.name} [{post.total:,d} views]'
898| fig,ax = chart_initialize(title, ymax=ymax, xmin=xmin)
899| ax.bar(xs,ys, color='#3355cc', width=31, alpha=0.85, zorder=10)
900|
901| filename = path.join(fpath, fname)
902| chart_save(fig, filename, height=3.2, bottom=0.18, top=0.91)
903| plt.close(fig)
904|
905|
906| def do_one_post_chart (**kwargs):
907| """CMND: Do One Post Chart."""
908| fpath = KWARG('fpath', ImgsPath, str, kwargs)
909| fname = KWARG('fname', 'selected-posts-one.out', str, kwargs)
910| dpath = KWARG('dpath', DataPath, str, kwargs)
911| dname = KWARG('dname', SelectedPosts.FileName, str, kwargs)
912| pname = KWARG('post', 'About', str, kwargs)
913| Log.info('SELECTED-POSTS-ONE:: %s' % str(kwargs))
914| Log.info('fpath="%s"' % fpath)
915| Log.info('fname="%s"' % fname)
916| Log.info('dname="%s"' % dname)
917| Log.info('dpath="%s"' % dpath)
918| Log.info('post-name="%s"' % pname)
919| Log.info()
920|
921| posts = SelectedPosts(fname=dname, fpath=dpath)
922| Log.debug(posts)
923| Log.debug()
924|
925| p = posts(pname)
926| if p:
927| Log.info(p)
928| fname = '%s.png' % SafeName(p.name)
929| chart_one_post(p, fname)
930| Log.info()
931| return 'Done'
932|
933| def do_all_post_charts (**kwargs):
934| """CMND: Do All Post Charts."""
935| fpath = KWARG('fpath', ImgsPath, str, kwargs)
936| fname = KWARG('fname', 'selected-posts-all.out', str, kwargs)
937| dpath = KWARG('dpath', DataPath, str, kwargs)
938| dname = KWARG('dname', SelectedPosts.FileName, str, kwargs)
939| Log.info('SELECTED-POSTS-ALL:: %s' % str(kwargs))
940| Log.info('fpath="%s"' % fpath)
941| Log.info('fname="%s"' % fname)
942| Log.info('dname="%s"' % dname)
943| Log.info('dpath="%s"' % dpath)
944| Log.info()
945|
946| obj = SelectedPosts(fname=dname, fpath=dpath)
947| Log.debug(obj)
948| Log.debug()
949|
950| for p in obj.posts:
951| print(p)
952| Log.info(p)
953| fname = '%s.png' % SafeName(p.name)
954| chart_one_post(p, fname)
955| Log.info()
956| return 'Done'
957|
958| def do_combined_posts_chart (**kwargs):
959| """CMND: Do Chart: Posts, Combined."""
960| fpath = KWARG('fpath', ImgsPath, str, kwargs)
961| fname = KWARG('fname', 'sel-posts-combined.png', str, kwargs)
962| dpath = KWARG('dpath', DataPath, str, kwargs)
963| dname = KWARG('dname', SelectedPosts.FileName, str, kwargs)
964| title = KWARG('title', f'{BlogName}: Post/Page Views (Selected Posts)', str, kwargs)
965| Log.info('SELECTED-POSTS-COMBINED:: %s' % str(kwargs))
966| Log.info('fpath="%s"' % fpath)
967| Log.info('fname="%s"' % fname)
968| Log.info('dname="%s"' % dname)
969| Log.info('dpath="%s"' % dpath)
970| Log.info('title="%s"' % title)
971| Log.info()
972|
973| stats = SelectedPosts(fname=dname, fpath=dpath)
974| Log.debug(stats)
975| Log.debug()
976|
977|
978| fig,ax = chart_initialize(title, ymax=1000)
979|
980|
981| accum = {}
982| for px,post in enumerate(stats.posts):
983| if post.name in ['Home']:
984| continue
985| for yr,_,hitdata in post.hits:
986| for mx,h in enumerate(hitdata):
987| dt = date(yr,1+mx,1)
988| if dt not in accum: accum[dt] = 0
989| accum[dt] += int(h)
990|
991| xs = list(sorted(accum.keys()))
992| ys = [accum[dt] for dt in xs]
993| wa = 6
994| ya = ([0]*wa) + [sum(ys[ix-wa:ix])/wa for ix in range(wa,len(ys))]
995| wb = 12
996| yb = ([0]*wb) + [sum(ys[ix-wb:ix])/wb for ix in range(wb,len(ys))]
997| wc = 18
998| yc = ([0]*wc) + [sum(ys[ix-wc:ix])/wc for ix in range(wc,len(ys))]
999|
1000| ax.fill_between(xs,ys,0, label='Views per month', color='#009966', alpha=0.75, zorder=10)
1001| ax.plot(xs,ya, label='Avg (rolling %d)'%wa, color='#ff0000', lw=1.5, alpha=1.00, zorder=11)
1002| ax.plot(xs,yb, label='Avg (rolling %d)'%wb, color='#0000ff', lw=1.5, alpha=1.00, zorder=12)
1003| ax.plot(xs,yc, label='Avg (rolling %d)'%wc, color='#000000', lw=2.5, alpha=1.00, zorder=13)
1004| ax.legend(bbox_to_anchor=(0.0,1.0), loc='upper left', shadow=True)
1005|
1006|
1007| filename = path.join(fpath, fname)
1008| chart_save(fig, filename)
1009| Log.info('wrote: %s' % filename)
1010| return 'Done'
1011|
1012|
1013| def do_overlay_posts_chart (**kwargs):
1014| """CMND: Do Chart, Posts, Overlayed."""
1015| fpath = KWARG('fpath', ImgsPath, str, kwargs)
1016| fname = KWARG('fname', 'sel-posts-overlay.png', str, kwargs)
1017| dpath = KWARG('dpath', DataPath, str, kwargs)
1018| dname = KWARG('dname', SelectedPosts.FileName, str, kwargs)
1019| title = KWARG('title', f'{BlogName}: Post/Page Views (Selected Posts)', str, kwargs)
1020| Log.info('SELECTED-POSTS-OVERLAY:: %s' % str(kwargs))
1021| Log.info('fpath="%s"' % fpath)
1022| Log.info('fname="%s"' % fname)
1023| Log.info('dname="%s"' % dname)
1024| Log.info('dpath="%s"' % dpath)
1025| Log.info('title="%s"' % title)
1026| Log.info()
1027|
1028| stats = SelectedPosts(fname=dname, fpath=dpath)
1029| Log.debug(stats)
1030| Log.debug()
1031|
1032|
1033| fig,ax = chart_initialize(title, ymax=250)
1034|
1035| for px,p in enumerate(stats.posts):
1036| if p.name in ['Home']:
1037| continue
1038| xs = []
1039| ys = []
1040| for yr,_,hitdata in p.hits:
1041| for mx,h in enumerate(hitdata):
1042| xs.append(date(yr,1+mx,1))
1043| ys.append(int(h))
1044| ax.fill_between(xs,ys,0, label=p.name, alpha=0.50, zorder=10+px)
1045|
1046|
1047| filename = path.join(fpath, fname)
1048| chart_save(fig, filename)
1049| Log.info()
1050| return 'Done'
1051|
1052|
1053| def do_check_selected_posts (**kwargs):
1054| """CMND: Do Selected Posts check."""
1055| fpath = KWARG('fpath', BasePath, str, kwargs)
1056| fname = KWARG('fname', 'selected-posts.out', str, kwargs)
1057| dpath = KWARG('dpath', DataPath, str, kwargs)
1058| dname = KWARG('dname', SelectedPosts.FileName, str, kwargs)
1059| arg1 = KWARG('arg1', 'foo', str, kwargs)
1060| arg2 = KWARG('arg2', 'bar', str, kwargs)
1061| arg3 = KWARG('arg3', 'geg', str, kwargs)
1062| Log.info('SELECTED-POSTS-CHECK:: %s' % str(kwargs))
1063| Log.info('fpath="%s"' % fpath)
1064| Log.info('fname="%s"' % fname)
1065| Log.info('dname="%s"' % dname)
1066| Log.info('dpath="%s"' % dpath)
1067| Log.info('argument-1="%s"' % arg1)
1068| Log.info('argument-2="%s"' % arg2)
1069| Log.info('argument-3="%s"' % arg3)
1070| Log.info()
1071|
1072|
1073| posts = SelectedPosts(fname=dname, fpath=dpath)
1074|
1075| if fname:
1076| posts.save(fname=fname, fpath=fpath)
1077|
1078|
1079| Log.info()
1080| Log.debug(posts)
1081| Log.debug()
1082|
1083|
1084| if 0 < len(posts.errs):
1085| Log.info('Errors:')
1086| for e in posts.errs:
1087| Log.error(e)
1088| Log.info()
1089|
1090|
1091| Log.info('Posts:')
1092| for p in posts:
1093| Log.info(p)
1094| Log.info()
1095|
1096| Log.info('Posts (sorted/all):')
1097| for px,p in enumerate(sorted(posts, key=lambda x:x.total, reverse=True)):
1098| d = '*' if px != p.rank else ' '
1099| s = '%s%2d/%2d: %s (%d)' % (d, px, p.rank, p.name, p.total)
1100| Log.info(s)
1101| Log.info()
1102|
1103| Log.info(f'Posts (sorted/{YearN}):')
1104| for px,p in enumerate(sorted(posts, key=lambda x:x.hits[-1][1], reverse=True)):
1105| d = '*' if px != p.rank_year else ' '
1106| s = '%s%2d/%2d: %s (%d)' % (d, px, p.rank_year, p.name, p.hits[-1][1])
1107| Log.info(s)
1108| Log.info()
1109|
1110| return 'Done'
1111|
1112|
1113| def do_selected_posts_page (**kwargs):
1114| """CMND: Do Selected Posts Page."""
1115| fpath = KWARG('fpath', BasePath, str, kwargs)
1116| fname = KWARG('fname', 'selected-posts.out', str, kwargs)
1117| dpath = KWARG('dpath', DataPath, str, kwargs)
1118| dname = KWARG('dname', SelectedPosts.FileName, str, kwargs)
1119| Log.info('SELECTED-POSTS-PAGE:: %s' % str(kwargs))
1120| Log.info('fpath="%s"' % fpath)
1121| Log.info('fname="%s"' % fname)
1122| Log.info('dname="%s"' % dname)
1123| Log.info('dpath="%s"' % dpath)
1124| Log.info()
1125| css_tab = 'font-size:13px;border-spacing:0;padding:0;margin:10px 20px 30px 10px;'
1126| css_th1 = 'background-color:#000000;color:#ffffff;'
1127| css_th2 = 'background-color:#000000;color:#ffffff;font-size:15px;text-align:left;vertical-align:center;padding-left:10px;'
1128| css_th3 = 'background-color:#000000;color:#ffffff;'
1129| css_td0 = 'font-weight:bold;text-align:left;'
1130| css_td1 = 'font-weight:normal;font-style:italic;'
1131| css_td2 = 'font-size:15px;font-weight:bold;'
1132| css_td3 = 'font-size:17px;font-family:monospace;font-weight:bold;text-align:right;padding-left:15px;'
1133|
1134|
1135| posts = SelectedPosts(fname=dname, fpath=dpath)
1136| Log.debug(posts)
1137| Log.debug()
1138|
1139|
1140| fn = path.join(HtmlPath, 'selected_posts.html')
1141| pg = WebPage('Selected Posts', h1=BlogName, h2='Stats & Charts', css=['/basic.css'])
1142| pg.add()
1143| pg.add('<table style="%s">' % css_tab)
1144| pg.add('<thead>')
1145| pg.add('<tr>')
1146| pg.add('<th style="%s">Rank</th>' % css_th1)
1147| pg.add('<th colspan="12" rowspan="2" style="%s">Post Name (and Link)</th>' % css_th2)
1148| pg.add('<th style="%s">Total</th>' % css_th3)
1149| pg.add('</tr>')
1150| pg.add('<tr>')
1151| pg.add('<th style="%s">All <em style="font-weight:normal;">(%s)</em></th>' % (css_th3,YearN))
1152| pg.add('<th style="%s">Views</th>' % css_th3)
1153| pg.add('</tr>')
1154| pg.add('</thead>')
1155| pg.add('<tbody>')
1156|
1157| for px,p in enumerate(sorted(posts, key=lambda x:x.total, reverse=True)):
1158| pg.add('<tr>')
1159| pg.add('<td style="%s">%d <span style="%s">(%d)</span></th>' % (css_td0,p.rank,css_td1,p.rank_year))
1160| pg.add('<td colspan="12" style="%s"><a target="_blank" href="%s">%s</a></td>' % (css_td2,p.url,p.name))
1161| pg.add('<td style="%s">%s</td>' % (css_td3,add_commas(p.total)))
1162| pg.add('</tr>')
1163| pg.add('<tr><td colspan="14" style="padding:1px 0;border-bottom:1px solid black;"></td></tr>')
1164| for row in p.hits:
1165| pg.add('<tr>')
1166| pg.add('<th style="%s">%d</th>' % ('',row[0]))
1167| for mon in row[2]:
1168| css = 'text-align:right;' if mon else 'color:#9f9f9f;text-align:right;'
1169| pg.add('<td style="%s">%d</th>' % (css,mon))
1170| css = 'text-align:right;'
1171| pg.add('<td style="%s">%s</th>' % (css,add_commas(row[1])))
1172| pg.add('</tr>')
1173| pg.add('<tr><td colspan="14" style="padding:5px 0 9px 0;border-top:3px solid black;"></td></tr>')
1174| pg.add()
1175|
1176| pg.add('</tbody>')
1177| pg.add('</table>')
1178| pg.add()
1179| pg.save(fn, log=Log)
1180|
1181| return 'Done'
1182|
1183|
1184| def do_selected_posts_links_page (**kwargs):
1185| """CMND: Do Selected Posts Stats Page Links Page."""
1186| fpath = KWARG('fpath', BasePath, str, kwargs)
1187| fname = KWARG('fname', 'sel-posts-stats-links.html', str, kwargs)
1188| dpath = KWARG('dpath', DataPath, str, kwargs)
1189| dname = KWARG('dname', SelectedPosts.FileName, str, kwargs)
1190| Log.info('SELECTED-POSTS-LINKS-PAGE:: %s' % str(list(kwargs.keys())))
1191| Log.info('fpath="%s"' % fpath)
1192| Log.info('fname="%s"' % fname)
1193| Log.info('dpath="%s"' % dpath)
1194| Log.info('dname="%s"' % dname)
1195| Log.info()
1196|
1197|
1198| posts = SelectedPosts(fname=dname, fpath=dpath)
1199| Log.debug(posts)
1200| Log.debug()
1201|
1202|
1203| H2 = 'Post Stats Page Links'
1204| H3 = 'Selected Posts: Stats Page Links'
1205| pg = WebPage(f'{BlogCode}:Post Stats', h1=BlogName, h2=H2, h3=H3, css=['http://localhost/basic.css','http://localhost/index.css'])
1206|
1207| pg.add()
1208| pg.add('<ol>')
1209|
1210|
1211| for post in posts:
1212|
1213|
1214| if post.pid == 920:
1215| pg.add('</ol>')
1216| pg.add('<ol start="3">')
1217|
1218|
1219| link = f'https://wordpress.com/stats/post/{post.pid}/{SlugName}.com'
1220| text = f'<a href="{link}" target="PostStats">{post.name}</a>'
1221| pg.add(f'<li>{text}</li>')
1222|
1223| pg.add('</ol>')
1224| pg.add()
1225|
1226|
1227| pg.add(f'<ul>')
1228| pg.add(f'<li>URL Template: https://wordpress.com/stats/post/<strong>PID</strong>/{SlugName}.com</li>')
1229| pg.add(f'<li>Example: <a target="_blank" href="https://wordpress.com/stats/post/4/thehardcorecoder.com">New Blog!</a>')
1230| pg.add(f'</ul>')
1231| pg.add()
1232|
1233|
1234| filename = path.join(fpath, fname)
1235| pg.save(filename, log=Log)
1236|
1237| Log.info()
1238| return 'Done'
1239|
1240|
1241| def do_visitors_per_month_chart (**kwargs):
1242| """CMND: Visitors per month chart. (Uses the visitors-per-month TAB file.)"""
1243| fpath = KWARG('fpath', DataPath, str, kwargs)
1244| fname = KWARG('fname', 'visitors-per-month.tab', str, kwargs)
1245| ipath = KWARG('ipath', ImgsPath, str, kwargs)
1246| ymax = KWARG('ymax', 800, int, kwargs)
1247| Log.info('POST-HITS-BY-YEAR:: %s' % str(list(kwargs.keys())))
1248| Log.info('fpath="%s"' % fpath)
1249| Log.info('fname="%s"' % fname)
1250| Log.info('ipath="%s"' % ipath)
1251| Log.info('max-y=%d' % ymax)
1252| Log.info()
1253| datafile = path.join(fpath, fname)
1254|
1255| class visits_per_month_chart (mlmonthchart):
1256| def __init__ (self, data, **kwargs):
1257| super().__init__(**kwargs)
1258| self.data = data
1259| self.title = f'{BlogName}: Blog Visitors per Month'
1260| self.x_limit = (date(Year0,1,1),date(YearN+1,1,1))
1261| self.y_title = 'Visitors'
1262| self.y_limit = (0, 3000)
1263| self.y_grids = (500, 100)
1264| self.y_tickf = '%d'
1265| self.fname = 'visitors_per_month.png'
1266| self.fpath = ipath
1267|
1268| def plotter (self):
1269| xs = [t[0] for t in self.data]
1270| ys = [t[1] for t in self.data]
1271| self.ax.fill_between(xs,ys, color='#336699', lw=2.0, alpha=0.80, zorder=11)
1272|
1273| data = tabfile(datafile)
1274| data.load()
1275| stats = [[SpecialK(n) if ix else int(n) for ix,n in enumerate(row)] for row in data]
1276| stuff = []
1277| for row in stats:
1278| Log.info(row)
1279| yr = row[0]
1280| for mon,visits in enumerate(row[1:13]):
1281| datum = (date(yr,mon+1,1), visits)
1282| stuff.append(datum)
1283| Log.info()
1284| Log.info(stuff[0:12])
1285|
1286| cht = visits_per_month_chart(stuff)
1287| cht.make()
1288| Log.info('wrote: %s' % path.join(cht.fpath,cht.fname))
1289| Log.info()
1290| return 'Done'
1291|
1292|
1293| def do_avg_visitors_per_day_chart (**kwargs):
1294| """CMND: Average Visitors per day chart. (Uses the visitors-per-day-avg TAB file.)"""
1295| fpath = KWARG('fpath', DataPath, str, kwargs)
1296| fname = KWARG('fname', 'visitors-per-day-avg.tab', str, kwargs)
1297| ipath = KWARG('ipath', ImgsPath, str, kwargs)
1298| ymax = KWARG('ymax', 800, int, kwargs)
1299| Log.info('POST-HITS-BY-YEAR:: %s' % str(list(kwargs.keys())))
1300| Log.info('fpath="%s"' % fpath)
1301| Log.info('fname="%s"' % fname)
1302| Log.info('ipath="%s"' % ipath)
1303| Log.info('max-y=%d' % ymax)
1304| Log.info()
1305| datafile = path.join(fpath, fname)
1306|
1307| class visits_per_day_chart (mlmonthchart):
1308| def __init__ (self, data, **kwargs):
1309| super().__init__(**kwargs)
1310| self.data = data
1311| self.title = f'{BlogName}: Average Blog Visitors per Day'
1312| self.x_limit = (date(Year0,1,1),date(YearN+1,1,1))
1313| self.y_title = 'Average #of Visitors'
1314| self.y_limit = (0, 100)
1315| self.y_grids = (25, 5)
1316| self.y_tickf = '%d'
1317| self.fname = 'visitors_per_day.png'
1318| self.fpath = ipath
1319|
1320| def plotter (self):
1321| xs = [t[0] for t in self.data]
1322| ys = [t[1] for t in self.data]
1323| self.ax.fill_between(xs,ys, color='#336699', lw=2.0, alpha=0.80, zorder=11)
1324|
1325| data = tabfile(datafile)
1326| data.load()
1327| stats = [[int(n) for n in row] for row in data]
1328| stuff = []
1329| for row in stats:
1330| Log.info(row)
1331| yr = row[0]
1332| for mon,visits in enumerate(row[1:13]):
1333| datum = (date(yr,mon+1,1), visits)
1334| stuff.append(datum)
1335| Log.info()
1336| Log.info(stuff[0:12])
1337|
1338| cht = visits_per_day_chart(stuff)
1339| cht.make()
1340| Log.info('wrote: %s' % path.join(cht.fpath,cht.fname))
1341| Log.info()
1342| return 'Done'
1343|
1344|
1345| def do_update_csv_hits_files (**kwargs):
1346| """CMND: Update Post Hits CSV files; change 'http:' to 'https:'."""
1347| dpath = KWARG('dpath', DataPath, str, kwargs)
1348| Log.info('UPDATE CSV FILES:: %s' % str(list(kwargs.keys())))
1349| Log.info('dpath="%s"' % dpath)
1350| Log.info()
1351|
1352|
1353| ff = filefinder(DataPath)
1354| ff.add_include_item(f'^{SlugName}_posts_')
1355| ff.scan()
1356|
1357|
1358| for fname in ff:
1359|
1360| if not fname.endswith('.csv'):
1361| Log.warn(f'Not a CSV file: {fname}')
1362| continue
1363|
1364|
1365| Log.info(fname)
1366| fo = linefile(fname)
1367| fo.load()
1368| Log.info(f'> {len(fo)} lines.')
1369|
1370|
1371| flag = False
1372| for ix,line in enumerate(fo.data):
1373| if 'http:' in line:
1374| flag = True
1375| fo.data[ix] = line.replace('http:', 'https:')
1376|
1377| if flag:
1378| Log.info('Rename CSV file.')
1379| backup_name = fname.replace('.csv', '.old')
1380| Log.debug(backup_name)
1381| rename(fname, backup_name)
1382|
1383| Log.info('Save updated CSV file.')
1384| fo.save()
1385| else:
1386| Log.info('No occurences of "http:" found.')
1387|
1388| Log.info()
1389|
1390| Log.info()
1391| return 'Done'
1392|
1393|
1394| def do_test (**kwargs):
1395| """CMND: Do Test."""
1396| fpath = KWARG('fpath', BasePath, str, kwargs)
1397| fname = KWARG('fname', 'test.html', str, kwargs)
1398| dpath = KWARG('dpath', DataPath, str, kwargs)
1399| dname = KWARG('dname', SelectedPosts.FileName, str, kwargs)
1400| year = KWARG('year', YearN, int, kwargs)
1401| Log.info('TEST:: %s' % str(list(kwargs.keys())))
1402| Log.info('fpath="%s"' % fpath)
1403| Log.info('fname="%s"' % fname)
1404| Log.info('dpath="%s"' % dpath)
1405| Log.info('dname="%s"' % dname)
1406| Log.info()
1407| filename = path.join(fpath, fname)
1408|
1409|
1410| Log.info()
1411| return 'Done'
1412|
1413| def dispatch (cmd, **kwargs):
1414| """Dispatch CMD to an Action function in this module."""
1415| Log.info('command: %s' % cmd)
1416| for kw in kwargs:
1417| Log.info('argument[%s]: %s' % (kw,kwargs[kw]))
1418| Log.info()
1419| if cmd == 'b:cats.list' : return do_blog_categories_list(**kwargs)
1420| if cmd == 'p:page.over' : return do_stats_overview_page(**kwargs)
1421| if cmd == 'p:page.hits' : return do_page_hits_page(**kwargs)
1422| if cmd == 'p:top.posts' : return do_top_posts_page(**kwargs)
1423| if cmd == 'p:charts' : return do_charts_list_page(**kwargs)
1424| if cmd == 'c:hits.year' : return do_page_hits_by_year_chart(**kwargs)
1425| if cmd == 'c:posts.yr' : return do_posts_per_year_chart(**kwargs)
1426| if cmd == 'c:posts.mo' : return do_posts_per_month_chart(**kwargs)
1427| if cmd == 'c:words.post': return do_words_per_post_chart(**kwargs)
1428| if cmd == 'c:visit1' : return do_visitors_per_month_chart(**kwargs)
1429| if cmd == 'c:visit2' : return do_avg_visitors_per_day_chart(**kwargs)
1430| if cmd == 'c:views' : return do_views_and_visitors_chart(**kwargs)
1431| if cmd == 'c:views.avg' : return do_avg_views_per_day_chart(**kwargs)
1432| if cmd == 'c:post.hits' : return do_post_hits_by_year_chart(**kwargs)
1433| if cmd == 'csv.update' : return do_update_csv_hits_files(**kwargs)
1434| if cmd == 'sel.check' : return do_check_selected_posts(**kwargs)
1435| if cmd == 'p:sel.posts' : return do_selected_posts_page(**kwargs)
1436| if cmd == 'c:sel.all' : return do_all_post_charts(**kwargs)
1437| if cmd == 'c:sel.one' : return do_one_post_chart(**kwargs)
1438| if cmd == 'c:sel.over' : return do_overlay_posts_chart(**kwargs)
1439| if cmd == 'c:sel.comb' : return do_combined_posts_chart(**kwargs)
1440| if cmd == 'sel.links' : return do_selected_posts_links_page(**kwargs)
1441| if cmd == 'test' : return do_test(**kwargs)
1442| return 'Nothing to do!'
1443|
1444| if __name__ == '__main__':
1445| print('autorun: %s' % argv[0])
1446| Log.start(path.join(BasePath,'pages-and-charts.log'))
1447| Log.level(debug())
1448| cmd = argv[1] if 1 < len(argv) else CMND
1449| kwargs = ARGS
1450| for a in argv[2:]:
1451| nv = a.split('=', 1)
1452| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
1453| Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
1454| try:
1455| obj = dispatch(cmd, **kwargs)
1456| print()
1457| print(obj)
1458| Log.info()
1459| Log.info(obj)
1460| except:
1461| etype, evalue, tb = exc_info()
1462| ts = extract_tb(tb)
1463| Log.error()
1464| Log.error('%s: %s' % (etype.__name__,str(evalue)))
1465| for t in ts[-9:]:
1466| Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
1467| Log.error(' %s' % t[3])
1468| Log.error()
1469| Log.error()
1470| raise
1471| finally:
1472| Log.end()
1473|
1474| '''eof'''
1475|