---
type: "Source File"
title: "from __future__ import annotations"
description: "from __future__ import annotations import html import json import re import uuid import zipfile from datetime import datetime, timezone from pathlib import Path from typing import Any BASE =."
resource: "https://thesis.copecheck.com"
tags: ["copecheck", "thesis", "source-file", "py"]
timestamp: "2026-05-11T21:16:29Z"
site: "thesis"
source_path: "copecheck-thesis/scripts/build_epub.py"
---

# from __future__ import annotations

Source path: `copecheck-thesis/scripts/build_epub.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-05-11T21:16:29Z`

```py
from __future__ import annotations

import html
import json
import re
import uuid
import zipfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any


BASE = Path(__file__).resolve().parents[1]
DATA_PATH = BASE / "data" / "thesis.json"
ASSET_DIR = BASE / "assets"
EPUB_PATH = ASSET_DIR / "discontinuity-thesis.epub"


def clean_id(value: str, fallback: str) -> str:
    result = re.sub(r"[^A-Za-z0-9_-]+", "-", value).strip("-")
    return result or fallback


def escape(value: Any) -> str:
    return html.escape("" if value is None else str(value), quote=True)


def utc_now() -> str:
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")


def render_table(table: dict[str, Any]) -> str:
    columns = table.get("columns") if isinstance(table.get("columns"), list) else []
    rows = table.get("rows") if isinstance(table.get("rows"), list) else []
    if not columns or not rows:
        return ""
    head = "".join(f"<th>{escape(column)}</th>" for column in columns)
    body = []
    for row in rows:
        if isinstance(row, dict):
            cells = "".join(f"<td>{escape(row.get(str(column), ''))}</td>" for column in columns)
            body.append(f"<tr>{cells}</tr>")
    return f"<figure><figcaption>{escape(table.get('title'))}</figcaption><table><thead><tr>{head}</tr></thead><tbody>{''.join(body)}</tbody></table></figure>"


def chapterize(thesis: dict[str, Any]) -> list[dict[str, Any]]:
    blocks = thesis.get("blocks") if isinstance(thesis.get("blocks"), list) else []
    table_items = thesis.get("appendix_tables") if isinstance(thesis.get("appendix_tables"), list) else []
    tables = {str(table.get("key")): table for table in table_items if isinstance(table, dict)}
    chapters: list[dict[str, Any]] = []
    current: dict[str, Any] | None = None

    for index, block in enumerate(blocks):
        if not isinstance(block, dict):
            continue
        kind = str(block.get("type") or "p")
        text = str(block.get("text") or "")
        block_id = clean_id(str(block.get("id") or ""), f"block-{index}")
        if kind == "h2":
            current = {"title": text, "id": block_id, "items": []}
            chapters.append(current)
            continue
        if current is None:
            current = {"title": str(thesis.get("title") or "The Discontinuity Thesis"), "id": "start", "items": []}
            chapters.append(current)
        if kind == "h3":
            current["items"].append(f'<h2 id="{escape(block_id)}">{escape(text)}</h2>')
        elif kind == "appendix_table":
            current["items"].append(render_table(tables.get(str(block.get("key"))) or {}))
        else:
            current["items"].append(f"<p>{escape(text)}</p>")
    return chapters


def xhtml_page(title: str, body: str) -> str:
    return f"""<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <title>{escape(title)}</title>
  <link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
{body}
</body>
</html>
"""


def build_epub() -> Path:
    thesis = json.loads(DATA_PATH.read_text(encoding="utf-8"))
    title = str(thesis.get("title") or "The Discontinuity Thesis")
    subtitle = str(thesis.get("subtitle") or "")
    author = str(thesis.get("author") or "Ben Luong")
    modified = utc_now()
    identifier = f"urn:uuid:{uuid.uuid5(uuid.NAMESPACE_URL, 'https://thesis.copecheck.com/the-discontinuity-thesis')}"
    chapters = chapterize(thesis)

    css = """
body { font-family: serif; line-height: 1.55; margin: 1.2em; }
h1, h2, h3 { font-family: sans-serif; line-height: 1.15; }
h1 { font-size: 1.7em; }
h2 { font-size: 1.25em; margin-top: 1.8em; }
p { margin: 0 0 0.9em; }
table { border-collapse: collapse; font-size: 0.86em; width: 100%; }
th, td { border: 1px solid #999; padding: 0.35em; vertical-align: top; }
figcaption { font-family: sans-serif; font-weight: bold; margin: 1em 0 0.35em; }
.cover { text-align: center; }
.cover img { max-width: 100%; height: auto; }
"""

    nav_items = "\n".join(
        f'<li><a href="chapter-{index:03d}.xhtml">{escape(chapter["title"])}</a></li>'
        for index, chapter in enumerate(chapters, 1)
    )
    nav_xhtml = xhtml_page(
        "Contents",
        f"""<nav epub:type="toc" id="toc" xmlns:epub="http://www.idpf.org/2007/ops">
  <h1>Contents</h1>
  <ol>{nav_items}</ol>
</nav>""",
    )
    cover_xhtml = xhtml_page(
        "Cover",
        '<section class="cover" epub:type="cover" xmlns:epub="http://www.idpf.org/2007/ops"><img src="cover.png" alt="The Discontinuity Thesis cover" /></section>',
    )

    manifest_items = [
        '<item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav" />',
        '<item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml" />',
        '<item id="styles" href="styles.css" media-type="text/css" />',
        '<item id="cover" href="cover.xhtml" media-type="application/xhtml+xml" />',
        '<item id="cover-image" href="cover.png" media-type="image/png" properties="cover-image" />',
    ]
    spine_items = ['<itemref idref="cover" />']
    chapter_files: list[tuple[str, str]] = []
    nav_points = []
    for index, chapter in enumerate(chapters, 1):
        filename = f"chapter-{index:03d}.xhtml"
        item_id = f"chapter-{index:03d}"
        body = f"<section><h1>{escape(chapter['title'])}</h1>{''.join(chapter['items'])}</section>"
        chapter_files.append((filename, xhtml_page(str(chapter["title"]), body)))
        manifest_items.append(f'<item id="{item_id}" href="{filename}" media-type="application/xhtml+xml" />')
        spine_items.append(f'<itemref idref="{item_id}" />')
        nav_points.append(
            f'<navPoint id="navPoint-{index}" playOrder="{index}"><navLabel><text>{escape(chapter["title"])}</text></navLabel><content src="{filename}" /></navPoint>'
        )

    opf = f"""<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="bookid">
  <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:identifier id="bookid">{identifier}</dc:identifier>
    <dc:title>{escape(title)}</dc:title>
    <dc:creator>{escape(author)}</dc:creator>
    <dc:language>en</dc:language>
    <dc:description>{escape(subtitle)}</dc:description>
    <dc:publisher>CopeCheck</dc:publisher>
    <dc:date>2026-05</dc:date>
    <meta property="dcterms:modified">{modified}</meta>
    <meta name="cover" content="cover-image" />
  </metadata>
  <manifest>{''.join(manifest_items)}</manifest>
  <spine toc="ncx">{''.join(spine_items)}</spine>
</package>
"""
    ncx = f"""<?xml version="1.0" encoding="utf-8"?>
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">
  <head><meta name="dtb:uid" content="{identifier}" /></head>
  <docTitle><text>{escape(title)}</text></docTitle>
  <navMap>{''.join(nav_points)}</navMap>
</ncx>
"""
    container = """<?xml version="1.0" encoding="utf-8"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
  <rootfiles>
    <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml" />
  </rootfiles>
</container>
"""

    EPUB_PATH.parent.mkdir(parents=True, exist_ok=True)
    with zipfile.ZipFile(EPUB_PATH, "w") as archive:
        info = zipfile.ZipInfo("mimetype")
        info.compress_type = zipfile.ZIP_STORED
        archive.writestr(info, "application/epub+zip")
        archive.writestr("META-INF/container.xml", container, compress_type=zipfile.ZIP_DEFLATED)
        archive.writestr("OEBPS/content.opf", opf, compress_type=zipfile.ZIP_DEFLATED)
        archive.writestr("OEBPS/toc.ncx", ncx, compress_type=zipfile.ZIP_DEFLATED)
        archive.writestr("OEBPS/nav.xhtml", nav_xhtml, compress_type=zipfile.ZIP_DEFLATED)
        archive.writestr("OEBPS/styles.css", css, compress_type=zipfile.ZIP_DEFLATED)
        archive.writestr("OEBPS/cover.xhtml", cover_xhtml, compress_type=zipfile.ZIP_DEFLATED)
        cover_path = ASSET_DIR / "cover.png"
        if cover_path.exists():
            archive.writestr("OEBPS/cover.png", cover_path.read_bytes(), compress_type=zipfile.ZIP_DEFLATED)
        for filename, contents in chapter_files:
            archive.writestr(f"OEBPS/{filename}", contents, compress_type=zipfile.ZIP_DEFLATED)
    return EPUB_PATH


def main() -> None:
    path = build_epub()
    print(json.dumps({"ok": True, "path": str(path), "bytes": path.stat().st_size}, indent=2))


if __name__ == "__main__":
    main()
```
