import jinja2 import os import subprocess from operator import itemgetter from collections import namedtuple from os.path import getmtime import json def extract_metadata(ipynb_file): Metadata = namedtuple('Metadata', ['tags', 'completion_date']) with open(ipynb_file, 'r') as f: j = json.load(f) try: tags = j['metadata']['tags'] completion_date = j['metadata']['completion_date'] except KeyError: raise Exception('Failed extracting meta from {}.'.format(ipynb_file)) return Metadata(tags, completion_date) def file_name_to_solution(name): Solution = namedtuple('Solution', ["number", "ipynb", "html", "name", "metadata"]) number = int(name.replace("EulerProblem", "").replace(".ipynb", "")) ipynb = name metadata = extract_metadata(ipynb) html = name.replace(".ipynb", ".html") name = name.replace("EulerProblem", "Problem ").replace(".ipynb", "") return Solution(number, ipynb, html, name, metadata) def get_solution_list(directory="./"): l = [file_name_to_solution(f) for f in os.listdir(directory) if f.endswith(".ipynb") and f.startswith("EulerProblem")] l.sort(key=itemgetter(0)) return l def convert_solutions_to_html(solutions): for s in solutions: if getmtime(s.html) < getmtime(s.ipynb): args = ["ipython", "nbconvert", s.ipynb] subprocess.call(args) def render_solutions(solutions): loader = jinja2.FileSystemLoader(searchpath="./") env = jinja2.Environment(loader=loader) template = env.get_template("template.html") d = {"solutions": solutions} with open("index.html", 'w') as f: f.write(template.render(**d)) def convert_solutions_to_html(solutions): for s in solutions: if not os.path.isfile(s.html) or getmtime(s.html) < getmtime(s.ipynb): args = ["ipython", "nbconvert", s.ipynb] subprocess.call(args) def ship_to_failx(): for f in os.listdir(): if f.endswith(".html"): args = ["scp", f, "failx@felixm.de:~/html/euler/"] subprocess.call(args) if __name__ == "__main__": solutions = get_solution_list() convert_solutions_to_html(solutions) render_solutions(solutions) #ship_to_failx()