Eureka/tools/bloom-sheet/bloom_sheet.py
2026-11-05 13:54:53 +01:00

345 lines
16 KiB
Python
Executable file

#!/usr/bin/env python3
"""Turn a markdown document into a one-page neon bloom sheet.
bloom_sheet.py notes.md -o sheet.png
The first top-level heading is the page title and the paragraph right after it
the subtitle; every other heading becomes a card, sized by how much it holds.
The plant grows through whatever the cards leave, and --visitor perches your
SVGs in the garden. Output is PDF or PNG, by the extension of -o. Takes about
two minutes: the growth, then LuaLaTeX twice.
Needs python3-numpy, python3-markdown-it, LuaLaTeX with tikz and tcolorbox,
pdftoppm for PNG, rsvg-convert for visitors, and the Ubuntu, IBM Plex Mono and
Montserrat fonts.
Everything from the document is escaped, and LaTeX runs with no shell escape.
"""
import argparse, json, os, random, re, shutil, subprocess, sys, tempfile, zlib
from pathlib import Path
from markdown_it import MarkdownIt
HERE = Path(__file__).resolve().parent
W, H = 210.0, 297.0
MARGIN, GUTTER = 5.0, 7.0
TITLE_H = 21.2
COLOURS = ["neonorange", "neonsky", "neonviolet"]
# Files first, then family names: a font's packaging differs between machines.
FONTS = r"""
\IfFontExistsTF{Ubuntu-L.ttf}{%
\setmainfont{Ubuntu-L.ttf}[BoldFont=Ubuntu-B.ttf]
\newfontfamily\speakfont{Ubuntu-R.ttf}[BoldFont=Ubuntu-B.ttf]
}{%
\setmainfont{Ubuntu}[UprightFont=* Light, BoldFont=* Bold]
\newfontfamily\speakfont{Ubuntu}[BoldFont=* Bold]
}
\IfFontExistsTF{IBMPlexMono-Regular.otf}{%
\newfontfamily\numfont{IBMPlexMono-Regular.otf}
\newfontfamily\labelfont{IBMPlexMono-Medium.otf}[LetterSpace=14]
}{%
\newfontfamily\numfont{IBM Plex Mono}
\newfontfamily\labelfont{IBM Plex Mono}[UprightFont=* Medium, LetterSpace=14]
}
\IfFontExistsTF{Montserrat-Thin.ttf}{\newfontfamily\thinfont{Montserrat-Thin.ttf}}{\newfontfamily\thinfont{Montserrat}[UprightFont=* Thin]}
"""
TEX_SPECIAL = {"\\": r"\textbackslash{}", "{": r"\{", "}": r"\}", "$": r"\$", "&": r"\&", "#": r"\#",
"%": r"\%", "_": r"\_", "^": r"\textasciicircum{}", "~": r"\textasciitilde{}"}
def esc(text):
return "".join(TEX_SPECIAL.get(c, c) for c in text)
def esc_code(text):
"""Escaped, with break points: code and URLs have no spaces to wrap at."""
return re.sub(r"(/|\.)", r"\1\\allowbreak{}", esc(text))
def inline(token):
"""Render one inline token's children as LaTeX; returns (tex, plain text)."""
tex, plain, stack = [], [], []
link = None
for t in token.children or []:
if t.type == "text":
tex.append(esc(t.content)); plain.append(t.content)
elif t.type == "code_inline":
tex.append(r"\code{" + esc_code(t.content) + "}"); plain.append(t.content)
elif t.type in ("softbreak", "hardbreak"):
tex.append(" " if t.type == "softbreak" else r"\newline{}"); plain.append(" ")
elif t.type in ("strong_open", "em_open"):
tex.append(r"\strong{" if t.type == "strong_open" else r"\soft{")
elif t.type in ("strong_close", "em_close"):
tex.append("}")
elif t.type == "link_open":
link = (t.attrGet("href") or "", len(plain))
elif t.type == "link_close" and link:
href, start = link
if href and href != "".join(plain[start:]):
tex.append(r" \faint{" + esc_code(href) + "}")
link = None
elif t.type == "image":
alt = t.content or "image"
tex.append(r"\faint{[" + esc(alt) + "]}"); plain.append(alt)
return "".join(tex), "".join(plain)
class Card:
def __init__(self, head=None, level=7):
self.head, self.level, self.parts, self.chars = head, level, [], len(head or "")
def add(self, tex, chars):
self.parts.append(tex)
self.chars += chars + 30 # each block costs a line's start and some space
def tex(self):
return (r"\head{" + esc(self.head) + "}\n" if self.head else "") + "\n".join(self.parts)
def table(tokens, i):
"""A pipe table as a tabular of equal ragged columns. Returns (tex, chars, next i)."""
rows, row, is_head = [], [], False
while tokens[i].type != "table_close":
t = tokens[i]
if t.type == "tr_open": row = []
elif t.type == "th_open": is_head = True
elif t.type == "td_open": is_head = False
elif t.type == "inline":
tex, plain = inline(t)
row.append((r"\strong{" + tex + "}" if is_head else tex, plain))
elif t.type == "tr_close": rows.append(row)
i += 1
n = max(len(r) for r in rows)
col = r">{\cell}p{\dimexpr(\linewidth - %d\tabcolsep)/%d\relax}" % (2 * (n - 1), n)
body = " \\\\\n".join(" & ".join(c[0] for c in r + [("", "")] * (n - len(r))) for r in rows)
chars = sum(max(len(c[1]) for c in r) * n + 10 for r in rows)
return r"\par\begin{tabular}{@{}" + "".join([col] * n) + "@{}}\n" + body + " \\\\\n\\end{tabular}\\par", chars, i
def parse(text, card_level):
"""Returns (title, subtitle, cards)."""
tokens = MarkdownIt("commonmark").enable("table").enable("strikethrough").parse(text)
title, subtitle, cards = None, None, []
card = None
depth, ordered, quote = 0, [], 0
i = 0
while i < len(tokens):
t = tokens[i]
if t.type == "heading_open":
level = int(t.tag[1])
_, plain = inline(tokens[i + 1])
if level == 1 and title is None and not cards and card is None:
title = plain
nxt = tokens[i + 3] if i + 3 < len(tokens) else None
if nxt is not None and nxt.type == "paragraph_open":
subtitle = inline(tokens[i + 4])[1]
i += 3
elif level <= card_level:
# a heading with nothing of its own is its first child's section name
if card is not None and card.head and not card.parts and level > card.level:
plain = f"{card.head} · {plain}"
cards.pop()
card = Card(plain, level); cards.append(card)
else:
if card is None:
card = Card(); cards.append(card)
card.add(r"\sub{" + esc(plain) + "}", len(plain))
i += 3
continue
if card is None and t.type not in ("hr",):
card = Card(); cards.append(card)
if t.type == "inline" and tokens[i - 1].type == "paragraph_open":
tex, plain = inline(t)
if depth:
marker = esc(f"{ordered[-1]}.") if ordered[-1] else "•"
if tokens[i - 2].type == "list_item_open":
card.add(rf"\li{{{depth}}}{{{marker}}}{{{tex}}}", len(plain))
if ordered[-1]: ordered[-1] += 1
else:
card.add(rf"\li{{{depth}}}{{}}{{{tex}}}", len(plain))
elif quote:
card.add(rf"\quoted{{{tex}}}", len(plain))
else:
card.add(tex + r"\par", len(plain))
elif t.type == "bullet_list_open":
depth += 1; ordered.append(0)
elif t.type == "ordered_list_open":
depth += 1; ordered.append(int(t.attrGet("start") or 1))
elif t.type in ("bullet_list_close", "ordered_list_close"):
depth -= 1; ordered.pop()
elif t.type == "blockquote_open":
quote += 1
elif t.type == "blockquote_close":
quote -= 1
elif t.type in ("fence", "code_block"):
for line in t.content.rstrip("\n").split("\n"):
# a kept space is a real glue item, so indents survive in the fit box
card.add(r"\codeline{" + esc_code(line).replace(" ", r"\ ") + r"\strut}", len(line) + 30)
elif t.type == "hr" and card is not None:
card.add(r"\hairline", 10)
elif t.type == "table_open":
tex, chars, i = table(tokens, i)
card.add(tex, chars)
i += 1
return title, subtitle, [c for c in cards if c.head or c.parts]
def layout(cards, box, rng, visitors):
"""Cut box into one rectangle per card, in reading order, each about the
size its text needs at 9.5 pt. Whatever that leaves is dealt in as holes:
the flowers and visitors need somewhere to bloom, and a short document gets
more garden. Returns [(card index, x, y, w, h)]."""
weights = [(k, 900 + 8 * c.chars) for k, c in enumerate(cards)]
need = sum(w for _, w in weights)
room = box[2] * box[3] - GUTTER * (box[2] + box[3]) * len(cards) ** 0.5
spare = max(room - need * 1.15, 0.05 * need)
holes = max(visitors, 2 + int(4 * spare / room))
for _ in range(holes):
# not first: the reader's eye starts at the top left
weights.insert(rng.randint(1, len(weights)), (None, max(spare / holes, 0.03 * need)))
out = []
def cut(items, x, y, w, h):
if len(items) == 1:
if items[0][0] is not None:
out.append((items[0][0], round(x, 1), round(y, 1), round(w, 1), round(h, 1)))
return
whole = sum(v for _, v in items)
# the split nearest even, so neither side ends up a sliver
best = min(range(1, len(items)), key=lambda n: abs(sum(v for _, v in items[:n]) - whole / 2))
s = sum(v for _, v in items[:best]) / whole
if w > h * 0.85: # side by side, first on the left
a = (w - GUTTER) * s
cut(items[:best], x, y, a, h)
cut(items[best:], x + a + GUTTER, y, w - a - GUTTER, h)
else: # stacked, first on top
a = (h - GUTTER) * s
cut(items[:best], x, y + h - a, w, a)
cut(items[best:], x, y, w, h - a - GUTTER)
cut(weights, *box)
return sorted(out)
def macro(k):
name = ""
k += 1
while k:
k, r = divmod(k - 1, 26)
name = chr(65 + r) + name
return r"\content" + name
def build(args, source):
title, subtitle, cards = parse(source, args.level)
if args.title is not None: title = args.title
if args.subtitle is not None: subtitle = args.subtitle
if not cards:
sys.exit("bloom-sheet: nothing to put on the page: the document has no headings or text")
seed = args.seed if args.seed is not None else zlib.crc32(source.encode("utf8")) % 100000
rng = random.Random(seed)
top = H - MARGIN
title_tex, title_box, swash = "", None, None
if title:
# Montserrat Thin runs about 0.56 em a letter; 31 pt is the sheet's title size
size = min(31.0, 31.0 * 192 / (0.56 * 10.9 * max(len(title), 1)))
width = min(196.0, 0.56 * size * 0.3528 * len(title))
title_tex = (r"\node[anchor=south west, inner sep=0pt, text=heading] at (7,278)" "\n"
rf" {{\thinfont\fontsize{{{size:.1f}}}{{{size:.1f}}}\selectfont {esc(title)}}};" "\n")
if subtitle:
title_tex += (r"\node[anchor=north west, inner sep=0pt, text=muted, text width=196mm] at (7.4,273.2)" "\n"
rf" {{\labelfont\fontsize{{5.6}}{{6}}\selectfont {esc(subtitle.upper())}}};" "\n")
title_box = [5, H - MARGIN - TITLE_H, 200, TITLE_H]
swash = [7, 276.4, 7 + max(30.0, width), 277.2]
top = title_box[1] - GUTTER
rects = layout(cards, (MARGIN, MARGIN, W - 2 * MARGIN, top - MARGIN), rng, len(args.visitor))
panels, contents, last = [], [], None
for k, x, y, w, h in rects:
colour = rng.choice([c for c in COLOURS if c != last]); last = colour
panels.append([macro(k)[8:], x, y, w, h, colour, macro(k)])
contents.append(rf"\newcommand{{{macro(k)}}}{{%" + "\n" + cards[k].tex() + "}")
# 5 pt type is about 1.7 mm of line and 0.9 mm of letter
room = (w - 6.2) * (h - 5.6) / (1.8 * 0.95)
if cards[k].chars > room:
print(f"bloom-sheet: card '{cards[k].head or 'intro'}' will come out under 5 pt: "
"shorten it or split the sheet", file=sys.stderr)
with tempfile.TemporaryDirectory(prefix="bloom-sheet-") as tmp:
d = Path(tmp)
names = []
for n, svg in enumerate(args.visitor):
names.append(f"visitor{n}.pdf")
run(["rsvg-convert", "-f", "pdf", "-o", str(d / names[-1]), str(Path(svg).resolve())], d, args.verbose)
(d / "spec.json").write_text(json.dumps(
{"seed": seed, "panels": panels, "title_box": title_box, "swash": swash, "visitors": names}), encoding="utf8")
page = (HERE / "page.tex").read_text(encoding="utf8")
for mark, value in (("@@FONTS@@", FONTS), ("@@CONTENTS@@", "\n".join(contents)), ("@@TITLE@@", title_tex)):
page = page.replace(mark, value)
(d / "sheet.tex").write_text(page, encoding="utf8")
grown = run([sys.executable, str(HERE / "grow.py"), "spec.json", "layer.tex"], d, args.verbose)
for line in grown.splitlines():
if line.startswith("left out: visitor"):
print(f"bloom-sheet: {line}", file=sys.stderr)
env = dict(os.environ)
# the font database takes a minute to build: keep it between sheets
cache = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "bloom-sheet"
try:
cache.mkdir(parents=True, exist_ok=True)
except OSError: # a sandbox with no home: slower, not broken
cache = d / "cache"
env.setdefault("TEXMFVAR", str(cache))
latex = ["lualatex", "--no-shell-escape", "--interaction=nonstopmode", "--halt-on-error", "sheet.tex"]
for _ in range(2): # remember picture lands right only on the second pass
run(latex, d, args.verbose, env, log="sheet.log")
out = Path(args.output)
out.parent.mkdir(parents=True, exist_ok=True)
if out.suffix.lower() == ".png":
run(["pdftoppm", "-r", str(args.dpi), "-png", "-singlefile", "sheet.pdf", "sheet"], d, args.verbose)
shutil.copyfile(d / "sheet.png", out)
else:
shutil.copyfile(d / "sheet.pdf", out)
print(f"{out} ({len(cards)} cards, seed {seed})")
def run(cmd, cwd, verbose, env=None, log=None):
try:
p = subprocess.run(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, errors="replace", timeout=600)
except FileNotFoundError:
sys.exit(f"bloom-sheet: {cmd[0]} is not installed")
except subprocess.TimeoutExpired:
sys.exit(f"bloom-sheet: {cmd[0]} ran past 10 minutes")
if verbose: print(p.stdout)
if p.returncode:
tail = p.stdout
if log and (Path(cwd) / log).exists():
text = (Path(cwd) / log).read_text(encoding="utf8", errors="replace")
errors = [i for i, line in enumerate(text.splitlines()) if line.startswith("!")]
tail = "\n".join(text.splitlines()[errors[0]:errors[0] + 12]) if errors else text[-1500:]
sys.exit(f"bloom-sheet: {cmd[0]} failed:\n{tail[-1500:]}")
return p.stdout
def main():
ap = argparse.ArgumentParser(prog="bloom-sheet", description="Turn a markdown document into a one-page neon bloom sheet.")
ap.add_argument("input", help="markdown file, or - for stdin")
ap.add_argument("-o", "--output", help="output .pdf or .png (default: the input's name, .pdf)")
ap.add_argument("--title", help="page title, instead of the document's first top-level heading; empty for none")
ap.add_argument("--subtitle", help="small line under the title")
ap.add_argument("--level", type=int, default=6, help="headings deeper than this are labels inside a card, not cards (default: every heading is a card)")
ap.add_argument("--visitor", action="append", default=[], metavar="SVG", help="an SVG to perch in the garden; repeat for more (about three suit a page)")
ap.add_argument("--seed", type=int, help="plant seed (default: from the document, so a sheet rebuilds the same)")
ap.add_argument("--dpi", type=int, default=200, help="PNG resolution (default 200)")
ap.add_argument("-v", "--verbose", action="store_true")
args = ap.parse_args()
source = sys.stdin.read() if args.input == "-" else Path(args.input).read_text(encoding="utf8")
if not args.output:
args.output = "sheet.pdf" if args.input == "-" else str(Path(args.input).with_suffix(".pdf"))
if Path(args.output).suffix.lower() not in (".pdf", ".png"):
sys.exit("bloom-sheet: -o must end in .pdf or .png")
build(args, source)
if __name__ == "__main__":
main()