posts.html


001| '''Substack Tasks.
001| 
001| Classes:
001|     Blogs                                   -global blog definitions
001|     Posts                                   -all Blogs, All Posts
001| 
001| Commands:
001|     p.index     do_posts_index_page         -all posts HTML index (new first; year groups)
001|     p.time      do_posts_timeline_page      -all posts HTML timeline (old first; month groups)
001|     p.cal       do_posts_calendar_page      -all posts HTML year calendar
001|     c.p/m       do_posts_per_month_chart    -all posts monthly chart
001|     c.p/y       do_posts_per_year_chart     -all posts yearly chart
001| 
001|     all         do_all_posts                -Index, Timeline, & Charts
001|     p.cal.all   do_all_calendar_years       -HTML year calendars for all blogging years
001|     list        do_lcc_hcc_posts_lists      -generate TAB file of LCC and HCC posts
001|     test        do_test                     -test
001| '''

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from datetime import date, datetime, timedelta
007| import matplotlib.pyplot as plt
008| import matplotlib.ticker as mlticks
009| import matplotlib.dates as mldates
010| from logger import logger,info,debug,trace, LogFilenameTimestamp
011| from goodies import KWARG, typename, plural
012| from files import linefile, csvfile, tabfile
013| from dbsql import dbTable
014| from mlchart import mlchart
015| from webpage import WebPage, make_web_calendar
016| ####################################################################################################
017| BasePath = r'C:\CJS\prj\Python\blog'
018| DataPath = BasePath
019| HtmlBase = r'C:\CJS\www\root\cjs\blog'
020| Log = logger('posts')
021| 
022| CMND = 'p.cal.all'
023| ARGS = {
024|     #'year': '2026',
025|     #'fname': 'posts.out',
026|     #'fpath': BasePath,
027|     #'dname': 'posts.tab',
028|     #'dpath': DataPath,
029| }
030| 
031| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
032| class Blogs:
033|     LCC = 1
034|     HCC = 2
035|     Sub = 3
036|     Name = ['', 'Logos con Carne', 'Hard-Core Coder', 'Substack']
037|     Tag  = ['', 'LCC', 'HCC', 'Sub']
038|     Colors = ['','#3366cc', '#990000', '#ff6719']
039|     Xref = {'LCC':LCC, 'HCC':HCC, 'Sub':Sub}
040| 
041| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
042| class BlogDbPosts:
043|     HCC_Code = 'HCC'
044|     LCC_Code = 'LCC'
045|     HCC_Path = path.join(HtmlBase, 'hcc')
046|     LCC_Path = path.join(HtmlBase, 'lcc')
047|     FileName = 'blog-db-posts.tab'
048| 
049|     def __init__ (self):
050|         self.hcc_filename = path.join(self.HCC_Path, self.FileName)
051|         self.lcc_filename = path.join(self.LCC_Path, self.FileName)
052|         self.hcc_file = tabfile(self.hcc_filename)
053|         self.lcc_file = tabfile(self.lcc_filename)
054|         self.hcc_file.load()
055|         self.lcc_file.load()
056| 
057|         def parse_record (r):
058|             f0 = datetime.strptime(r[1], '%Y-%m-%d %H:%M:%S')
059|             f1 = r[2]   # Post Title
060|             f2 = r[0]   # Post ID
061|             f3 = r[3]   # Post URL
062|             return (f0, f1, f2, f3)
063| 
064|         self.hcc_data = [parse_record(rcd) for rcd in self.hcc_file]
065|         self.lcc_data = [parse_record(rcd) for rcd in self.lcc_file]
066|         self.hcc_data.sort(key=lambda t:t[0], reverse=True)
067|         self.lcc_data.sort(key=lambda t:t[0], reverse=True)
068| 
069|     def __repr__ (self):
070|         return f'<{typename(self)} lcc:{len(self.lcc_data)} hcc:{len(self.hcc_data)} @{id(self):08x}>'
071| 
072|     @property
073|     def hcc (self): return self.hcc_data
074| 
075|     @property
076|     def lcc (self): return self.lcc_data
077| 
078| 
079| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
080| class Posts:
081|     '''All the Blogs, All the Posts!'''
082|     NameMaxLength = 60
083| 
084|     def __init__ (self, fname='posts.tab', fpath=BasePath):
085|         '''New Posts instance.'''
086|         self.filename = path.join(fpath,fname) if fpath else fname
087|         self.posts = []
088|         self.years = {}
089|         self.months = {}
090|         self.total = 0
091|         # Load the list-of-posts data file...
092|         self.fobj = tabfile(self.filename, headers=True)
093|         self.fobj.load()
094| 
095|         # Process the file data...
096|         for post in self.fobj:
097|             # If the first field is empty, skip the line...
098|             if len(post[0]) == 0:
099|                 continue
100|             # Ignore comment lines (start with ";" or "#")...
101|             if post[0].startswith(';') or post[0].startswith('#'):
102|                 continue
103| 
104|             # Translate the tag field...
105|             tag = Blogs.Xref[post[0]]
106|             # Translate the data field...
107|             dt = date(int(post[1]), int(post[2]), int(post[3]))
108|             # Get the name field...
109|             name = post[4]
110|             pid = int(post[5])
111|             url = post[6]
112|             self.posts.append((tag,dt,name,pid,url))
113|             self.total += 1
114| 
115|             # Update years and months counters...
116|             if dt.year not in self.years: self.years[dt.year] = 0
117|             self.years[dt.year] += 1
118| 
119|             key = (dt.year,dt.month)
120|             if key not in self.months: self.months[key] = 0
121|             self.months[key] += 1
122| 
123|     def __iter__(self): return iter(self.posts)
124|     def __len__(self): return len(self.posts)
125|     def __getitem__(self, ix): return self.posts[ix]
126| 
127|     def __repr__ (self):
128|         return f'<{typename(self)} @{id(self):012x}>'
129| 
130|     def __str__ (self):
131|         return f'{self.filename} ({len(self)} posts)'
132| 
133|     @property
134|     def total_posts (self):
135|         return self.total
136| 
137|     def year_count (self, curr_year):
138|         '''Return posts count for a given year.'''
139|         return self.years[curr_year] if curr_year in self.years else 0
140| 
141|     def month_count (self, curr_date):
142|         '''Return posts count for a given year/month.'''
143|         key = (curr_date.year, curr_date.month)
144|         return self.months[key] if key in self.months else 0
145| 
146|     def index_webpage (self, fname='posts-index.html', fpath=BasePath):
147|         '''Generate an index webpage of all posts.'''
148|         props = {'h1':'Blogging', 'h2':'Posts Index', 'h3':'', 'css':['http://localhost/basic.css']}
149|         css0 = 'font-size:13px; border-spacing:0; padding:0; border:0; margin:13px;'
150|         css1 = 'background-color:#000000;color:#ffffff; font-family:monospace; font-size:9pt; padding:1px 6px; text-align:right;vertical-align:bottom; white-space:nowrap;'
151|         css2 = 'background-color:#efefef; font-size:10pt; padding:1px 10px; vertical-align:bottom; white-space:nowrap;'
152|         css3 = 'font-family:sans-serif; font-size:10pt; font-style:italic; padding:1px 2px; vertical-align:bottom; white-space:nowrap;'
153|         css4 = 'font-size:11pt; font-weight:bold; padding:1px 5px 2px 10px; vertical-align:bottom; white-space:nowrap;'
154|         css5 = 'background-color:#000099;color:#ffff00; font-size:12pt; font-weight:bold;'
155| 
156|         pag = WebPage('Posts:Timeline', **props)
157| 
158|         dts = [post[1] for post in self.posts]
159|         min_date = min(dts)
160|         max_date = max(dts)
161|         pag.add(f'<h3>{min_date:%B %d, %Y} &mdash; {max_date:%B %d, %Y} ({self.total_posts} posts)</h3>')
162|         pag.add()
163|         pag.add(f'<table style="{css0}">')
164|         pag.add('<tbody>')
165| 
166|         yhdr = '<td colspan="5" style="{css}padding-left:20px;">{year:4d} <span style="font-weight:normal;">({num} post{ss})</span></td>'
167|         ps = sorted(self.posts, key=lambda t:(t[1],t[2]), reverse=True)
168|         prev_date = None
169|         curr_year = None
170|         for ix,post in enumerate(ps):
171|             if post[1].year != curr_year:
172|                 curr_year = post[1].year
173|                 num = self.year_count(curr_year)
174|                 ss = plural(num)
175|                 pag.add(f'<tr>')
176|                 pag.add(f'<td colspan="2" style="{css5}"></td>')
177|                 pag.add(yhdr.format(year=post[1].year, num=num, ss=ss, css=css5))
178|                 pag.add(f'</tr>')
179| 
180|             pname = self.truncate(post[2])
181|             blgclr = f'color:{Blogs.Colors[post[0]]};'
182|             sdt1 = '' if post[1]==prev_date else post[1].strftime('%a')
183|             sdt2 = '' if post[1]==prev_date else post[1].strftime('%b')
184|             sdt3 = '' if post[1]==prev_date else post[1].strftime('%d')
185|             sdt4 = '' if post[1]==prev_date else post[1].strftime('%Y')
186|             pag.add(f'<tr>')
187|             pag.add(f'<td style="{css1}">{len(ps)-ix:3d}</td>')
188|             pag.add(f'<td style="{css2}{blgclr}">{Blogs.Name[post[0]]}</td>')
189|             pag.add(f'<td style="{css3}">{sdt1}</td>')
190|             pag.add(f'<td style="{css3}">{sdt2}</td>')
191|             pag.add(f'<td style="{css3}font-weight:bold;">{sdt3}</td>')
192|             pag.add(f'<td style="{css3}">{sdt4}</td>')
193|             pag.add(f'<td style="{css4}"><a target="_blank" href="{post[4]}">{pname}</a></td>')
194|             pag.add(f'</tr>')
195|             prev_date = post[1]
196| 
197|         pag.add('</tbody>')
198|         pag.add('</table>')
199| 
200|         fn = path.join(fpath, fname) if fpath else fname
201|         pag.save(fn, log=Log)
202| 
203|     def timeline_webpage (self, fname='posts-timeline.html', fpath=BasePath):
204|         '''Generate a timeline webpage of all dates and any posts on that date.'''
205|         props = {'h1':'Blogging', 'h2':'Posts Timeline', 'h3':'', 'css':['http://localhost/basic.css']}
206|         css0 = 'background-color:#000099; color:#ffff99; font-size:13pt; font-weight:bold; text-align:center;'
207|         css1 = 'white-space:nowrap; font-size:11pt; background-color:#000000; color:#ffffff;'
208|         css2 = 'white-space:nowrap; font-size:11pt; font-style:italic; padding:0 9px; background-color:#efefef;'
209|         css3 = 'white-space:nowrap; font-size:11pt; font-weight:bold;'
210| 
211|         def find_entry_by_date (dt):
212|             '''Find any posts on a given date.'''
213|             result = []
214|             for post in self.posts:
215|                 if post[1] == dt:
216|                     result.append(post)
217|             return result
218| 
219|         pag = WebPage('Posts:Calendar', **props)
220| 
221|         dts = [post[1] for post in self.posts]
222|         min_date = min(dts)
223|         max_date = max(dts)
224|         pag.add(f'<h3>{min_date:%B %d, %Y} &mdash; {max_date:%B %d, %Y} ({self.total_posts} posts)</h3>')
225|         pag.add()
226|         pag.add(f'<div><a href="#{max_date:y%Ym%m}">[{max_date:%B %Y}]</a></div>')
227|         pag.add()
228|         pag.add('<table>')
229|         pag.add('<tbody>')
230| 
231|         mhdr = '<tr><td colspan="5" style="{css}"><a name="{dt:y%Ym%m}"></a>{dt:%B %Y} <span style="font-weight:normal;">({num} post{ss})</span></td></tr>'
232|         one_day = timedelta(1)
233|         dt = min_date
234|         num = self.month_count(dt)
235|         pag.add(mhdr.format(dt=dt, num=num, ss=plural(num), css=css0))
236|         while dt <= max_date:
237|             if dt.day == 1:
238|                 num = self.month_count(dt)
239|                 pag.add(mhdr.format(dt=dt, num=num, ss=plural(num), css=css0))
240|             if dt in dts:
241|                 found = find_entry_by_date(dt)
242|                 for ix,post in enumerate(found):
243|                     sdt1 = '' if ix else dt.strftime('%a')
244|                     sdt2 = '' if ix else dt.strftime('%b')
245|                     sdt3 = '' if ix else dt.strftime('%d')
246|                     blgclr = f'color:{Blogs.Colors[post[0]]};'
247|                     pname = self.truncate(post[2])
248|                     pag.add(f'<tr>')
249|                     pag.add(f'<td style="{css1}">{sdt1}</td>')
250|                     pag.add(f'<td style="{css1}">{sdt2}</td>')
251|                     pag.add(f'<td style="{css1}font-weight:bold;">{sdt3}</td>')
252|                     pag.add(f'<td style="{css2}{blgclr}">{Blogs.Tag[post[0]]}</td>')
253|                     pag.add(f'<td style="{css3}"><a target="_blank" href="{post[4]}">{pname}</a></td>')
254|                     pag.add(f'</tr>')
255|             else:
256|                 pag.add(f'<tr>')
257|                 pag.add(f'<td style="{css1}">{dt:%a}</td>')
258|                 pag.add(f'<td style="{css1}">{dt:%b}</td>')
259|                 pag.add(f'<td style="{css1}font-weight:bold;">{dt:%d}</td>')
260|                 pag.add(f'<td style="{css2}">&nbsp;</td>')
261|                 pag.add(f'</tr>')
262|             dt = dt + one_day
263| 
264|         pag.add('</tbody>')
265|         pag.add('</table>')
266| 
267|         fn = path.join(fpath, fname) if fpath else fname
268|         pag.save(fn, log=Log)
269|         Log.info()
270| 
271|     @classmethod
272|     def truncate (cls, name):
273|         if len(name) < cls.NameMaxLength:
274|             return name
275|         return f'{name[:34]}...{name[-3:]}'
276| 
277| ##================================================================================================##
278| def do_posts_index_page (**kwargs):
279|     """CMND: Create an HTML index of all posts (newest to oldest; year sections)."""
280|     fpath = KWARG('fpath', HtmlBase, str, kwargs)
281|     fname = KWARG('fname', 'posts-index.html', str, kwargs)
282|     dpath = KWARG('dpath', DataPath, str, kwargs)
283|     dname = KWARG('dname', 'posts.tab', str, kwargs)
284|     Log.info('posts-index-webpage:: %s' % str(list(kwargs.keys())))
285|     Log.debug(f'{fpath=}')
286|     Log.debug(f'{fname=}')
287|     Log.debug(f'{dpath=}')
288|     Log.debug(f'{dname=}')
289|     Log.info()
290| 
291|     # Load the all-posts data...
292|     posts = Posts(fname=dname, fpath=dpath)
293| 
294|     # Generate webpage...
295|     posts.index_webpage(fname=fname, fpath=fpath)
296| 
297|     Log.info()
298|     return 'Done'
299| 
300| ##================================================================================================##
301| def do_posts_timeline_page (**kwargs):
302|     """CMND: Create an HTML timeline of all posts (oldest to newest; month sections)."""
303|     fpath = KWARG('fpath', HtmlBase, str, kwargs)
304|     fname = KWARG('fname', 'posts-timeline.html', str, kwargs)
305|     dpath = KWARG('dpath', DataPath, str, kwargs)
306|     dname = KWARG('dname', 'posts.tab', str, kwargs)
307|     Log.info('posts-timeline-webpage:: %s' % str(list(kwargs.keys())))
308|     Log.debug(f'{fpath=}')
309|     Log.debug(f'{fname=}')
310|     Log.debug(f'{dpath=}')
311|     Log.debug(f'{dname=}')
312|     Log.info()
313| 
314|     # Load the all-posts data...
315|     posts = Posts(fname=dname, fpath=dpath)
316| 
317|     # Generate webpage...
318|     posts.timeline_webpage(fname=fname, fpath=fpath)
319| 
320|     Log.info()
321|     return 'Done'
322| 
323| ##================================================================================================##
324| def do_posts_calendar_page (**kwargs):
325|     """CMND: Create an HTML year calendar with post dates marked."""
326|     fpath = KWARG('fpath', HtmlBase, str, kwargs)
327|     fname = KWARG('fname', 'posts-calendar-%04i.html', str, kwargs)
328|     dpath = KWARG('dpath', DataPath, str, kwargs)
329|     dname = KWARG('dname', 'posts.tab', str, kwargs)
330|     cyear = KWARG('year', date.today().year, int, kwargs)
331|     Log.info('posts-calendar-webpage:: %s' % str(list(kwargs.keys())))
332|     Log.debug(f'{fpath=}')
333|     Log.debug(f'{fname=}')
334|     Log.debug(f'{dpath=}')
335|     Log.debug(f'{dname=}')
336|     Log.debug(f'{cyear=}')
337|     Log.info()
338|     prev_html  = '<span style="float:left;"><a href="{lnk}" style="color:#7f7f7f;font-size:xx-small;">&#xAB;&nbsp;{txt}</a></span>'
339|     next_html  = '<span style="float:right;"><a href="{lnk}" style="color:#7f7f7f;font-size:xx-small;">{txt}&nbsp;&#xBB;</a></span>'
340|     day_html   = '<span title="{title}" style="{style};padding:1px 4px;">{dtext}</span>'
341|     post_day   = 'background-color:yellow;color:red;font-weight:bold;'
342|     day_colors = ['#cc0000', '#000000', '#0000cc', '#000000', '#006600', '#999999', '#cc9999']
343|     day_color  = lambda dt: 'color:%s;' % day_colors[dt.weekday()]
344|     css_text = """\
344| table.CalendarMonth thead th ,
344| table.CalendarMonth tfoot th {
344|     padding: 2px 3px;
344| }
344| 
344| table.CalendarMonth tbody td {
344|     padding: 2px 3px;
344| }
344| """

