#!/usr/bin/env python3
# Copyright 2026 Anthropic, PBC
# Copyright 2026 Learning Commons
# SPDX-License-Identifier: Apache-2.0
"""Render lesson JSON -> a styled, self-contained HTML preview (the teacher-facing view).
Visual design principles:
- Minimal color. Callouts are distinguished by an icon prefix, not background fill, so they
survive B+W printing. Student worksheets avoid color entirely.
- Horizontal rule above each H1 section; no colored section bars.
- Bullets over paragraphs wherever possible.
- Shorter student tasks may use a 2-column layout to save pages.
- Student worksheets follow: task -> instructions -> reminders -> workspace.
Block types (canonical names; legacy aliases accepted, see ALIASES in lesson_common):
paragraph, labeled, list, h2, h3, callout, table, cards, columns, group, page_break,
phase_header, fill_in, instructions, workspace, checklist
Usage:
python render_lesson_html.py lesson.json -o lesson_preview.html
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from html import escape
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from lesson_common import ( # noqa: E402
DEFAULT_THEME, Theme, CALLOUT_KINDS,
btype as _btype, resolve_callout_kind as _resolve_callout_kind,
answer_profile, expand_document, build_header, preamble_blocks, coerce_marks, item_text,
workspace_height, normalize_text, label_text, label_sep, table_row_height,
coerce_headers, coerce_rows,
)
FILL_IN_SIZES = {"short": "6em", "med": "14em", "long": "100%"}
def md(text) -> str:
t = escape(normalize_text(text), quote=True)
t = re.sub(r"\*\*(.+?)\*\*", r"\1", t)
t = re.sub(r"(?\1", t)
# Preserve line structure: text fields use \n for meaningful line breaks (sub-parts,
# multi-paragraph callouts). Collapsing them produced unreadable prose blobs.
t = re.sub(r"[ \t]*\n[ \t]*", "
", t)
return t
def answer_space(blk: dict, theme) -> str:
"""Open writing space — blank whitespace, or ruled lines for lower-grade prose."""
h = workspace_height(blk, theme)
if blk.get("ruled", theme.ruled_default):
gap = float(theme.answer_gap)
n = max(2, int(round(h / gap)))
lines = f"
" * n
return f"{lines}
"
return f""
def css(theme: Theme) -> str:
"""All styling lives in theme.css (next to this script) so the designer can edit it
directly. CSS custom properties carry the few themeable values."""
css_path = Path(__file__).resolve().parent / "theme.css"
base = css_path.read_text(encoding="utf-8") if css_path.exists() else ""
if not base:
print(f"warning: {css_path} not found — output will be unstyled", file=sys.stderr)
try:
title_size = float(theme.raw.get("title_size", DEFAULT_THEME["title_size"]))
except (TypeError, ValueError):
title_size = DEFAULT_THEME["title_size"]
try:
body_size = float(theme.raw.get("body_size", DEFAULT_THEME["body_size"]))
except (TypeError, ValueError):
body_size = DEFAULT_THEME["body_size"]
root = (":root{"
f"--primary:{theme.safe('primary')};--title-color:{theme.safe('title_color')};"
f"--text:{theme.safe('text')};--muted:{theme.safe('muted')};"
f"--rule:{theme.safe('rule')};--border:{theme.safe('border')};"
f"--title-size:{title_size}pt;--body-size:{body_size}pt"
"}")
return root + "\n" + base
def render_block(blk: dict, theme: Theme) -> str:
# Adding a block type or text field? Render it in render_lesson_docx.py in
# the same commit — the html and docx renderers must emit the same text.
t = _btype(blk)
if t == "paragraph":
return f"{md(blk.get('text', ''))}
"
if t == "labeled":
lbl = label_text(blk)
return f"{md(lbl)}{label_sep(lbl)} {md(blk.get('text', ''))}
"
if t == "h2":
# Heading levels come from document context (theme.hbase/theme.hsub, set in
# render()) so the outline never skips a level — an "h3" block directly under
# a section heading must land at h3, not a fixed h4 (axe: heading-order).
lvl = getattr(theme, "hbase", 3)
theme.hsub = True
return f"{md(blk.get('text', ''))}"
if t == "h3":
lvl = getattr(theme, "hbase", 3) + (1 if getattr(theme, "hsub", False) else 0)
return f"{md(blk.get('text', ''))}"
if t == "instructions":
return f"{md(blk.get('text', ''))}
"
if t in ("list", "checklist"):
cls = ' class="check"' if t == "checklist" else ""
tag = "ol" if blk.get("ordered") else "ul"
items = "".join(f"{md(item_text(i))}" for i in blk.get("items", []))
head = (f"{md(label_text(blk))}
"
if blk.get("label") else "")
return f"{head}<{tag}{cls}>{items}{tag}>"
if t == "callout":
# Models sometimes write "body"/"content" for the content key — tolerate rather than
# silently rendering an empty box.
text = blk.get("text") or blk.get("body") or blk.get("content") or ""
kind = _resolve_callout_kind(blk)
icon, klass = CALLOUT_KINDS[kind]
label = label_text(blk)
head = (f"{icon}"
f"{md(label)}
" if label
else f"{icon}
")
body = f"{md(text)}
" if text else ""
return f"{head}{body}
"
if t == "cards":
items = [c if isinstance(c, dict) else {"title": str(c), "text": ""}
for c in blk.get("items", [])]
cards = "".join(
""
f"
{md(c.get('title', ''))}
"
f"
{md(c.get('text', ''))}
"
for c in items)
return f"{cards}
"
if t == "fill_in":
size = FILL_IN_SIZES.get(str(blk.get("size", "med")).lower(), FILL_IN_SIZES["med"])
line = f""
if blk.get("label"):
return f"{md(label_text(blk))}: {line}
"
return f"{line}
"
if t == "phase_header":
mins = blk.get("minutes")
right = f"{md(mins)} min" if mins is not None else ""
lvl = getattr(theme, "hbase", 3)
theme.hsub = True
return (f"{md(blk.get('name', ''))}"
f"{right}")
if t == "group":
inner = "".join(render_block(b, theme) for b in blk.get("blocks", []))
return f"{inner}
"
if t == "workspace":
return answer_space(blk, theme)
if t == "labeled_box":
label = md(label_text(blk))
head = f"{label}
" if label else ""
return f"{head}{answer_space(blk, theme)}"
if t == "page_break":
return "
"
if t == "table":
headers = coerce_headers(blk.get("headers"))
head = ""
if headers:
head = ("" + "".join(f"| {md(str(h).rstrip(': '))} | " for h in headers)
+ "
")
rows = []
for r in coerce_rows(blk.get("rows")):
# An underscore run is the model writing "blank to fill in" — render it as a
# real blank cell, not literal underscores.
r = [item_text(c) for c in r]
r = ["" if str(c).strip().strip("_") == "" and "_" in str(c) else c for c in r]
full_blank = not any(str(c).strip() for c in r)
row_h = table_row_height(blk, theme, full_blank=full_blank)
cells = []
for c in r:
style = ""
if not str(c).strip(): # td height acts as a minimum; the row still grows
style = f" style=\"height:{row_h:g}pt\""
cells.append(f"{md(c)} | ")
rows.append("" + "".join(cells) + "
")
classes = [] if headers else ["headless"]
if blk.get("display") == "large":
classes.append("display-large")
klass = f" class=\"{' '.join(classes)}\"" if classes else ""
return f""
if t == "columns":
left = "".join(render_block(b, theme) for b in blk.get("left", []))
right = "".join(render_block(b, theme) for b in blk.get("right", []))
return f""
if t == "source_card":
bits = " · ".join(md(str(blk.get(k))) for k in ("author", "date", "origin")
if blk.get(k))
title = md(blk.get("title", ""))
excerpt = md(blk.get("excerpt") or blk.get("text") or "")
meta = f" — {bits}" if bits else ""
return (f"{title}{meta}
"
f"
{excerpt}
")
if t == "fill_table":
headers = coerce_headers(blk.get("headers"))
row_h = table_row_height(blk, theme, full_blank=True)
head = ("" + "".join(f"| {md(h)} | " for h in headers) + "
") if headers else ""
try:
cols = max(1, len(headers) or int(blk.get("cols") or 2))
except (TypeError, ValueError):
cols = 2
cols = min(cols, 12)
rows_val = blk.get("rows")
if isinstance(rows_val, list):
# Mixed rows: a non-empty list renders its cells (a worked example);
# an empty list [] renders a blank write-in row.
body = ""
for r in coerce_rows(rows_val[:50]):
cells = r[:cols]
cells += [""] * (cols - len(cells))
# Underscore runs are write-in blanks, not text (same rule as `table`,
# and as the docx fill_table path which forwards through _emit_table).
cells = ["" if str(c).strip().strip("_") == "" and "_" in str(c) else c
for c in cells]
tds = "".join(
f"{md(c)} | " if str(c).strip()
else f" | " for c in cells)
body += f"{tds}
"
else:
try:
n = int(blk.get("blank_rows") or rows_val or 3)
except (TypeError, ValueError):
n = 3
n = min(max(1, n), 50)
body = ("" + (f" | " * cols) + "
") * n
return f""
if t == "number_line":
lo, hi = blk.get("min", 0), blk.get("max", 10)
try:
raw_ticks = None if blk.get("ticks") is None else int(blk.get("ticks"))
except (TypeError, ValueError):
raw_ticks = None
# An explicit 0 means "blank line — students partition it themselves": the
# bar and its end labels still draw, but with no tick marks at all.
is_blank = raw_ticks == 0
ticks = 10 if raw_ticks is None else raw_ticks
ticks = min(max(1, ticks), 100)
marks = coerce_marks(blk.get("marks"))
try:
lo_f, hi_f = float(lo), float(hi)
span = hi_f - lo_f or 1.0
except (TypeError, ValueError):
lo_f, hi_f, span = 0.0, float(ticks), float(ticks)
eps = abs(span) * 0.002
marks = [(v, lab) for v, lab in marks
if abs(v - lo_f) > eps and abs(v - hi_f) > eps]
tick_html = "".join(
f""
f"{md(lo if i == 0 else hi if i == ticks else '')}"
for i in range(ticks + 1))
mark_html = "".join(
f""
+ (f"{md(lab)}" if lab else "")
for v, lab in marks)
mark_desc = "; ".join(f"{lab or v} at {v}" for v, lab in marks)
alt = f"number line from {lo} to {hi}" + (f", marked: {mark_desc}" if marks else "")
return (f""
f"
{tick_html}{mark_html}
")
# NEVER dump raw JSON into the page — a printed worksheet with {"type": ...} on it is a
# blocking print-safety failure (seen in real model output: "list" and "labeled_box").
if blk.get("text"):
return f"{md(blk.get('text'))}
"
if blk.get("items"):
return "" + "".join(f"- {md(item_text(i))}
" for i in blk.get("items", [])) + "
"
# Unknown type with no renderable content: emit nothing. (No debug comment — the type
# string is model-controlled and could contain "-->" to break out of an HTML comment.)
return ""
def render(data: dict) -> str:
data = expand_document(data, data.get("audience", "teacher"))
theme = Theme(data.get("theme"))
(theme.answer_height, theme.answer_gap,
theme.answer_row, theme.ruled_default) = answer_profile(data)
theme.student_doc = data.get("audience") == "student"
# Heading-level context for render_block: hbase is the level an "h2"-type block
# (or phase_header) renders at in the current scope — 2 in the preamble (parent
# is the h1 title), 3 inside a section (parent is the h2 section heading). hsub
# flips once such a heading has been emitted, so "h3"-type blocks nest one level
# deeper only when they actually have a mid-level parent above them.
theme.hbase, theme.hsub = 2, False
hdr = build_header(data)
out = [""]
if hdr["eyebrow"]:
out.append(f"
{md(hdr['eyebrow'])}
")
out.append(f"
{md(hdr['title'])}
")
if hdr["meta"]:
out.append(f"
{md(hdr['meta'])}
")
out.append("
")
if hdr["name_line"]:
out.append(f"{md(hdr['name_line'])}
")
for blk in preamble_blocks(data):
out.append(render_block(blk, theme))
LIGHT_TYPES = {"paragraph", "labeled", "list", "checklist", "h2", "h3", "callout",
"instructions"}
HEAVY_TYPES = {"group", "workspace", "labeled_box"}
for section in data.get("sections", []):
theme.hbase, theme.hsub = 3, False
h1 = (f"{md(str(section.get('heading', '')).rstrip(': '))}"
"
")
# The section heading + leading light blocks + the first atomic item
# (group/workspace) print as one unbreakable unit, so an instructions box never
# strands above a page break while its first problem starts the next page.
blocks = list(section.get("blocks", []))
unit = [h1]
glued = 0
while blocks and glued < 4 and _btype(blocks[0]) in LIGHT_TYPES:
unit.append(render_block(blocks.pop(0), theme))
glued += 1
if blocks and _btype(blocks[0]) in HEAVY_TYPES:
unit.append(render_block(blocks.pop(0), theme))
if len(unit) > 1:
out.append("" + "".join(unit) + "
")
else:
out.append(h1)
for blk in blocks:
out.append(render_block(blk, theme))
if data.get("footer_note"):
out.append(f"")
title = escape(str(data.get("title", "Lesson Plan")), quote=True)
return ("" + title
+ ""
+ "".join(out) + "")
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("input", help="lesson JSON file")
ap.add_argument("-o", "--output", default="lesson_preview.html")
args = ap.parse_args()
data = json.loads(Path(args.input).read_text(encoding="utf-8"))
Path(args.output).write_text(render(data), encoding="utf-8")
print(f"wrote {args.output}")
return 0
if __name__ == "__main__":
sys.exit(main())