blog-db.html


001| '''Blog Database Applications.
001| 
001| Commands:
001|     --make      do_posts_table_create       Load Database From XML File
001|     --kill      do_posts_table_destroy      Delete Database Contents
001| 
001|     $posts      do_list_posts               List All Post Records
001|     $pages      do_list_pages               List All Page Records
001|     $all        do_posts_table_list         List All Records
001| 
001|     xpost       do_extract_post             Extract Posts
001|     xpage       do_extract_page             Extract Pages
001|     xposts      do_extract_posts            Extract Posts
001|     xpages      do_extract_pages            Extract Pages
001| 
001|     wc          do_count_words              Word Counter; All Posts
001| 
001|     ?txt        do_search                   Search Posts for a string
001|     ?sql        do_query                    Query Records using an SQL file
001| 
001|     c:pi        do_post_intervals           Histogram Chart
001|     test        do_test                     Sandbox
001| 
001| Classes:
001|     myPostsTable (dbPostsTable)
001|     WordCounter
001| 
001| Functions:
001|     db_list_records         (post_type, **kwargs)
001|     extract_posts_or_pages  (pids, fname, fpath, **props)
001| 
001| SQLite Database:
001|     Tablename:
001|         posts
001|     Columns:
001|         post_id         -- Post ID; integer
001|         post_date       -- Post Date [YYYY-MM-DD hh:dd:ss]
001|         post_type       -- Post Type [post|page|attachment|feedback|nav_menu_item|wp_global_styles]
001|         post_status     -- Post Status [publish|draft|future|inherit]
001|         post_name       -- Post Name (slug)
001|         post_title      -- Post Title
001|         category        -- Category
001|         content         -- Page content
001|         link            -- URL
001|         url             -- Wordpress Item Link
001|     Filenames:
001|         thehardcorecoder.sqlite
001|         thehardcorecoder.xml
001| 
001| Developer@Sonnack.com
001| June 2017
001| '''

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from time import time, ctime
007| from datetime import datetime
008| from logger import logger, info, debug, trace
009| from dates import UTC, CST
010| from files import linefile, csvfile, tabfile
011| from goodies import KWARG
012| from wordpress import dbPostsTable, BlogPostWebPage
013| from webpage import WebPage, htmlize
014| ####################################################################################################
015| Log = logger('BlogDB')
016| BasePath = r'C:\CJS\prj\Python\blog\hcc'
017| HtmlPath = r'C:\CJS\www\root\cjs\blog\hcc'
018| DataPath = path.join(BasePath, 'dat')
019| ImgsPath = path.join(BasePath, 'img')
020| BlogName = 'The Hard-Core Coder'
021| BlogCode = 'HCC'
022| BlogLink = 'https://thehardcorecoder.com'
023| SlugName = 'thehardcorecoder'
024| 
025| CMND = ''
026| ARGS = {
027|     #'s': 'foobar',
028|     #'pgids': '',
029|     #'fpath': BasePath,
030|     #'fname': 'foobar.html',
031|     #'dpath': BasePath,
032|     #'dname': 'page_ids.list',
033|     #'sname': 'blog-db.sql',
034|     #'spath': BasePath,
035| }
036| 
037| ##------------------------------------------------------------------------------------------------##
038| CssFiles = ['/basic.css', 'blogpost.css']
039| 
040| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
041| class myPostsTable (dbPostsTable):
042|     dbName = f'{SlugName}.sqlite'
043|     dbPath = HtmlPath
044|     xmlName = f'{SlugName}.xml'
045|     xmlPath = HtmlPath
046| 
047| ##================================================================================================##
048| def do_posts_table_create (**kwargs):
049|     """Create POSTS SQL Table. (Database should not already exist!)"""
050|     Log.info('DATABASE-CREATE')
051|     tbl = myPostsTable()
052|     tbl.create_table()
053|     Log.info()
054|     return 'Done'
055| ##================================================================================================##
056| def do_posts_table_destroy (**kwargs):
057|     """Destroy POSTS SQL Table. (Does not delete database!)"""
058|     Log.info('DATABASE-DESTROY')
059|     tbl = myPostsTable()
060|     tbl.destroy_table()
061|     Log.info()
062|     return 'Done'
063| ##================================================================================================##
064| def do_posts_table_list (**kwargs):
065|     """List POSTS SQL Table. (Assuming database exists!)"""
066|     fpath = KWARG('fpath', HtmlPath, str, kwargs)
067|     fname = KWARG('fname', 'blog-db.tab', str, kwargs)
068|     Log.info('DATABASE-LIST')
069|     Log.info('fpath="%s"' % fpath)
070|     Log.info('fname="%s"' % fname)
071|     Log.info()
072| 
073|     # Query database for records...
074|     sql = 'SELECT %s FROM "%s" ORDER BY "post_id"'
075|     tbl = myPostsTable()
076|     flds = ','.join([f for f in tbl.col_names if 'content' not in f])
077|     tbl.list_to_file(sql % (flds, tbl.name), fname=fname, fpath=fpath)
078|     return 'Done'
079| ##================================================================================================##
080| def db_list_records (post_type, **kwargs):
081|     """Query database for records of a given type. Write list to file."""
082|     fpath = KWARG('fpath', HtmlPath, str, kwargs)
083|     fname = KWARG('fname', 'blog-db.csv', str, kwargs)
084|     Log.info('LIST-RECORDS:: %s' % post_type)
085|     Log.info('fpath="%s"' % fpath)
086|     Log.info('fname="%s"' % fname)
087|     Log.info()
088|     flds = '"post_id","post_date","post_title","link"'
089| 
090|     # Query database for records...
091|     sql = '''SELECT %s FROM "%s" WHERE (post_type='%s') AND (post_status='publish') ORDER BY post_id'''
092|     tbl = myPostsTable()
093|     rs = tbl.db_query(sql % (flds, tbl.name, post_type))
094|     if not rs:
095|         Log.info('No data!')
096|         return 'No records'
097|     Log.info('Records Found: %d' % len(rs))
098|     # Write records to file...
099|     fn = path.join(fpath, fname)
100|     fo = tabfile(fn)
101|     fo.hdrs = ['Id','Date','Title','URL']
102|     fo.data = [[str(f) for f in r] for r in rs]
103|     fo.save()
104| ##================================================================================================##
105| def do_list_posts (**kwargs):
106|     """CMND: List all Post records in the database."""
107|     fpath = KWARG('fpath', HtmlPath, str, kwargs)
108|     fname = KWARG('fname', 'blog-db-posts.tab', str, kwargs)
109|     Log.info('LIST-POSTS:: %s' % str(list(kwargs)))
110|     Log.info('fpath="%s"' % fpath)
111|     Log.info('fname="%s"' % fname)
112|     Log.info()
113|     # Query database...
114|     db_list_records('post', fname=fname, fpath=fpath)
115|     Log.info()
116|     return 'Done'
117| ##================================================================================================##
118| def do_list_pages (**kwargs):
119|     """CMND: List all Page records in the database."""
120|     fpath = KWARG('fpath', HtmlPath, str, kwargs)
121|     fname = KWARG('fname', 'blog-db-pages.tab', str, kwargs)
122|     Log.info('LIST-PAGES:: %s' % str(list(kwargs)))
123|     Log.info('fpath="%s"' % fpath)
124|     Log.info('fname="%s"' % fname)
125|     Log.info()
126|     # Query database...
127|     db_list_records('page', fname=fname, fpath=fpath)
128|     Log.info()
129|     return 'Done'
130| 
131| ##================================================================================================##
132| def extract_posts_or_pages (pids, **props):
133|     '''Extract Posts/Pages from DB.'''
134|     fpath = KWARG('fpath', HtmlPath, str, props)
135|     fname = KWARG('fname', 'post_%06d.html', str, props)
136|     Log.info('EXTRACT-POSTS-OR-PAGES:: %s' % str(list(props.keys())))
137|     Log.info('fpath="%s"' % fpath)
138|     Log.info('fname="%s"' % fname)
139|     Log.info()
140|     cols = '"post_date","post_name","post_title","category","link","content"'
141|     sql = 'SELECT %s FROM "%s" WHERE ("post_id"=%d)'
142|     ttl = '%s:%s' % (props['h1'], props['h2'])
143| 
144|     # Detect partial job...
145|     make_index = True
146|     if (0 < len(pids)) and (pids[0] < 0):
147|         pids.pop(0)
148|         make_index = False
149| 
150|     if make_index:
151|         index_pg = WebPage(ttl, **props)
152|         index_pg.add('<table class="Index">')
153|         index_pg.add('<thead>')
154|         index_pg.add('<tr>')
155|         index_pg.add('<th>#</th>')
156|         index_pg.add('<th>PID</th>')
157|         index_pg.add('<th>Date</th>')
158|         index_pg.add('<th>Post</th>')
159|         index_pg.add('</tr>')
160|         index_pg.add('</thead>')
161|         index_pg.add('<tbody>')
162| 
163|     # For each PID, generate an HTML Post Page...
164|     for px,pid in enumerate(pids):
165|         tbl = myPostsTable()
166|         rcds = tbl.db_query(sql % (cols, tbl.name, pid))
167|         if not rcds:
168|             Log.info('No Record Found!')
169|             return 'No Record Found!'
170|         assert len(rcds)==1, RuntimeError('Database Error!')
171|         rcd = rcds[0]
172|         Log.info('pid %d: %s' % (pid,rcd[2]))
173|         Log.trace(rcd[-1])
174|         Log.trace()
175|         # Write the HTML file...
176|         pgname = fname % pid
177|         fn = path.join(fpath, pgname)
178|         pg = BlogPostWebPage(pid, rcd, props['h1'], props['h2_pg'])
179|         pg.save(fname=fn)
180|         Log.trace(pg.content())
181|         Log.trace()
182|         Log.info('wrote: %s' % fn)
183|         Log.info()
184|         if make_index:
185|             index_pg.add('<tr>')
186|             index_pg.add('<td class="C1">%d</td>' % (px+1))
187|             index_pg.add('<td class="C2"><a href="%s" target="BlogPage">%d</a></td>' % (rcd[4],pid))
188|             index_pg.add('<td class="C3">%s</td>' % rcd[0])
189|             index_pg.add('<td class="C4"><a href="%s" target="BlogPage">%s</a></td>' % (pgname,rcd[2]))
190|             index_pg.add('</tr>')
191| 
192|     if make_index:
193|         index_pg.add('</tbody>')
194|         index_pg.add('</table>')
195|         index_pg.add('')
196|         index_pg.save(path.join(fpath, 'index.html'), log=Log)
197| 
198| ##------------------------------------------------------------------------------------------------##
199| WebPageCSS = '''\
199| #PageBody table.Index {
199|     background-color: #eff7ff;
199|     color: #000000;
199|     font-size: 12px;
199|     border-spacing: 0;
199|     padding: 3px;
199|     border: 1px solid black;
199|     margin: 10px 20px;
199| }
199| #PageBody table.Index thead th {
199|     font-weight: normal;
199|     border: 1px solid black;
199| }
199| #PageBody table.Index tbody td {
199|     background-color: #ffffff;
199|     font-size: 12px;
199|     vertical-align: bottom;
199|     padding: 2px 5px 3px 5px;
199|     border: 1px solid black;
199| }
199| #PageBody table.Index tbody td.C1 {
199|     font-family: monospace;
199|     font-weight: bold;
199|     text-align: right;
199| }
199| #PageBody table.Index tbody td.C2 {
199|     font-family: monospace;
199|     font-weight: bold;
199|     text-align: right;
199| }
199| #PageBody table.Index tbody td.C3 {
199|     font-family: serif;
199|     font-size: 15px;
199|     font-weight: normal;
199|     text-align: center;
199| }
199| #PageBody table.Index tbody td.C4 {
199|     font-weight: bold;
199|     padding-right: 20px;
199| }
199| '''