345| 
346|     # Load the all-posts data...
347|     posts = Posts(fname=dname, fpath=dpath)
348| 
349|     # Extract dates for the desired year...
350|     post_dates_list = {p[1] for p in posts if p[1].year == cyear}
351|     for ix,dt in enumerate(sorted(post_dates_list), start=1):
352|         Log.debug(f'{ix:3d}: {dt}')
353|     Log.debug()
354| 
355|     # Generate calendar...
356|     def cb_prev (year:int):
357|         if year in posts.years:
358|             return prev_html.format(lnk=fname % year, txt=year)
359|         return ''
360| 
361|     def cb_next (year:int):
362|         if year in posts.years:
363|             return next_html.format(lnk=fname % year, txt=year)
364|         return ''
365| 
366|     def cb_print_month (obj):
367|         return obj.dt1.strftime('%B')
368| 
369|     def cb_print_day (obj):
370|         title = obj.dt1.strftime('%A, %B %d, %Y')
371|         style = post_day if obj.dt1 in post_dates_list else day_color(obj.dt1)
372|         dtext = obj.dt1.day
373|         return day_html.format(title=title, style=style, dtext=dtext)
374| 
375|     cal_props = dict(
376|         fname = fname,
377|         fpath = fpath,
378|         h1 = 'Blogging',
379|         h2 = 'Calendar',
380|         cb_day = cb_print_day,
381|         cb_month = cb_print_month,
382|         cb_next = cb_next,
383|         cb_prev = cb_prev,
384|         csstxt = css_text,
385|     )
386|     make_web_calendar(cyear, **cal_props)
387| 
388|     Log.info()
389|     return 'Done'
390| 
391| ##================================================================================================##
392| def do_posts_per_month_chart (**kwargs):
393|     """CMND: Create Posts-per-Month chart (all blogs)."""
394|     fpath = KWARG('fpath', HtmlBase, str, kwargs)
395|     fname = KWARG('fname', 'All-Posts-Month.png', str, kwargs)
396|     dpath = KWARG('dpath', DataPath, str, kwargs)
397|     dname = KWARG('dname', 'posts.tab', str, kwargs)
398|     Log.info('chart-posts-per-month:: %s' % str(list(kwargs.keys())))
399|     Log.debug(f'{fpath=}')
400|     Log.debug(f'{fname=}')
401|     Log.debug(f'{dpath=}')
402|     Log.debug(f'{dname=}')
403|     Log.info()
404|     tagname = lambda n:Blogs.Tag[n]
405| 
406|     posts = Posts(fname=dname, fpath=dpath)
407|     year_buckets = {}
408|     month_buckets = {}
409|     for tag,dt,name,pid,url in posts:
410|         Log.trace(f'{dt} {tagname(tag)} {pid:5d} {name} {url}')
411| 
412|         # Increment year bucket...
413|         if dt.year not in year_buckets: year_buckets[dt.year] = 0
414|         year_buckets[dt.year] += 1
415| 
416|         # Increment month bucket...
417|         key = (dt.year, dt.month)
418|         if key not in month_buckets: month_buckets[key] = {1:0, 2:0, 3:0}
419|         month_buckets[key][tag] += 1
420| 
421|     Log.trace()
422| 
423|     Log.info('Years...')
424|     for yr in sorted(year_buckets):
425|         Log.info(f'{yr}: {year_buckets[yr]:5d}')
426|     Log.info()
427| 
428|     for key in sorted(month_buckets):
429|         data = month_buckets[key]
430|         items = [f'{tag}: {data[tag]}' for tag in sorted(data)]
431|         text = ', '.join(items)
432|         Log.info(f'{key[0]}-{key[1]:02d}: {text}')
433|     Log.info()
434| 
435|     xs = [date(yr,mn,1) for yr,mn in sorted(month_buckets)]
436|     ys1 = [month_buckets[key][1] for key in sorted(month_buckets)]
437|     ys2 = [month_buckets[key][2] for key in sorted(month_buckets)]
438|     ys3 = [month_buckets[key][3] for key in sorted(month_buckets)]
439|     yb1 = [0 for y in ys1]
440|     yb2 = [y1 for y1,y2 in zip(ys1,ys2)]
441|     yb3 = [y1+y2 for y1,y2,y3 in zip(ys1,ys2,ys3)]
442| 
443|     # Create a chart...
444|     fig, ax = plt.subplots()
445|     fig.set_figwidth(16.0)
446|     fig.set_figheight(4.8)
447|     fig.subplots_adjust(left=0.035, right=0.995, bottom=0.16, top=0.93)
448|     ax.set_title(f'Posts per Month (all blogs) — {len(posts)} posts total', fontsize=15, fontweight='bold')
449| 
450|     # X-axis...
451|     ax.set_xlabel('Year', fontsize=13, fontweight='bold')
452|     ax.xaxis_date()
453|     ax.set_xlim(date(2011,1,1), date(2027,1,1))
454|     ax.xaxis.set_major_locator(mldates.YearLocator())
455|     ax.xaxis.set_major_formatter(mldates.DateFormatter('%Y'))
456|     ax.xaxis.set_minor_locator(mldates.MonthLocator(interval=1))
457|     ax.xaxis.set_minor_formatter(mlticks.NullFormatter())
458|     for tick in ax.xaxis.get_major_ticks():
459|         tick.label1.set_rotation('vertical')
460|         tick.label1.set_size(10)
461|         #tick.label1.set_fontweight('bold')
462| 
463|     # Y-axis...
464|     ax.set_ylabel('Number of Posts', fontsize=13, fontweight='bold')
465|     ax.set_ylim(0, 50)
466|     ax.yaxis.set_major_locator(mlticks.MultipleLocator(10))
467|     ax.yaxis.set_minor_locator(mlticks.MultipleLocator(1))
468|     ax.yaxis.set_major_formatter(mlticks.FormatStrFormatter('%d'))
469|     # Grid...
470|     ax.grid(which='major', axis='both', color='#bfbfbf', lw=1.0,ls='-', alpha=1.0, zorder=1)
471|     ax.grid(which='minor', axis='both', color='#dfdfdf', lw=0.5,ls='-', alpha=1.0, zorder=0)
472|     #
473|     ax.bar(xs,ys1, bottom=yb1, label='Logos con Carne (WP)', color='#0074a2', width=25, alpha=1.0, zorder=11)
474|     ax.bar(xs,ys2, bottom=yb2, label='Hard-Core Coder (WP)', color='#3fbf00', width=25, alpha=1.0, zorder=12)
475|     ax.bar(xs,ys3, bottom=yb3, label='Logos con Carne (Sub)', color='#ef6013', width=25, alpha=1.0, zorder=13)
476|     ax.legend(loc='upper right')
477|     #
478|     filename = path.join(fpath, fname)
479|     fig.savefig(filename)
480|     Log.info(f'wrote: {filename}')
481|     Log.info()
482| 
483|     Log.info()
484|     return 'Done'
485| 
486| ##================================================================================================##
487| def do_posts_per_year_chart (**kwargs):
488|     """CMND: Create Posts-per-Year chart (all blogs)."""
489|     fpath = KWARG('fpath', HtmlBase, str, kwargs)
490|     fname = KWARG('fname', 'All-Posts-Year.png', str, kwargs)
491|     dpath = KWARG('dpath', DataPath, str, kwargs)
492|     dname = KWARG('dname', 'posts.tab', str, kwargs)
493|     Log.info('chart-posts-per-year:: %s' % str(list(kwargs.keys())))
494|     Log.debug(f'{fpath=}')
495|     Log.debug(f'{fname=}')
496|     Log.debug(f'{dpath=}')
497|     Log.debug(f'{dname=}')
498|     Log.info()
499|     tagname = lambda n:Blogs.Tag[n]
500| 
501|     posts = Posts(fname=dname, fpath=dpath)
502|     year_buckets = {}
503|     for tag,dt,name,pid,url in posts:
504|         Log.trace(f'{dt} {tagname(tag)} {pid:5d} {name} {url}')
505| 
506|         # Increment year bucket...
507|         if dt.year not in year_buckets: year_buckets[dt.year] = {0:0, 1:0, 2:0, 3:0}
508|         year_buckets[dt.year][0] += 1
509|         year_buckets[dt.year][tag] += 1
510| 
511|     Log.trace()
512|     Log.info('Year LCC HCC Sub Tot')
513|     Log.info('---- --- --- --- ----')
514|     for yr in sorted(year_buckets):
515|         Log.info(f'{yr}: {year_buckets[yr][1]:3d} {year_buckets[yr][2]:3d} {year_buckets[yr][3]:3d} {year_buckets[yr][0]:4d}')
516|     Log.info('---- --- --- --- ----')
517|     Log.info()
518| 
519|     xs = [date(yr,1,1) for yr in sorted(year_buckets)]
520|     ys1 = [year_buckets[key][1] for key in sorted(year_buckets)]
521|     ys2 = [year_buckets[key][2] for key in sorted(year_buckets)]
522|     ys3 = [year_buckets[key][3] for key in sorted(year_buckets)]
523|     yb1 = [0 for y in ys1]
524|     yb2 = [y1 for y1,y2 in zip(ys1,ys2)]
525|     yb3 = [y1+y2 for y1,y2,y3 in zip(ys1,ys2,ys3)]
526| 
527|     # Create a chart...
528|     fig, ax = plt.subplots()
529|     fig.set_figwidth(12.0)
530|     fig.set_figheight(4.8)
531|     fig.subplots_adjust(left=0.058, right=0.995, bottom=0.11, top=0.93)
532|     fig.suptitle(f'Posts per Year (all blogs) — {len(posts)} posts total', fontsize=15, fontweight='bold')
533| 
534|     # X-axis...
535|     ax.set_xlabel('Year', fontsize=13, fontweight='bold')
536|     ax.xaxis_date()
537|     ax.set_xlim(date(2010,7,1), date(2026,6,1))
538|     ax.xaxis.set_major_locator(mldates.YearLocator())
539|     ax.xaxis.set_minor_locator(mlticks.NullLocator())
540|     ax.xaxis.set_major_formatter(mldates.DateFormatter('%Y'))
541|     ax.xaxis.set_minor_formatter(mlticks.NullFormatter())
542|     for tick in ax.xaxis.get_major_ticks():
543|         tick.label1.set_fontsize(11)
544|         #tick.label1.set_fontweight('bold')
545|     # Y-axis...
546|     ax.set_ylabel('Number of Posts', fontsize=13, fontweight='bold')
547|     ax.set_ylim(0, 200)
548|     ax.yaxis.set_major_locator(mlticks.MultipleLocator(50))
549|     ax.yaxis.set_minor_locator(mlticks.MultipleLocator(10))
550|     ax.yaxis.set_major_formatter(mlticks.FormatStrFormatter('%d'))
551|     # Grid...
552|     ax.grid(which='major', axis='both', color='#bfbfbf', lw=1.0,ls='-', alpha=1.0, zorder=1)
553|     ax.grid(which='minor', axis='both', color='#dfdfdf', lw=0.5,ls='-', alpha=1.0, zorder=0)
554|     #
555|     ax.bar(xs,ys1, bottom=yb1, label='Logos con Carne (WP)' , color='#0074a2', width=280, alpha=1.0, zorder=11)
556|     ax.bar(xs,ys2, bottom=yb2, label='Hard-Core Coder (WP)' , color='#3fbf00', width=280, alpha=1.0, zorder=12)
557|     ax.bar(xs,ys3, bottom=yb3, label='Logos con Carne (Sub)', color='#ef6013', width=280, alpha=1.0, zorder=13)
558|     ax.legend(loc='upper left')
559|     #
560|     filename = path.join(fpath, fname)
561|     fig.savefig(filename)
562|     Log.info(f'wrote: {filename}')
563|     Log.info()
564| 
565|     Log.info()
566|     return 'Done'
567| 
568| ##================================================================================================##
569| def do_lcc_hcc_posts_lists (**kwargs):
570|     """CMND: Generate a TAB file of LCC and HCC posts."""
571|     fpath = KWARG('fpath', DataPath, str, kwargs)
572|     fname = KWARG('fname', 'lcc_hcc_posts.tab', str, kwargs)
573|     Log.info('lcc-hcc-posts-list:: %s' % str(list(kwargs.keys())))
574|     Log.debug(f'{fpath=}')
575|     Log.debug(f'{fname=}')
576|     Log.info()
577| 
578|     posts = BlogDbPosts()
579|     Log.info(posts)
580|     Log.info()
581| 
582|     fn = path.join(fpath,fname) if fpath else fname
583|     fp = open(fn, mode='w', encoding='utf8')
584|     try:
585|         # LCC
586|         for rcd in posts.lcc:
587|             dy = rcd[0].year
588|             dm = rcd[0].month
589|             dd = rcd[0].day
590|             print(f'LCC\t{dy}\t{dm}\t{dd}\t{rcd[1]}\t{rcd[2]}\t{rcd[3]}', file=fp)
591|         print(file=fp)
592| 
593|         # HCC
594|         for rcd in posts.hcc:
595|             dy = rcd[0].year
596|             dm = rcd[0].month
597|             dd = rcd[0].day
598|             print(f'HCC\t{dy}\t{dm}\t{dd}\t{rcd[1]}\t{rcd[2]}\t{rcd[3]}', file=fp)
599|         print(file=fp)
600| 
601|     except:
602|         raise
603| 
604|     finally:
605|         fp.close()
606|         Log.info(f'wrote: {fn}')
607| 
608|     Log.info()
609|     return 'Done'
610| 
611| ##================================================================================================##
612| def do_all_posts (**kwargs):
613|     """CMND: Do all posts (charts and pages)."""
614|     fpath = KWARG('fpath', HtmlBase, str, kwargs)
615|     fname = KWARG('fname', 'posts.out', str, kwargs)
616|     dpath = KWARG('dpath', DataPath, str, kwargs)
617|     dname = KWARG('dname', 'posts.tab', str, kwargs)
618|     Log.info('all-posts:: %s' % str(list(kwargs.keys())))
619|     Log.debug(f'{fpath=}')
620|     Log.debug(f'{fname=}')
621|     Log.debug(f'{dpath=}')
622|     Log.debug(f'{dname=}')
623|     Log.info()
624|     do_posts_index_page(**kwargs)
625|     do_posts_timeline_page(**kwargs)
626|     do_posts_calendar_page(**kwargs)
627|     do_posts_per_month_chart(**kwargs)
628|     do_posts_per_year_chart(**kwargs)
629|     Log.info()
630|     return 'Done'
631| 
632| ##================================================================================================##
633| def do_all_calendar_years (**kwargs):
634|     """CMND: Create HTML calendars for all years of blogging."""
635|     fpath = KWARG('fpath', HtmlBase, str, kwargs)
636|     fname = KWARG('fname', 'posts-calendar-%04i.html', str, kwargs)
637|     dpath = KWARG('dpath', DataPath, str, kwargs)
638|     dname = KWARG('dname', 'posts.tab', str, kwargs)
639|     Log.info('all-calendar-years:: %s' % str(list(kwargs.keys())))
640|     Log.debug(f'{fpath=}')
641|     Log.debug(f'{fname=}')
642|     Log.debug(f'{dpath=}')
643|     Log.debug(f'{dname=}')
644|     Log.info()
645| 
646|     # Load the all-posts data...
647|     posts = Posts(fname=dname, fpath=dpath)
648| 
649|     for year in sorted(posts.years):
650|         Log.info(f'{year} ({posts.years[year]})')
651|         kwargs['year'] = year
652|         do_posts_calendar_page(**kwargs)
653| 
654|     Log.info()
655|     return 'Done'
656| 
657| ##================================================================================================##
658| def do_test (**kwargs):
659|     """CMND: Do a test."""
660|     fpath = KWARG('fpath', BasePath, str, kwargs)
661|     fname = KWARG('fname', 'test.out', str, kwargs)
662|     dpath = KWARG('dpath', DataPath, str, kwargs)
663|     dname = KWARG('dname', 'posts.tab', str, kwargs)
664|     Log.info('test:: %s' % str(list(kwargs.keys())))
665|     Log.debug(f'{fpath=}')
666|     Log.debug(f'{fname=}')
667|     Log.debug(f'{dpath=}')
668|     Log.debug(f'{dname=}')
669|     Log.info()
670| 
671|     # Load the all-posts data...
672|     posts = Posts(fname=dname, fpath=dpath)
673|     Log.info(posts)
674|     Log.info(repr(posts))
675|     Log.info()
676| 
677|     for post in posts:
678|         Log.info(post)
679|     Log.info()
680| 
681|     Log.info()
682|     return 'Done'
683| ####################################################################################################
684| def dispatch (cmd, **kwargs):
685|     """Dispatch to a module function based on CMD."""
686|     Log.info(f'CMD: {cmd}')
687|     for kw in kwargs:
688|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
689|     Log.info()
690|     if cmd == 'all':        return do_all_posts(**kwargs)
691|     if cmd == 'p.index':    return do_posts_index_page(**kwargs)
692|     if cmd == 'p.time':     return do_posts_timeline_page(**kwargs)
693|     if cmd == 'p.cal':      return do_posts_calendar_page(**kwargs)
694|     if cmd == 'p.cal.all':  return do_all_calendar_years(**kwargs)
695|     if cmd == 'c.p/m':      return do_posts_per_month_chart(**kwargs)
696|     if cmd == 'c.p/y':      return do_posts_per_year_chart(**kwargs)
697|     if cmd == 'list':       return do_lcc_hcc_posts_lists(**kwargs)
698|     if cmd == 'test':       return do_test(**kwargs)
699|     return 'Nothing to do!'
700| ####################################################################################################
701| if __name__ == '__main__':
702|     print('autorun: %s' % argv[0])
703|     Log.start(path.join(BasePath,'posts.log'))
704|     Log.level(trace())
705|     Log.info(argv[0])
706|     Log.info()
707|     cmd = argv[1] if 1 < len(argv) else CMND
708|     kwargs = ARGS
709|     for a in argv[2:]:
710|         nv = a.split('=', 1)
711|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
712|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
713|     try:
714|         print(f'CMD: {cmd}')
715|         print()
716|         obj = dispatch(cmd, **kwargs)
717|         print()
718|         print(obj)
719|         Log.info()
720|         Log.info(obj)
721|     except:
722|         etype, evalue, tb = exc_info()
723|         ts = extract_tb(tb)
724|         Log.error()
725|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
726|         Log.error()
727|         for t in ts[-5:]:
728|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
729|             Log.error(' %s' % t[3])
730|             Log.error()
731|         raise
732|     finally:
733|         Log.end()
734| ####################################################################################################
735| '''eof'''
736|