---
type: "Source File"
title: "from __future__ import annotations"
description: "from __future__ import annotations import json import re import subprocess import sys from datetime import datetime, timezone from pathlib import Path BASE = Path(__file__).resolve().parents[1] PDF_PATH =."
resource: "https://thesis.copecheck.com"
tags: ["copecheck", "thesis", "source-file", "py"]
timestamp: "2026-05-11T20:44:57Z"
site: "thesis"
source_path: "copecheck-thesis/scripts/build_thesis_data.py"
---

# from __future__ import annotations

Source path: `copecheck-thesis/scripts/build_thesis_data.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-05-11T20:44:57Z`

```py
from __future__ import annotations

import json
import re
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path


BASE = Path(__file__).resolve().parents[1]
PDF_PATH = Path(sys.argv[1]) if len(sys.argv) > 1 else BASE / "assets" / "The_Discontinuity_Thesis_v1_1_2.pdf"
DATA_DIR = BASE / "data"


EXTRA_WORDS = {
    "accessibility",
    "administrative",
    "anthropic",
    "approximately",
    "artificial",
    "asymmetry",
    "automatically",
    "automated",
    "boundary",
    "categorical",
    "complementarity",
    "communications",
    "contractors",
    "cumulative",
    "customer",
    "deployment",
    "developers",
    "discontinuity",
    "distribution",
    "documentary",
    "dominance",
    "enterprise",
    "environments",
    "execution",
    "expansion",
    "frontier",
    "gatekeeping",
    "judgement",
    "labour",
    "organisation",
    "organised",
    "organisation",
    "parameters",
    "polyphasic",
    "productivity",
    "recomposition",
    "refutation",
    "responsibility",
    "systematically",
    "verification",
    "artisanal",
    "benchmarks",
    "coinbase",
    "cybersecurity",
    "desktop",
    "harmonised",
    "occurred",
    "superintelligent",
    "telecom",
    "workflows",
}


def load_words() -> set[str]:
    words = set(EXTRA_WORDS)
    dictionary = Path("/usr/share/dict/words")
    if dictionary.exists():
        try:
            words.update(word.strip().lower() for word in dictionary.read_text(errors="ignore").splitlines())
        except OSError:
            pass
    return words


WORDS = load_words()


def known_word(value: str) -> bool:
    lower = value.lower().replace("’", "'")
    if lower in WORDS:
        return True
    variants = []
    if lower.endswith("ies") and len(lower) > 4:
        variants.append(lower[:-3] + "y")
    if lower.endswith("es") and len(lower) > 3:
        variants.extend([lower[:-2], lower[:-1]])
    if lower.endswith("s") and len(lower) > 3:
        variants.append(lower[:-1])
    if lower.endswith("ed") and len(lower) > 4:
        variants.extend([lower[:-2], lower[:-1]])
    if lower.endswith("ing") and len(lower) > 5:
        variants.extend([lower[:-3], lower[:-3] + "e"])
    if lower.endswith("ers") and len(lower) > 5:
        variants.extend([lower[:-1], lower[:-3]])
    return any(candidate in WORDS for candidate in variants)


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


def extract_pdf_text(pdf_path: Path, *, layout: bool = False) -> str:
    if not pdf_path.exists():
        raise FileNotFoundError(pdf_path)
    mode = "-layout" if layout else "-raw"
    completed = subprocess.run(
        ["pdftotext", mode, str(pdf_path), "-"],
        check=True,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    return completed.stdout


def trim_front_matter(text: str) -> str:
    marker = "\fThe Discontinuity Thesis\nA Sequence of Seven Essays on Why Postwar Capitalism Ends"
    start = text.find(marker)
    if start >= 0:
        text = text[start + 1 :]
    else:
        fallback = "The Discontinuity Thesis\nA Sequence of Seven Essays on Why Postwar Capitalism Ends\nTable of Contents"
        start = text.find(fallback)
        text = text[start:] if start >= 0 else text
    toc_start = text.find("\nTable of Contents\n")
    body_start = text.find("\nHow to Read This Sequence\n")
    if toc_start >= 0 and body_start > toc_start:
        text = text[:toc_start] + text[body_start:]
    return text


HYPHEN_SPLIT = re.compile(r"\b([A-Za-z][A-Za-z']{1,})-(\s+)([A-Za-z][A-Za-z']{1,})\b")


def repair_hyphen_splits(text: str, *, collapse_unknown: bool = False) -> str:
    def replace(match: re.Match[str]) -> str:
        left = match.group(1)
        whitespace = match.group(2)
        right = match.group(3)
        joined = f"{left}{right}"
        if known_word(joined):
            return joined
        if collapse_unknown and right[:1].islower():
            return f"{left}-{right}"
        return f"{left}-{whitespace}{right}"

    return HYPHEN_SPLIT.sub(replace, text)


def stitch_hyphenated_breaks(lines: list[str]) -> list[str]:
    stitched: list[str] = []
    index = 0
    while index < len(lines):
        line = lines[index]
        if line and line.endswith("-"):
            next_index = index + 1
            while next_index < len(lines) and not lines[next_index]:
                next_index += 1
            if next_index < len(lines) and lines[next_index][:1].islower():
                stitched.append(repair_hyphen_splits(f"{line} {lines[next_index]}", collapse_unknown=True))
                index = next_index + 1
                continue
        stitched.append(line)
        index += 1
    return stitched


def clean_lines(text: str, *, include_footnotes: bool = True) -> list[str]:
    lines = []
    skipping_footnote = False
    skipped_footnote = False
    for raw_line in text.replace("\r\n", "\n").replace("\x0c", "\n").split("\n"):
        line = re.sub(r"\s+", " ", raw_line).strip()
        if not line:
            if skipping_footnote:
                skipping_footnote = False
                if skipped_footnote and lines and not re.search(r"[.!?….”\"')\]]$", lines[-1]):
                    skipped_footnote = False
                    continue
                skipped_footnote = False
            lines.append("")
            continue
        if re.fullmatch(r"\d{1,3}", line):
            if not include_footnotes:
                skipping_footnote = True
                skipped_footnote = True
            continue
        if skipping_footnote and not include_footnotes:
            skipped_footnote = True
            continue
        if re.fullmatch(r"[ivxlcdm]{1,6}", line, flags=re.I):
            continue
        if re.fullmatch(r"THE DISCONTINUITY THESIS \d+", line):
            continue
        if re.fullmatch(r"[1-7]\. [A-Z0-9 \u2019'-]+ \d+", line):
            continue
        if re.fullmatch(r"CONTENTS [ivxlcdm]{1,6}", line, flags=re.I):
            continue
        if re.fullmatch(r"APPENDIX [IVX]+: .+ \d+", line):
            continue
        lines.append(line)
    combined: list[str] = []
    index = 0
    while index < len(lines):
        line = lines[index]
        next_line = lines[index + 1] if index + 1 < len(lines) else ""
        if line == "Appendix III: Frontier Capability and" and next_line == "Deployment Evidence":
            combined.append("Appendix III: Frontier Capability and Deployment Evidence")
            index += 2
            continue
        combined.append(line)
        index += 1
    lines = stitch_hyphenated_breaks(combined)
    return lines


TOP_HEADING = re.compile(
    r"^(The Discontinuity Thesis|[1-7]\. .+|Appendix [IVX]+: .+|End of Sequence)$"
)
SECTION_HEADING = re.compile(r"^Section (one|two|three|four|five|six|seven|eight|nine): .+", re.I)


def looks_like_subheading(line: str) -> bool:
    if len(line) > 92:
        return False
    if line.startswith(("“", '"', "‘", "'")):
        return False
    if line.endswith("-"):
        return False
    if line.startswith(("http://", "https://")):
        return False
    if re.search(r"(?:[.)”\"]|percent)\d+$", line):
        return False
    if re.search(r"[%$]|https?://|\d{4}|^\d+ ", line):
        return False
    if line.endswith((".", ",", ";", ":", "?”", "?")) and not line.startswith("Section "):
        return False
    if line[:1].islower():
        return False
    blocked_prefixes = ("Model ", "OpenAI,", "Anthropic,", "Anthropic’s engineering", "Microsoft ", "Meta ", "Reuters ")
    return not line.startswith(blocked_prefixes)


def classify_block(line: str) -> str:
    if TOP_HEADING.match(line):
        return "h2"
    if SECTION_HEADING.match(line):
        return "h3"
    if looks_like_subheading(line):
        return "h3"
    return "p"


def table_key_for_header(line: str) -> str | None:
    compact = re.sub(r"\s+", " ", line.strip())
    if compact == "Model Date GDPval (wins-or-ties) GDPval-AA (Elo)":
        return "gdpval"
    if compact == "Model Date OSWorld-Verified":
        return "osworld"
    if compact == "Model Date SWE-Bench Verified SWE-Bench Pro":
        return "swe-bench"
    if compact == "Model Tau2-bench Telecom":
        return "tau2"
    if compact == "Model Terminal-Bench 2.0":
        return "terminal-bench"
    return None


def looks_like_table_row(line: str) -> bool:
    return line.startswith(
        (
            "GPT-",
            "Claude ",
            "Gemini ",
            "Grok ",
            "Mistral ",
            "Meta ",
            "OpenAI ",
            "DeepSeek ",
        )
    )


def make_slug(value: str, used: set[str]) -> str:
    slug = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")[:72] or "section"
    base = slug
    suffix = 2
    while slug in used:
        slug = f"{base}-{suffix}"
        suffix += 1
    used.add(slug)
    return slug


def build_blocks(lines: list[str]) -> list[dict[str, str]]:
    blocks: list[dict[str, str]] = []
    paragraph: list[str] = []
    used_slugs: set[str] = set()
    skipping_table_rows = False

    def flush_paragraph() -> None:
        if not paragraph:
            return
        text = repair_hyphen_splits(" ".join(paragraph).strip(), collapse_unknown=True)
        paragraph.clear()
        if text:
            blocks.append({"type": "p", "text": text})

    for index, line in enumerate(lines):
        if not line:
            skipping_table_rows = False
            flush_paragraph()
            continue
        table_key = table_key_for_header(line)
        if table_key:
            flush_paragraph()
            blocks.append({"type": "appendix_table", "key": table_key})
            skipping_table_rows = True
            continue
        if skipping_table_rows:
            if looks_like_table_row(line):
                continue
            skipping_table_rows = False
        kind = classify_block(line)
        next_line = next((candidate for candidate in lines[index + 1 :] if candidate), "")
        if kind == "h3" and next_line[:1].islower():
            kind = "p"
        if kind in {"h2", "h3"}:
            flush_paragraph()
            text = repair_hyphen_splits(line, collapse_unknown=True)
            block = {"type": kind, "text": text, "id": make_slug(text, used_slugs)}
            blocks.append(block)
            continue
        paragraph.append(line)
    flush_paragraph()
    return blocks


def split_columns(line: str) -> list[str]:
    return [part.strip() for part in re.split(r"\s{2,}", line.strip()) if part.strip()]


def parse_appendix_table(
    lines: list[str],
    key: str,
    title: str,
    columns: list[str],
    marker: str,
) -> dict[str, object] | None:
    start = next((index for index, line in enumerate(lines) if marker in re.sub(r"\s+", " ", line)), None)
    if start is None:
        return None

    rows: list[dict[str, str]] = []
    index = start + 1
    while index < len(lines):
        raw_line = lines[index].rstrip()
        line = raw_line.strip()
        index += 1
        if not line:
            if rows:
                break
            continue
        if re.fullmatch(r"(?:THE DISCONTINUITY THESIS|APPENDIX [IVX]+:.+)\s+\d+", line):
            continue
        parts = split_columns(raw_line)
        if len(parts) < 2:
            if rows:
                break
            continue
        if rows and not looks_like_table_row(parts[0]):
            break
        if len(parts) > len(columns):
            parts = parts[: len(columns) - 1] + [" ".join(parts[len(columns) - 1 :])]
        parts = parts + [""] * (len(columns) - len(parts))
        rows.append(dict(zip(columns, (repair_hyphen_splits(value, collapse_unknown=True) for value in parts), strict=False)))

    if not rows:
        return None
    return {"key": key, "title": title, "columns": columns, "rows": rows}


def extract_appendix_tables(pdf_path: Path) -> list[dict[str, object]]:
    layout_text = extract_pdf_text(pdf_path, layout=True)
    appendix_start = layout_text.rfind("Appendix III: Frontier Capability and")
    appendix_text = layout_text[appendix_start:] if appendix_start >= 0 else layout_text
    lines = appendix_text.splitlines()
    specs = [
        (
            "gdpval",
            "GDPval and GDPval-AA",
            ["Model", "Date", "GDPval (wins-or-ties)", "GDPval-AA (Elo)"],
            "Model Date GDPval (wins-or-ties) GDPval-AA (Elo)",
        ),
        (
            "osworld",
            "OSWorld-Verified",
            ["Model", "Date", "OSWorld-Verified"],
            "Model Date OSWorld-Verified",
        ),
        (
            "swe-bench",
            "SWE-Bench Verified and SWE-Bench Pro",
            ["Model", "Date", "SWE-Bench Verified", "SWE-Bench Pro"],
            "Model Date SWE-Bench Verified SWE-Bench Pro",
        ),
        (
            "tau2",
            "Tau2-bench Telecom",
            ["Model", "Tau2-bench Telecom"],
            "Model Tau2-bench Telecom",
        ),
        (
            "terminal-bench",
            "Terminal-Bench 2.0",
            ["Model", "Terminal-Bench 2.0"],
            "Model Terminal-Bench 2.0",
        ),
    ]
    tables = []
    for spec in specs:
        table = parse_appendix_table(lines, *spec)
        if table:
            tables.append(table)
    return tables


def table_of_contents(blocks: list[dict[str, str]]) -> list[dict[str, str]]:
    toc = []
    for block in blocks:
        if block["type"] in {"h2", "h3"} and "id" in block:
            toc.append({"id": block["id"], "text": block["text"], "level": block["type"]})
    return toc


def main() -> None:
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    raw_text = trim_front_matter(extract_pdf_text(PDF_PATH))
    article_lines = clean_lines(raw_text, include_footnotes=False)
    full_text = repair_hyphen_splits("\n".join(line for line in article_lines).strip(), collapse_unknown=True) + "\n"
    blocks = build_blocks(article_lines)
    appendix_tables = extract_appendix_tables(PDF_PATH)
    payload = {
        "title": "The Discontinuity Thesis",
        "subtitle": "A Sequence of Seven Essays on Why Postwar Capitalism Ends",
        "author": "Ben Luong",
        "version": "v1.1.2 final",
        "publication_date": "May 2026",
        "source_pdf": "/assets/The_Discontinuity_Thesis_v1_1_2.pdf",
        "generated_at": utc_now(),
        "word_count": len(re.findall(r"\b[\w'-]+\b", full_text)),
        "blocks": blocks,
        "toc": table_of_contents(blocks),
        "appendix_tables": appendix_tables,
        "full_text": full_text,
    }
    (DATA_DIR / "thesis.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    (DATA_DIR / "full.txt").write_text(full_text, encoding="utf-8")
    print(json.dumps({"ok": True, "blocks": len(blocks), "words": payload["word_count"]}, indent=2))


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