200| 
201| ##================================================================================================##
202| def do_extract_post (**kwargs):
203|     """CMND: Use one or more PIDs to extract Post(s) into an HTML file."""
204|     fpath = KWARG('fpath', HtmlPath, str, kwargs)
205|     fname = KWARG('fname', 'post_%06d.html', str, kwargs)
206|     pgids = KWARG('pgids', '', str, kwargs)
207|     Log.info('EXTRACT-ONE-POST:: %s' % str(list(kwargs.keys())))
208|     Log.info('fpath="%s"' % fpath)
209|     Log.info('fname="%s"' % fname)
210|     Log.info('pgids=[%s]' % pgids)
211|     Log.info()
212| 
213|     pids = [int(pid) for pid in pgids.split(',')]
214|     pids.insert(0,-1) # mark as partial job
215|     Log.info('post-ids="%s"' % pids)
216|     Log.info()
217| 
218|     props = dict(
219|         fname=fname, fpath=fpath,
220|         h1=BlogName, h2='Blog Posts', h3='Index',
221|         h2_pg='Blog Post',
222|         csstxt=WebPageCSS,
223|     )
224|     extract_posts_or_pages(pids, **props)
225| 
226|     Log.info()
227|     return 'Done'
228| ##================================================================================================##
229| def do_extract_page (**kwargs):
230|     """CMND: Use one or more PIDs to extract Page(s) into an HTML file."""
231|     fpath = KWARG('fpath', HtmlPath, str, kwargs)
232|     fname = KWARG('fname', 'page_%06d.html', str, kwargs)
233|     pgids = KWARG('pgids', '', str, kwargs)
234|     Log.info('EXTRACT-ONE-PAGE:: %s' % str(list(kwargs.keys())))
235|     Log.info('fpath="%s"' % fpath)
236|     Log.info('fname="%s"' % fname)
237|     Log.info('pgids=[%s]' % pgids)
238|     Log.info()
239| 
240|     pids = [int(pid) for pid in pgids.split(',')]
241|     pids.insert(0,-1) # mark as partial job
242|     Log.info('page-ids="%s"' % pids)
243|     Log.info()
244| 
245|     props = dict(
246|         fname=fname, fpath=fpath,
247|         h1=BlogName, h2='Blog Pages', h3='Index',
248|         h2_pg='Blog Page',
249|         csstxt=WebPageCSS,
250|     )
251|     extract_posts_or_pages(pids, **props)
252| 
253|     Log.info()
254|     return 'Done'
255| ##================================================================================================##
256| def do_extract_posts (**kwargs):
257|     """CMND: For each PID, extract Post into an HTML file."""
258|     fpath = KWARG('fpath', HtmlPath, str, kwargs)
259|     fname = KWARG('fname', 'post_%06d.html', str, kwargs)
260|     dpath = KWARG('dpath', HtmlPath, str, kwargs)
261|     dname = KWARG('dname', 'post_ids.list', str, kwargs)
262|     Log.info('EXTRACT-ALL-POSTS:: %s' % str(list(kwargs.keys())))
263|     Log.info('fpath="%s"' % fpath)
264|     Log.info('fname="%s"' % fname)
265|     Log.info('dpath="%s"' % dpath)
266|     Log.info('dname="%s"' % dname)
267|     Log.info()
268|     ids_file = path.join(dpath, dname) if dpath else dname
269| 
270|     fo = linefile(ids_file)
271|     fo.load()
272|     pids = [int(ln.split()[0]) for ln in fo]
273|     Log.info('post-ids="%s"' % pids)
274|     Log.info()
275| 
276|     props = dict(
277|         fname=fname, fpath=fpath,
278|         h1=BlogName, h2='Blog Posts', h3='Index',
279|         h2_pg='Blog Post',
280|         csstxt=WebPageCSS,
281|     )
282|     extract_posts_or_pages(pids, **props)
283| 
284|     Log.info()
285|     return 'Done'
286| ##================================================================================================##
287| def do_extract_pages (**kwargs):
288|     """CMND: For each PID, extract Page into an HTML file."""
289|     fpath = KWARG('fpath', HtmlPath, str, kwargs)
290|     fname = KWARG('fname', 'page_%06d.html', str, kwargs)
291|     dpath = KWARG('dpath', HtmlPath, str, kwargs)
292|     dname = KWARG('dname', 'page_ids.list', str, kwargs)
293|     Log.info('EXTRACT-ALL-PAGES:: %s' % str(list(kwargs.keys())))
294|     Log.info('fpath="%s"' % fpath)
295|     Log.info('fname="%s"' % fname)
296|     Log.info('dpath="%s"' % dpath)
297|     Log.info('dname="%s"' % dname)
298|     Log.info()
299|     ids_file = path.join(dpath, dname) if dpath else dname
300| 
301|     fo = linefile(ids_file)
302|     fo.load()
303|     pids = [int(ln.split()[0]) for ln in fo]
304|     Log.info('page-ids="%s"' % pids)
305|     Log.info()
306| 
307|     props = dict(
308|         fname=fname, fpath=fpath,
309|         h1=BlogName, h2='Blog Pages', h3='Index',
310|         h2_pg='Blog Page',
311|         csstxt=WebPageCSS,
312|     )
313|     extract_posts_or_pages(pids, **props)
314| 
315|     Log.info()
316|     return 'Done'
317| 
318| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
319| class WordCounter:
320|     def __init__ (self):
321|         self.post_count = 0
322|         self.word_count = 0
323|         self.line_count = 0
324|         self.para_count = 0
325|         self.tags_count = 0
326|         self.words = {}
327|         self.tags = {}
328| 
329|     def __repr__ (self):
330|         return f'Posts: {self.post_count}, Words: {self.word_count}, Lines: {self.line_count}, Tags: {self.tags_count}'
331| 
332|     def __call__ (self, text):
333|         '''Submit text to be counted.'''
334|         ALPHA,WORD,TAGNAME,TAG,CAPTION,CODE = range(6)
335|         state = ALPHA
336|         cp = 0
337|         buf = ''
338|         self.post_count += 1
339| 
340|         while cp < len(text):
341|             # Get next text character...
342|             ch = text[cp].lower()
343|             cp += 1
344| 
345|             # Detect and count lines...
346|             if ch == '.':
347|                 self.line_count += 1
348| 
349|             # ...ALPHA...
350|             if state == ALPHA:
351|                 if ch.isalnum():
352|                     # Start of a word...
353|                     buf = ch
354|                     state = WORD
355|                     continue
356|                 if ch == '<':
357|                     # Start of an HTML tag...
358|                     buf = ''
359|                     state = TAGNAME
360|                     continue
361|                 # Possible start of [caption] or [lang]...
362|                 if ch == '[':
363|                     # [caption...]<image> <text>[/caption]
364|                     if text[cp:].startswith('caption'):
365|                         cp += (len('caption') - 1)
366|                         state = CAPTION
367|                         continue
368|                     if text[cp:].startswith('/caption'):
369|                         cp += (len('/caption') - 1)
370|                         state = CAPTION
371|                         continue
372|                     if text[cp:].startswith('code '):
373|                         cp += (len('code ') - 1)
374|                         state = CODE
375|                         continue
376|                     # Or not...
377|                 continue
378| 
379|             # ...WORD...
380|             if state == WORD:
381|                 if ch.isalnum() or (ch=="'"):
382|                     # Add to word...
383|                     buf += ch
384|                 else:
385|                     # End of word...
386|                     Log.trace('word: "%s"' % buf)
387|                     if not buf in self.words:
388|                         self.words[buf] = 0
389|                     self.words[buf] += 1
390|                     self.word_count += 1
391|                     cp -= 1
392|                     state = ALPHA
393|                 continue
394| 
395|             # ...TAGNAME...
396|             if state == TAGNAME:
397|                 if ch == '/':
398|                     # End tag (ignore name)...
399|                     state = TAG
400|                     continue
401|                 if ch == '!':
402|                     # special tag (ignore content)...
403|                     state = TAG
404|                     continue
405|                 if ch.isalnum():
406|                     # Add to tagname...
407|                     buf += ch
408|                 else:
409|                     # End of tagname...
410|                     Log.trace('tag: "%s"' % buf)
411|                     if not buf in self.tags:
412|                         self.tags[buf] = 0
413|                     self.tags[buf] += 1
414|                     self.tags_count += 1
415|                     if buf == 'p':
416|                         self.para_count += 1
417|                     cp -= 1
418|                     state = TAG
419|                 continue
420| 
421|             # ...TAG...
422|             if state == TAG:
423|                 if ch == '>':
424|                     state = ALPHA
425|                 continue
426| 
427|             # ...CAPTION...
428|             if state == CAPTION:
429|                 ix = text[cp:].index(']')
430|                 cp += ix
431|                 state = ALPHA
432|                 continue
433| 
434|             # ...CODE...
435|             if state == CODE:
436|                 ix = text[cp:].index('[/code]')
437|                 Log.debug(f'Skipping: {text[cp:cp+ix]}')
438|                 cp += (ix + len('[/code]'))
439|                 state = ALPHA
440|                 continue
441| 
442|         return self
443| 
444| ##------------------------------------------------------------------------------------------------##
445| CountWordsSQL = '''\
445| SELECT "post_id","post_type","post_date","post_title","content"
445| FROM "%s"
445| WHERE (("post_type"='post') OR ("post_type"='page')) AND ("post_status"='publish')
445| ORDER BY "post_id"
445| '''

