a-plan-is-not-a-path / code /build_research_library.py
0721alex's picture
Make the research presentation language-neutral by default
9fe00bb verified
Raw History Blame Contribute Delete
12.1 kB
"""Build static English reading pages from the research Markdown documents."""
import html
import json
import re
import subprocess
from pathlib import Path
from urllib.parse import urlsplit
from bs4 import BeautifulSoup
from markdown_it import MarkdownIt
ROOT = Path(__file__).resolve().parent.parent
DOCS = ROOT / "outputs/cliff_realistic_dense_v1"
SITE = ROOT / "deployments/cloudflare/site"
DEST = SITE / "materials"
HF = "https://huggingface.co/datasets/0721alex/a-plan-is-not-a-path"
PACK = HF + "/resolve/main/outputs/english_research_pack.zip?download=true"
PAGES = [
("submission", "submission_en.md", "Application", "The question and the study", "Personal experience, a systematic evaluation and proposals for better LLM assistance.", "01"),
("methods", "methods_and_results_en.md", "Methods & results", "Methods and complete results", "The pinned checkpoint, full experimental settings, every cash level and reproduction commands.", "02"),
("theory", "theory_and_improvement_en.md", "Theory & improvements", "From diagnosis to better planning", "The economic mechanism and specific proposals for data, supervision and institutional support.", "03"),
("sources", "source_and_development_en.md", "Sources & development", "Sources and development history", "Published references, synthetic assumptions and every stage of the experiment's development.", "04"),
("data", "data_guide_en.md", "Data guide", "Inside the evaluation data", "A guide to the original records, reading copies, fields and reproduction workflow.", "05"),
("example", "example_task_en.md", "Example task", "The task, in full", "Read all six notices for one saved request, with the exact amounts, dates and funding conditions.", "06"),
("essay", "essay_en.md", "Full essay", "The full research essay", "The extended account, interactive-study captions and complete academic references.", "07"),
]
BY_FILE = {p[1]: p[0] for p in PAGES}
MARKDOWN = MarkdownIt("commonmark", {"html": True}).enable("table")
def clean_source(text):
return text.split("<!-- /edition -->", 1)[-1].lstrip()
def render_math(text):
expressions = []
def take(match):
expr = match.group(1) or match.group(2)
expressions.append({"tex": expr.strip(), "display": match.group(1) is not None})
return f"<div>MATHTOKEN{len(expressions)-1}</div>" if match.group(1) else f"MATHTOKEN{len(expressions)-1}"
text = re.sub(r"\$\$(.*?)\$\$|\$([^$\n]+)\$", take, text, flags=re.S)
if not expressions:
return text
js = "const fs=require('fs'), k=require('./code/vendor/katex.cjs');process.stdout.write(JSON.stringify(JSON.parse(fs.readFileSync(0,'utf8')).map(e=>k.renderToString(e.tex,{output:'mathml',displayMode:e.display,throwOnError:true}))));"
result = subprocess.run(["node", "-e", js], input=json.dumps(expressions), text=True, capture_output=True, cwd=ROOT, check=True)
for i, rendered in reversed(list(enumerate(json.loads(result.stdout)))):
text = text.replace(f"MATHTOKEN{i}", rendered)
return text
def fix_link(href):
if href.startswith(("https:", "http:", "#", "mailto:")):
return href
part = urlsplit(href)
name = Path(part.path).name
if name in BY_FILE:
return BY_FILE[name] + ".html" + ("#" + part.fragment if part.fragment else "")
if name == "report.pdf":
return "../assets/report.pdf"
if part.path.startswith("figures_en/"):
return "../assets/figures/" + Path(name).stem + ".svg"
local = (DOCS / part.path).resolve()
relative = local.relative_to(ROOT).as_posix()
kind = "tree" if local.is_dir() else "blob" if local.suffix in {".md", ".py", ".txt"} else "resolve"
return HF + "/" + kind + "/main/" + relative + ("#" + part.fragment if part.fragment else "")
def body_and_toc(text):
text = re.sub(r"^# .+\n", "", clean_source(text), count=1)
soup = BeautifulSoup(MARKDOWN.render(render_math(text)), "html.parser")
toc = []
for heading in soup.select("h2, h3"):
ident = re.sub(r"[^a-z0-9]+", "-", heading.get_text().lower()).strip("-")
heading["id"] = heading.get("id", ident)
if heading.name == "h2":
toc.append((heading["id"], heading.get_text()))
for tag in soup.select("a[href], img[src]"):
attr = "href" if tag.name == "a" else "src"
tag[attr] = fix_link(tag[attr])
for table in soup.select("table"):
wrap = soup.new_tag("div", attrs={"class": "table-scroll", "tabindex": "0", "aria-label": "Scrollable data table"})
table.wrap(wrap)
for image in soup.select("img"):
image["loading"] = "lazy"
figure = soup.new_tag("figure")
image.wrap(figure)
if image.get("alt"):
caption = soup.new_tag("figcaption")
caption.string = image["alt"]
figure.append(caption)
return str(soup), toc
def shell(title, content, active="", description="Research documents and original experimental records."):
links = "".join(f'<a href="{slug}.html" {"aria-current=page" if slug==active else ""}><span>{number}</span>{label}</a>' for slug, _, label, _, _, number in PAGES)
return f'''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="description" content="{html.escape(description, quote=True)}"><title>{html.escape(title)} · A Plan Is Not a Path</title><link rel="stylesheet" href="library.css"><script src="library.js" defer></script></head><body>
<a class="skip" href="#main">Skip to content</a><div class="reading-progress" aria-hidden="true"></div>
<header class="library-header"><a class="brand" href="index.html"><svg viewBox="0 0 28 32" aria-hidden="true"><path d="M3 28V5h10v11m5 0h7v12" fill="none" stroke="currentColor" stroke-width="1.8"/><circle cx="3" cy="28" r="2.7" fill="currentColor"/><circle cx="25" cy="28" r="2.7" fill="currentColor"/></svg>A Plan Is Not a Path<span>Research library</span></a><nav aria-label="Research links"><a href="../?lang=en">Interactive study ↗</a><a href="{HF}">Hugging Face ↗</a><a class="paper-link" href="../assets/report.pdf">Read the paper ↗</a></nav></header>
{content}
<footer class="library-footer"><a class="footer-brand" href="index.html">A Plan Is Not a Path</a><p>One study of cash flow in LLM planning.<br>All 504 outcomes remain available.</p><div><a href="{PACK}">Research pack ↓</a><a href="{HF}/tree/main">Original data & code ↗</a></div></footer>
<template id="library-menu">{links}</template></body></html>'''
def main():
DEST.mkdir(parents=True, exist_ok=True)
cards = []
for i, (slug, filename, label, title, description, number) in enumerate(PAGES):
body, toc = body_and_toc((DOCS / filename).read_text())
contents = "".join(f'<a href="#{ident}">{html.escape(text)}</a>' for ident, text in toc)
previous = PAGES[i-1] if i else None
following = PAGES[i+1] if i+1 < len(PAGES) else None
neighbours = (f'<a href="{previous[0]}.html"><small>Previous</small>← {previous[2]}</a>' if previous else '<a href="index.html"><small>Collection</small>← Research library</a>')
neighbours += f'<a href="{following[0]}.html"><small>Continue reading</small>{following[2]} →</a>' if following else '<a href="../?lang=en"><small>Explore</small>Interactive study ↗</a>'
menu = "".join(f'<a href="{p[0]}.html" {"aria-current=page" if p[0]==slug else ""}><span>{p[5]}</span>{p[2]}</a>' for p in PAGES)
content = f'''<main id="main" class="document-layout"><aside class="document-menu"><a class="all-materials" href="index.html">← All materials</a><p class="eyebrow">In this collection</p><nav aria-label="Documents">{menu}</nav><a class="download-side" href="{PACK}">Download the collection ↓</a></aside><div class="document-main"><div class="doc-heading"><p class="eyebrow">Research document / {number}</p><h1>{title}</h1><p class="standfirst">{description}</p><div class="doc-actions"><a href="{HF}/blob/main/outputs/cliff_realistic_dense_v1/{filename}">View on Hugging Face ↗</a><a href="{HF}/resolve/main/outputs/cliff_realistic_dense_v1/{filename}?download=true">Markdown ↓</a><button type="button" onclick="window.print()">Print</button></div></div><details class="mobile-toc"><summary>In this document</summary><nav>{contents}</nav></details><article class="prose">{body}</article><nav class="next-reading" aria-label="Continue reading">{neighbours}</nav></div><aside class="page-toc"><p class="eyebrow">In this document</p><nav>{contents}</nav></aside></main>'''
(DEST / (slug + ".html")).write_text(shell(title, content, slug, description))
cards.append(f'<a class="material-card" href="{slug}.html"><span class="card-number">{number}</span><span class="card-arrow">↗</span><h3>{label}</h3><p>{description}</p><span class="card-format">Read online <span>Markdown available</span></span></a>')
content = f'''<main id="main" class="collection"><section class="collection-hero"><div><p class="eyebrow">A Plan Is Not a Path / Research collection</p><h1>Research<br><em>library.</em></h1><p class="standfirst">The question, the evidence and the work behind it.<br>Research documents alongside the original experimental records.</p><div class="hero-actions"><a class="primary" href="submission.html">Start with the application <span>↗</span></a><a href="{PACK}">Download the research pack ↓</a></div></div><aside class="collection-evidence"><p class="eyebrow">The finding / Qwen3.5-4B</p><p class="evidence-question">When an LLM says its plan is feasible, can it pay every bill?</p><div class="evidence-pair"><div><strong>21<span>/24</span></strong><p>promised feasibility</p></div><div><strong>0<span>/24</span></strong><p>completed the year</p></div></div><p class="evidence-note">At RMB 50,000 in starting cash.<br>Same twenty-four responses. Full-year execution.</p><a href="methods.html#complete-results">Read the complete results ↗</a></aside></section><section class="library-documents" aria-labelledby="documents-title"><div class="section-heading"><p class="eyebrow">Reading sequence</p><h2 id="documents-title">Inside the study</h2><p>Begin with the application. Use the methods and source record to examine how the result was obtained.</p></div><div class="material-grid">{''.join(cards)}</div></section><section class="data-shelf"><div><p class="eyebrow">Original experiment</p><h2>504 responses.<br>Every response is available.</h2><p>The evaluated prompts and original model prose are Chinese. English prompt copies and outcome records make all 504 tasks and scored results accessible; the original responses remain available alongside them.</p></div><div class="data-links"><a href="{HF}/resolve/main/data/cliff_realistic_dense_v1/english_reading/requests.en.jsonl"><strong>504 prompt reading copies</strong><span>JSONL · same request IDs ↓</span></a><a href="{HF}/resolve/main/data/cliff_realistic_dense_v1/english_reading/outcomes.en.jsonl"><strong>504 outcome records</strong><span>JSONL · saved judgments and execution results ↓</span></a><a href="{HF}/tree/main/results"><strong>Original responses and scores</strong><span>Full final answers, thinking and runtime ↗</span></a><a href="{HF}/tree/main/code"><strong>Reproduction code</strong><span>Generation, execution and reference search ↗</span></a></div></section><section class="paper-shelf"><div><p class="eyebrow">The short paper</p><h2>The study in five pages.</h2><p>Methods, three figures, complete findings and development context in one report.</p><a class="primary" href="../assets/report.pdf">Open the paper <span>↗</span></a></div><a href="../assets/report.pdf"><img src="../assets/figures/figure1_absolute_cash_claim_execution.svg" alt="The paper's first figure: promises, structural validity and execution across starting cash."></a></section></main>'''
(DEST / "index.html").write_text(shell("Research library", content))
print(f"Built {len(PAGES)} English documents and the research-library index.")
if __name__ == "__main__":
main()