iselp50
clone your own copy | download snapshot

Snapshots | iceberg

No images in this repository’s iceberg at this time

Inside this repository

combine-toc.py
text/x-python

Download raw (1.6 KB)

import glob
import json
import sys

toc = []

inpatt = sys.argv[1] if len(sys.argv) > 1 else 'toc-*.json'
outpath = sys.argv[2] if len(sys.argv) > 2 else 'toc.json'
outpath_html = outpath + '.html'

for path in glob.glob(inpatt):
  local_toc = json.load(open(path, 'r'))
  toc.extend(local_toc)

toc = sorted(toc, key=lambda e: e['page'])

print(toc)



with open(outpath, 'w') as out:
  json.dump(toc, out, ensure_ascii=False)

print('Wrote {}'.format(outpath))

######
# Templates for generated html

global_template = """
  <div id="my-toc-content" style="display:none;"></div>
  <section class="index-body">
    {toc}
  </section>
"""

index_letter_template = """
  <h3>{letter}</h3>
  <section class="index-letter-section">
    {index}
  </section>
"""

toc_row_template = """
  <section class="toc-row level{level} {label}" data-level="{level}">
    <p class="toc-row-label label-level{level}">{label}</p>
    <section class="toc-row-pagenumber pagenumber-level{level}">{pagenumber}</section>
  </section>
"""

######
# Constructing the index

toc_html = ""

for r in toc:
  toc_html += toc_row_template.format(level=r['level'], label=r['label'], pagenumber=r['page'])

body = global_template.format(toc=toc_html)

#######
# Write to an html file

with open("header.html", "r", encoding="utf-8") as input_file:
    h = input_file.read()
    # Insert id in header based on filename
    h = h.replace("{{ id }}",  "toc")

with open("footer.html", "r", encoding="utf-8") as input_file:
    f = input_file.read()

with open(outpath_html, "w", encoding="utf-8") as o:
  o.write('{header} {body} {footer}'.format(header=h, body=body, footer=f))

print('Wrote {}'.format(outpath_html))