446| ##================================================================================================##
447| def do_count_words (**kwargs):
448|     """CMND: Count Words."""
449|     fpath = KWARG('fpath', BasePath, str, kwargs)
450|     name1 = KWARG('name1', 'word.list', str, kwargs)
451|     name2 = KWARG('name2', 'word_sorted.list', str, kwargs)
452|     name3 = KWARG('name3', 'word-count.out', str, kwargs)
453|     limit = KWARG('limit', 0, int, kwargs)
454|     Log.info('COUNT-WORDS:: %s' % str(list(kwargs)))
455|     Log.info(f'fpath="{fpath}"')
456|     Log.info(f'name1="{name1}"')
457|     Log.info(f'name2="{name2}"')
458|     Log.info(f'name3="{name3}"')
459|     Log.info(f'limit="{limit}"')
460|     Log.info()
461|     filename1 = path.join(fpath, name1)
462|     filename2 = path.join(fpath, name2)
463|     filename3 = path.join(fpath, name3)
464| 
465|     # Query database for records...
466|     tbl = myPostsTable()
467|     rs = tbl.db_query(CountWordsSQL % tbl.name)
468|     if not rs:
469|         Log.info('No data!')
470|         return 'No records'
471|     Log.info('Records Found: %d' % len(rs))
472|     Log.info()
473| 
474|     # Count words in posts...
475|     WC = WordCounter()
476| 
477|     # For every post (or page), add to count...
478|     for rx,r in enumerate(rs):
479|         if 0 < limit <= rx:
480|             break
481|         Log.debug('[%d/%d] (%s) %s %s' % (1+rx,r[0], r[1],r[2],r[3]))
482|         print(r[3])
483|         # Count the words...
484|         WC(r[4])
485|     Log.debug()
486|     Log.info(f'Words Found: {len(WC.words)}')
487|     Log.info()
488| 
489|     # Prune...
490|     for w in list(WC.words):
491|         n = WC.words[w]
492|         # Remove numbers used less than 10 times...
493|         if w.isdigit() and (n < 10):
494|             Log.debug('DELETE: "%s" (%d)' % (w,n))
495|             del WC.words[w]
496|             continue
497|         # Remove single characters...
498|         if (len(w) == 1) and not w.isdigit():
499|             if w in ['a', 'i']:
500|                 continue
501|             Log.debug('DELETE: "%s" (%d)' % (w,n))
502|             del WC.words[w]
503|             continue
504|     Log.debug()
505|     Log.info(f'Words Remaining: {len(WC.words)}')
506|     Log.info()
507| 
508|     # Write WORDS file...
509|     fp = open(filename1, mode='w', encoding='utf-8')
510|     try:
511|         for word,count in sorted(WC.words.items(), key=lambda t:t[0]):
512|             print(f'{word}, {count}', file=fp)
513|     except:
514|         raise
515|     else:
516|         Log.info(f'wrote: {filename1}')
517|     finally:
518|         fp.close()
519|     Log.info()
520| 
521|     # Write sorted WORDS file...
522|     fp = open(filename2, mode='w', encoding='utf-8')
523|     try:
524|         for word,count in sorted(WC.words.items(), key=lambda t:t[1], reverse=True):
525|             print(f'{word}, {count}', file=fp)
526|     except:
527|         raise
528|     else:
529|         Log.info(f'wrote: {filename2}')
530|     finally:
531|         fp.close()
532|     Log.info()
533| 
534|     # Write Stats file...
535|     fp = open(filename3, mode='w', encoding='utf-8')
536|     try:
537|         print(f'Posts: {WC.post_count:,}', file=fp)
538|         print(f'Words: {WC.word_count:,}', file=fp)
539|         print(f'Lines: {WC.line_count:,}', file=fp)
540|         print(f'Paras: {WC.para_count:,}', file=fp)
541|         print(file=fp)
542|         print(f'Tags: {WC.tags_count:,}', file=fp)
543|         print(file=fp)
544|         print(f'Distinct Words: {len(WC.words):,}', file=fp)
545|         print(f'Distinct Tags: {len(WC.tags):,}', file=fp)
546|         print(file=fp)
547| 
548|         print('Tags:', file=fp)
549|         for ix,tag in enumerate(sorted(WC.tags)):
550|             print(f'{1+ix:2d} <{tag.upper()}> {WC.tags[tag]}', file=fp)
551|         print(file=fp)
552| 
553|         print('Top Words:', file=fp)
554|         for ix,t in enumerate(sorted(WC.words.items(), key=lambda t:t[1], reverse=True)):
555|             if 50 <= ix:
556|                 break
557|             print(f'{1+ix:2d}: {t[1]:9d} "{t[0]}"', file=fp)
558|         print(file=fp)
559|     except:
560|         raise
561|     else:
562|         Log.info(f'wrote: {filename3}')
563|     finally:
564|         fp.close()
565| 
566|     Log.info()
567|     return 'Done'
568| 
569| ##------------------------------------------------------------------------------------------------##
570| QueryResultCSS = '''\
570| .dbHead {
570|     margin: 0 0 12pt 0;
570| }
570| .dbFoot {
570|     margin: 12pt 0 0 0;
570| }
570| .dbFoot div {
570|     margin-left: 10px;
570| }
570| .dbFoot pre {
570|     background-color: #ffffef;
570|     color: black;
570|     font-size: 11px;
570|     padding: 5px 10px;
570|     border: 1px solid black;
570|     margin: 5px 30% 15px 10px;
570| }
570| .dbRecords {
570|     margin: 12pt 24pt 12pt 6pt;
570| }
570| .dbRecord {
570|     margin: 0 0 5pt 0;
570| }
570| '''

