PYTHON 36
Nomlines.py By cbettis on 9th April 2022 01:08:02 PM
  1. import argparse
  2. import configparser
  3. import logging
  4. import logging.handlers
  5. from logging import config
  6. import os
  7. import secrets
  8. import sqlite3
  9. from sqlite3 import Error
  10. import string
  11. import sys
  12.  
  13. CONFIG = r'.\config\nomlines.ini'
  14. DB = r'C:\development\data\verses.sqlite'
  15. SR = secrets.SystemRandom()
  16.  
  17. logging.config.fileConfig(CONFIG)
  18. infolog = logging.getLogger('infolog')
  19. errorlog = logging.getLogger('errorlog')
  20.  
  21. def configure():
  22.     global CONFIG, DB
  23.     config_parser = configparser.ConfigParser()
  24.     config_parser.read(CONFIG)
  25.     if config_parser['DATA']['db'] != None:
  26.         DB = config_parser['DATA']['db']
  27.  
  28. def sqlConnection():
  29.     global DB
  30.     try:
  31.         con = sqlite3.connect(DB)
  32.         return con
  33.     except Exception as err:
  34.         errorlog.exception(err)
  35.         print("EXCEPTION OCCURRED. PLEASE SEE LOGS.")
  36.  
  37. def getRandomSyllable():
  38.     vowels = ('a','e','i','o','u')
  39.     consonants = ('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z','th','ch','sh')
  40.     return secrets.choice(consonants) + secrets.choice(vowels)
  41.  
  42. def getRandomWord(numSyllables):
  43.     ret = ''
  44.     accum = 0
  45.     while accum < numSyllables:
  46.         ret += getRandomSyllable()
  47.         accum += 1
  48.     return ret
  49.  
  50. def getRandomTitle(numWords=3):
  51.     words = []
  52.     while len(words) < numWords:
  53.         numSyllables = 1 + secrets.randbelow(4)
  54.         words.append(getRandomWord(numSyllables))
  55.     return ' '.join(words).title()
  56.  
  57. def getTitleFromLine(line,maxwords=3):
  58.     words = line.Text.split()
  59.     return ' '.join(words[0:maxwords]).title()
  60.  
  61. class Source:
  62.     def __init__(self, name=None, by=None):
  63.         self.Name = name
  64.         self.By = by
  65.  
  66. class Line:
  67.     def __init__(self,id=None,text=None,source=None):
  68.         self.Id = id
  69.         self.Text = text
  70.         self.Source = source
  71.  
  72. def getSourcesSet(sourcelist):
  73.     ret = set()
  74.     for source in sourcelist:
  75.         text = source.Name + ' by ' + source.By
  76.         ret.add(text)
  77.     return ret
  78.  
  79. class Work:
  80.     def __init__(self,line=None,title=None):
  81.         self.Lines = []
  82.         self.Sources = set()
  83.         self.Title = ''
  84.         if title != None:
  85.             self.Title = title
  86.         if line != None:
  87.             self.Lines.append(line)
  88.             if line.Source != None:
  89.                 self.Sources.add(line.Source)
  90.     def setTitle(self,title):
  91.         self.Title = title
  92.     def add(self,line):
  93.         self.Lines.append(line)
  94.         if line.Source != None:
  95.             self.Sources.add(line.Source)
  96.     def generateTitle(self):
  97.         if len(self.Lines) > 0:
  98.             self.Title = getTitleFromLine(self.Lines[0])
  99.         else:
  100.             self.Title = getRandomTitle()
  101.     def toString(self):
  102.         ret = ''
  103.         if len(self.Title) > 0:
  104.             ret += self.Title + '\n\n'
  105.         for line in self.Lines:
  106.             ret += line.Text + '\n'
  107.         ret += '\n'
  108.         if len(self.Sources) > 0:
  109.             ret += 'Sources:\n'
  110.             sset = getSourcesSet(self.Sources)
  111.             for source in sset:
  112.                 ret += f'- {source}' + '\n'
  113.         return ret
  114.  
  115. def getLineCount():
  116.     lineCount = 0
  117.     try:
  118.         con = sqlConnection()
  119.         cur = con.cursor()
  120.         cur.execute(f"SELECT COUNT(*) FROM line;")
  121.         data = cur.fetchone()
  122.         if data != None:
  123.             lineCount = int(data[0])
  124.     except Exception as err:
  125.         errorlog.exception(err)
  126.         print('EXCEPTION OCCURRED. PLEASE SEE LOGS.')
  127.     finally:
  128.         cur.close()
  129.         con.close()
  130.         return lineCount
  131.  
  132. def getRandomLine(exclusionList=[]):
  133.     clause = ' '
  134.     ret = None
  135.     if len(exclusionList) != 0:
  136.         clause = " WHERE vid NOT IN ("
  137.         for r in range(0,len(exclusionList)):
  138.             clause += str(exclusionList[r])
  139.             if r != len(exclusionList) - 1:
  140.                 clause += ','
  141.         clause += ') '
  142.     sqlText = f'SELECT vid, verse, src, byline FROM line{clause}ORDER BY random() LIMIT 1;'
  143. #    print(sqlText)
  144.     try:
  145.         con = sqlConnection()
  146.         cur = con.cursor()
  147.         cur.execute(sqlText)
  148.         data = cur.fetchone()
  149.         if data != None:
  150.             vid = data[0]
  151.             vtext = data[1]
  152.             vsrc = data[2]
  153.             vby = data[3]
  154.             src = Source(name=vsrc,by=vby)
  155.             ret = Line(id=vid,text=vtext,source=src)
  156.     except Exception as err:
  157.         errorlog.exception(err)
  158.         print('EXCEPTION OCCURRED. PLEASE SEE LOGS.')
  159.     finally:
  160.         cur.close()
  161.         con.close()
  162.         return ret        
  163.  
  164. def getLinesWithReplace(howmany):
  165.     lines = []
  166.     sources = []
  167.     while len(lines) < howmany:
  168.         line = getRandomLine()
  169.         lines.append()
  170.         lines.append(getRandomLine())
  171.     return lines
  172.  
  173. def getLinesNoReplace(howmany):
  174.     lines = []
  175.     vids = []
  176.     while len(lines) < howmany:
  177.         line = getRandomLine(vids)
  178.         lines.append(line)
  179.         vids.append(line.Id)
  180.     return lines
  181.  
  182. def getLines(howmany):
  183.     limit = getLineCount()
  184.     if limit < howmany:
  185.         return getLinesWithReplace(howmany)
  186.     else:
  187.         return getLinesNoReplace(howmany)
  188.  
  189. def generateWork(howmany):
  190.     body = getLines(howmany)
  191.     work = Work(line=body[0])
  192.     for k in range(1,len(body)):
  193.         work.add(body[k])
  194.     work.generateTitle()
  195.     # work.setTitle(getRandomTitle())
  196.     return work
  197.  
  198. def main(argv):
  199.     parser = argparse.ArgumentParser()
  200.     parser.add_argument('-n', '--numberoflines', help='Number of lines (defaults to 3).', type=int, default=3)
  201.     args = parser.parse_args()
  202.     configure()
  203.     thing = generateWork(args.numberoflines)
  204.     print('   ')
  205.     print(thing.toString())
  206.     print('   ')
  207.  
  208. if __name__ == "__main__":
  209.     main(sys.argv)

Caracabe Heap is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.