clrs-practice-exam/practice-exam-generator.py

69 lines
2.0 KiB
Python

import string
import cmarkgfm
import argparse
import sqlite3
import sys
import os
parser = argparse.ArgumentParser(
prog='CLRS practice exam generator',
description='Generates practice exams from your clrs.db')
parser.add_argument('--db', default="clrs.db", dest='db_path', help='Path of the database to query')
parser.add_argument('--output', dest='output_path', help='Path (including file name) of the resulting HTML document', default="exam.html")
parser.add_argument('--template', dest='template_path', help='Path (including file name) of the HTML template', default="./template.html")
parser.add_argument('query', help='SQLite query string to select the desired problems')
class ModifiedTemplate(string.Template):
delimiter = '%$%'
markdownOptions = (
cmarkgfm.cmark.Options.CMARK_OPT_UNSAFE |
cmarkgfm.cmark.Options.CMARK_OPT_GITHUB_PRE_LANG
)
def main(args):
con = sqlite3.connect(args.db_path)
con.row_factory = sqlite3.Row
cur = con.cursor()
practice_exam = ""
template_string = "%$%content"
if args.template_path is not None:
with open(args.template_path, "r") as template_file:
template_string = template_file.read()
template = ModifiedTemplate(template_string)
cur.execute(args.query)
problems = cur.fetchall()
for problem in problems:
chapter = problem["chapter"]
section = problem["section"]
problem_number = problem["problem_number"]
question = problem["question"]
answer = problem["answer"]
starred = problem["starred"]
practice_exam = practice_exam + f"""
## {chapter}.{section}-{problem_number} {"*" if starred else ""}
{question}
<details>
<summary>Solution</summary>
{cmarkgfm.markdown_to_html(answer, markdownOptions)}
</details>
"""
with open(args.output_path, "w") as output_file:
output_file.write(template.substitute(content=cmarkgfm.markdown_to_html(practice_exam, markdownOptions)))
return 0
if __name__ == '__main__':
args = parser.parse_args()
sys.exit(main(args))