571| ##------------------------------------------------------------------------------------------------##
572| SearchSQL = '''\
572| SELECT "post_id","link","post_title","post_date","content"
572| FROM "%s"
572| WHERE ("post_type"='post') AND ("post_status"='publish') AND ("content" LIKE '%%%s%%')
572| ORDER BY "post_date" DESC
572| '''

573| ##================================================================================================##
574| def do_search (**kwargs):
575|     """CMND: Search Posts."""
576|     fpath = KWARG('fpath', BasePath, str, kwargs)
577|     fname = KWARG('fname', 'search.html', str, kwargs)
578|     patt  = kwargs['s'] if 's' in kwargs else 'foobar'
579|     Log.info('DO-SEARCH:: %s' % str(list(kwargs)))
580|     Log.info('fpath="%s"' % fpath)
581|     Log.info('fname="%s"' % fname)
582|     Log.info('pattern="%s"' % patt)
583|     Log.info()
584| 
585|     tbl = myPostsTable()
586|     rcds = tbl.db_query(SearchSQL % (tbl.name,patt))
587|     if not rcds:
588|         Log.info('No data!')
589|         return 'No data!'
590|     Log.info('Posts Found: %d' % len(rcds))
591| 
592|     fn = path.join(fpath, fname)
593|     fp = open(fn, mode='w', encoding='utf-8')
594|     try:
595|         print('<style type="text/css">', file=fp)
596|         print('.dbRecords {width:600px;}', file=fp)
597|         print('.dbRecord {margin:0 24pt 12pt 0;}', file=fp)
598|         print('.postId {font-family:monospace;font-size:10pt;font-weight:bold;}', file=fp)
599|         print('.postLink {font-size:12pt;font-weight:bold;}', file=fp)
600|         print('.postText {font-family:serif; font-size:9pt;}', file=fp)
601|         print('</style>', file=fp)
602|         print(file=fp)
603|         print('<div class="dbHead">', file=fp)
604|         print('<div>Search String: "%s"</div>' % patt, file=fp)
605|         print('</div> <!-- end dbHead -->', file=fp)
606|         print(file=fp)
607|         print('<div class="dbRecords">', file=fp)
608|         for rx,rcd in enumerate(rcds):
609|             pid,link,title,postdate,content = rcd
610|             print('<hr style="height:1px;margin:0;">', file=fp)
611|             print('<div class="dbRecord" id="dbRcd#%05d">' % (rx+1), file=fp)
612|             print('<div class="postId">%d</div>' % pid, file=fp)
613|             print('<div class="postLink"><a href="%s">%s</a></div>' % (link,title), file=fp)
614|             print('<div class="postText">%s</div>' % content, file=fp)
615|             print('</div>', file=fp)
616|             print(file=fp)
617|         print('</div><!-- end dbRecords -->', file=fp)
618|         print(file=fp)
619|     except:
620|         raise
621|     else:
622|         Log.info('wrote: %s' % fn)
623|     finally:
624|         fp.close()
625|     Log.info()
626|     return 'Done'
627| 
628| ##================================================================================================##
629| def do_query (**kwargs):
630|     """CMND: SQL Query."""
631|     fpath = KWARG('fpath', BasePath, str, kwargs)
632|     fname = KWARG('fname', 'query.html', str, kwargs)
633|     spath = KWARG('spath', BasePath, str, kwargs)
634|     sname = KWARG('sname', 'blog-db.sql', str, kwargs)
635|     Log.info('DO-SQL-QUERY:: %s' % str(list(kwargs)))
636|     Log.info('out-path="%s"' % fpath)
637|     Log.info('out-name="%s"' % fname)
638|     Log.info('sql-path="%s"' % spath)
639|     Log.info('sql-name="%s"' % sname)
640|     Log.info()
641| 
642|     sql_filename = path.join(spath, sname)
643|     sql_file = linefile(sql_filename)
644|     sql_file.load()
645|     sql = sql_file()
646| 
647|     tbl = myPostsTable()
648|     rcds = tbl.db_query(sql)
649|     if not rcds:
650|         Log.info('No data!')
651|         return 'No data!'
652|     Log.info('Records Found: %d' % len(rcds))
653| 
654|     page_props = dict(
655|         h1=BlogName, h2='Blog-DB Query', h3='',
656|         csstxt=QueryResultCSS,
657|     )
658|     page = WebPage('Query Results', **page_props)
659| 
660|     fn = path.join(fpath, fname)
661|     page.add('<div class="dbHead">')
662|     page.add('<p style="font-weight:bold;">Records Found: %d</p>' % len(rcds))
663|     page.add('</div> <!-- end dbHead -->')
664|     page.add()
665| 
666|     page.add('<div class="dbRecords">')
667|     for rx,rcd in enumerate(rcds):
668|         page.add('<hr style="height:1px;margin:0;">')
669|         page.add('<div class="dbRecord" id="dbRcd#%05d">' % (rx+1))
670|         for fx,fld in enumerate(rcd):
671|             # Print first field in bold...
672|             if fx == 0:
673|                 page.add('<div><strong>%s</strong></div>' % fld)
674|                 continue
675|             # Print link field...
676|             if isinstance(fld,str) and fld.startswith('http'):
677|                 page.add('<div><a target="_blank" href="%s">%s</a></div>' % (fld,fld))
678|                 continue
679|             # Print field (default)...
680|             page.add('<div>%s</div>' % fld)
681|         page.add('</div>')
682|     page.add('</div><!-- end dbRecords -->')
683|     page.add()
684| 
685|     page.add('<div class="dbFoot">')
686|     page.add('<h4>Query SQL:</h4>')
687|     page.add('<pre>%s</pre>' % htmlize(sql))
688|     page.add('</div> <!-- end dbFoot -->')
689|     page.add()
690| 
691|     page.save(fn, log=Log)
692| 
693|     Log.info()
694|     return 'Done'
695| 
696| ##================================================================================================##
697| def do_post_intervals (**kwargs):
698|     """CMND: Posting intervals histogram chart."""
699|     fpath = KWARG('fpath', BasePath, str, kwargs)
700|     fname = KWARG('fname', 'post-intervals.png', str, kwargs)
701|     Log.info('POST-INTERVALS-HISTOGRAM:: %s' % str(list(kwargs)))
702|     Log.info('fpath="%s"' % fpath)
703|     Log.info('fname="%s"' % fname)
704|     Log.info()
705|     '''Posting frequency by interval.'''
706|     from mlchart import mlchart
707|     from goodies import stddev
708| 
709|     class intervals_chart (mlchart):
710|         def __init__ (self, data, **kwargs):
711|             super().__init__(**kwargs)
712|             self.data = data
713|             self.title   = 'Interval Between Posts'
714|             self.x_title = 'Interval Bin'
715|             self.y_title = 'Number of Times'
716|             self.x_limit = (0, 192)
717|             self.y_limit = (0, 40)
718|             self.x_grids = (24, 6)
719|             self.y_grids = (10, None)
720|             self.x_tickf = '%d'
721|             self.y_tickf = '%d'
722|             self.title_kw = {'fontweight':'bold'}
723|             self.x_title_kw = {'fontsize':12}
724|             self.y_title_kw = {'fontsize':12}
725|             self.dims = (12.0, 4.0)
726|             self.margins = dict(left=0.05, right=0.98, bottom=0.13, top=0.92)
727| 
728|         def plotter (self):
729|             xs = self.data[0]
730|             ys = self.data[1]
731|             self.ax.bar(xs,ys, color='#5f9fdf', width=1.00, alpha=0.90, zorder=11)
732| 
733|     def secs_2_mins (secs):
734|         m,s = divmod(secs, 60)
735|         if m < 180:
736|             return f'{int(m)}:{int(s):02d}'
737|         h,m = divmod(m, 60)
738|         if h < 24:
739|             return f'{int(h)}:{int(m)}:{int(s):02d}'
740|         d,h = divmod(h, 24)
741|         ds = '' if d == 1 else 's'
742|         return f'{int(d)} day{ds}, {int(h)}:{int(m)}:{int(s):02d}'
743| 
744|     # Query database for records...
745|     sql = '''SELECT post_date FROM "%s" WHERE (post_type='post') AND (post_status='publish') ORDER BY post_date'''
746|     tbl = myPostsTable()
747|     rs = tbl.db_query(sql % tbl.name)
748|     if not rs:
749|         Log.info('No data!')
750|         return 'No records'
751|     Log.info('Records Found: %d' % len(rs))
752|     Log.info()
753|     data = []
754|     dt0 = None
755|     for rcd in rs:
756|         dt = datetime.fromisoformat(rcd[0])
757|         if dt0 is not None:
758|             tsecs = (dt - dt0).total_seconds()
759|             if tsecs < 26_000_000:
760|                 data.append(tsecs)
761|             Log.info(f'{dt} - {dt0} = {secs_2_mins(tsecs)}')
762|         dt0 = dt
763|     Log.info()
764|     Log.info(f'time deltas: {len(data)}')
765|     Log.info(f'max delta: {secs_2_mins(max(data))}')
766|     Log.info(f'min delta: {secs_2_mins(min(data))}')
767|     Log.info(f'avg delta: {secs_2_mins(sum(data)/len(data))}')
768|     Log.info(f'stddev: {secs_2_mins(stddev(data))}')
769|     Log.info()
770| 
771|     bins = {}
772|     for secs in data:
773|         hrs = int(secs / 3600)
774|         if hrs in bins:
775|             bins[hrs] += 1
776|         else:
777|             bins[hrs] = 1
778| 
779|     for hr in sorted(bins):
780|         Log.debug(f'{hr}: {bins[hr]}')
781|     Log.debug()
782| 
783|     xs = list(sorted(bins.keys()))
784|     ys = [bins[x] for x in xs]
785|     dat = (xs, ys)
786| 
787|     cht = intervals_chart(dat, fname=fname, fpath=fpath)
788|     cht.make()
789|     Log.info('wrote: %s (in: %s)' % (fname,fpath))
790|     Log.info()
791| 
792|     #
793|     Log.info()
794|     return 'Done'
795| 
796| ##================================================================================================##
797| def do_test (**kwargs):
798|     """CMND: Test."""
799|     fpath = KWARG('fpath', BasePath, str, kwargs)
800|     fname = KWARG('fname', 'blog-db.out', str, kwargs)
801|     dpath = KWARG('dpath', HtmlPath, str, kwargs)
802|     dname = KWARG('dname', 'blog-db.dat', str, kwargs)
803|     Log.info('TEST:: %s' % str(list(kwargs)))
804|     Log.info('fpath="%s"' % fpath)
805|     Log.info('fname="%s"' % fname)
806|     Log.info('dpath="%s"' % dpath)
807|     Log.info('dname="%s"' % dname)
808|     Log.info()
809| 
810|     # Get post data...
811|     sql = '''SELECT post_date,post_title,link FROM "%s" WHERE (post_type='post') AND (post_status='publish') ORDER BY post_date'''
812|     tbl = myPostsTable()
813|     rs = tbl.db_query(sql % tbl.name)
814|     if not rs:
815|         Log.info('No data!')
816|         return 'No records'
817|     Log.info('Records Found: %d' % len(rs))
818|     Log.info()
819| 
820|     # Write output...
821|     fn = path.join(fpath, fname) if fpath else fname
822|     fo = linefile(fn)
823|     for rcd in rs:
824|         dt = datetime.fromisoformat(rcd[0])
825|         dty = f'{dt.year:4d}'
826|         dtm = f'{dt.month:2d}'
827|         dtd = f'{dt.day:2d}'
828|         ttl = rcd[1].replace("'","\\'")
829|         fo.add(f" (Blogs.{BlogCode}, date({dty},{dtm},{dtd}), '{ttl}', '{rcd[2]}'),")
830|     fo.add()
831|     fo.save()
832| 
833|     Log.info()
834|     return 'Done'
835| ####################################################################################################
836| def dispatch (cmd, **kwargs):
837|     """Dispatch CMD to an Action function in this module."""
838|     Log.info('command: %s' % cmd)
839|     for kw in kwargs:
840|         Log.info('argument[%s]: %s' % (kw,kwargs[kw]))
841|     Log.info()
842|     if cmd == 'c:pi': return do_post_intervals(**kwargs)
843|     if cmd == '?txt': return do_search(**kwargs)
844|     if cmd == '?sql': return do_query(**kwargs)
845|     if cmd == '$posts': return do_list_posts(**kwargs)
846|     if cmd == '$pages': return do_list_pages(**kwargs)
847|     if cmd == '$all': return do_posts_table_list(**kwargs)
848|     if cmd == 'wc': return do_count_words(**kwargs)
849|     if cmd == 'xpost': return do_extract_post(**kwargs)
850|     if cmd == 'xpage': return do_extract_page(**kwargs)
851|     if cmd == 'xposts': return do_extract_posts(**kwargs)
852|     if cmd == 'xpages': return do_extract_pages(**kwargs)
853|     if cmd == '--make': return do_posts_table_create(**kwargs)
854|     if cmd == '--kill': return do_posts_table_destroy(**kwargs)
855|     if cmd == 'test': return do_test(**kwargs)
856|     return 'Nothing to do!'
857| ####################################################################################################
858| if __name__ == '__main__':
859|     print('autorun: %s' % argv[0])
860|     Log.start(path.join(BasePath,'blog-db.log'))
861|     Log.level(debug())
862|     cmd = argv[1] if 1 < len(argv) else CMND
863|     kwargs = ARGS
864|     for a in argv[2:]:
865|         nv = a.split('=', 1)
866|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
867|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
868|     try:
869|         obj = dispatch(cmd, **kwargs)
870|         print()
871|         print(obj)
872|         Log.info()
873|         Log.info(obj)
874|     except:
875|         etype, evalue, tb = exc_info()
876|         ts = extract_tb(tb)
877|         Log.error()
878|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
879|         for t in ts[-5:]:
880|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
881|             Log.error(' %s' % t[3])
882|         raise
883|     finally:
884|         Log.end()
885| ####################################################################################################
886| '''eof'''
887|