Eureka/tools/bloom-sheet/bloom_sheet.py
Eureka a1b19054bb bloom-sheet: a large bare fill is a wash and a heavy line, not a solid
Flat solids read as stickers beside the plant. Small fills stay solid, like a
flower's centre, and dark fills stay cutouts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:53:43 +01:00

441 lines
21 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.
A visitor is drawn with the plant's own pen, not pasted in. Stroked shapes
become weighted neon lines, and a fill under a stroke becomes a faint wash, as
on a petal. A shape with only a fill is drawn the same way with a heavy line,
unless it is small: spots and eyes stay solid, like a flower's centre. Colours
snap to the sheet's palette, near-black paints the ground (a cutout), and
opacity is ignored. All of it must touch, reading as one thing; a closed
outline counts as covering its inside. Text, images and gradients are refused.
Needs python3-numpy, python3-markdown-it, LuaLaTeX with tikz and tcolorbox,
pdftoppm for PNG, the Ubuntu, IBM Plex Mono and Montserrat fonts, and for
visitors python3-svgelements and python3-shapely.
Everything from the document is escaped, and LaTeX runs with no shell escape.
"""
import argparse, colorsys, json, math, 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
SPOT = 0.35 # a bare fill wider than this, as a fraction of its drawing, is outlined
PALETTE_HUES = {"neonorange": 28, "neonsky": 205, "neonviolet": 244, "neonrose": 336}
def neon_colour(colour):
"""The sheet's colour nearest an SVG colour; near-black is the page's ground."""
h, s, v = colorsys.rgb_to_hsv(colour.red / 255, colour.green / 255, colour.blue / 255)
if v < 0.25: return "ground"
if s < 0.25: return "neonwhite"
return min(PALETTE_HUES, key=lambda c: abs((h * 360 - PALETTE_HUES[c] + 180) % 360 - 180))
def read_visitor(svg):
"""Read an SVG into marks the plant's pen can draw, in paint order, centred,
y up, and scaled so everything lies within radius 1. Exits with the reason
if the drawing can't be one. A mark is {"colour", "rings", "outlined"} for a
bare fill or {"colour", "pts", "width", "closed", "wash"} for a line."""
from shapely.geometry import LineString, Polygon
from shapely.ops import unary_union
from svgelements import SVG, Close, Line, Move, Path as SvgPath, Shape, Text
from svgelements import Image as SvgImage
def refuse(why):
sys.exit(f"bloom-sheet: visitor {svg}: {why}")
def paint(element, attr):
"""The element's fill or stroke, or None. svgelements reads url(#...) as black."""
if "url(" in str(element.values.get(attr, "")):
refuse(f"its {attr} is a gradient or pattern; use one flat colour per shape")
c = getattr(element, attr)
return c if c is not None and c.value is not None else None
raw = [] # (fill, stroke, stroke width, [(points, closed)])
for e in SVG.parse(svg, reify=True).elements():
if isinstance(e, Text): refuse("it has text; draw it as paths")
if isinstance(e, SvgImage): refuse("it has an embedded image; draw it as paths")
if not isinstance(e, Shape): continue
fill, stroke = paint(e, "fill"), paint(e, "stroke")
if stroke is not None and not e.implicit_stroke_width: stroke = None
if fill is None and stroke is None: continue
subs = []
for seg in SvgPath(e):
if isinstance(seg, Move):
subs.append([[(seg.end.x, -seg.end.y)], False])
elif isinstance(seg, Close):
subs[-1][1] = True
else:
n = 1 if isinstance(seg, Line) else 24
subs[-1][0].extend((p.x, -p.y) for p in (seg.point(k / n) for k in range(1, n + 1)))
subs = [(pts, closed or math.dist(pts[0], pts[-1]) < 1e-6) for pts, closed in subs if len(pts) > 1]
if subs: raw.append((fill, stroke, float(e.implicit_stroke_width or 0), subs))
if not raw: refuse("nothing in it has a fill or a stroke")
every = [p for *_, subs in raw for pts, _ in subs for p in pts]
xs, ys = [p[0] for p in every], [p[1] for p in every]
cx, cy = (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2
radius = max(math.dist(p, (cx, cy)) for p in every) or 1.0
unit = lambda pts: [(round((x - cx) / radius, 5), round((y - cy) / radius, 5)) for x, y in pts]
# all dark would be all cutout: a plain black icon is meant to be seen
colours = [c for f, s, *_ in raw for c in (f, s) if c is not None]
ink = (lambda c: "neonwhite") if all(neon_colour(c) == "ground" for c in colours) else neon_colour
marks, covers = [], []
touch = radius * 0.005
for fill, stroke, width, subs in raw:
if fill is not None:
area = None
for pts, _ in subs:
if len(pts) > 2:
poly = Polygon(pts).buffer(0)
area = poly if area is None else area.symmetric_difference(poly)
if area is not None: covers.append(area.buffer(touch))
if stroke is None:
rings = [unit(pts) for pts, _ in subs]
xs, ys = [p[0] for r in rings for p in r], [p[1] for r in rings for p in r]
big = math.hypot(max(xs) - min(xs), max(ys) - min(ys)) / 2 > SPOT
marks.append({"colour": ink(fill), "rings": rings, "outlined": big and ink(fill) != "ground"})
continue
for pts, closed in subs:
marks.append({"colour": ink(stroke), "pts": unit(pts), "width": round(width / radius, 5), "closed": closed,
"wash": ink(fill) if fill is not None and closed else None})
covers.append(Polygon(pts).buffer(touch) if closed and len(pts) > 3
else LineString(pts).buffer(width / 2 + touch))
whole = unary_union(covers)
if whole.geom_type != "Polygon":
refuse(f"it comes apart into {len(whole.geoms)} separate pieces; "
"join them, or pass each as its own --visitor")
return marks
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")
visitors = [read_visitor(svg) for svg in args.visitor] # refuse before the two minutes
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)
(d / "spec.json").write_text(json.dumps(
{"seed": seed, "panels": panels, "title_box": title_box, "swash": swash, "visitors": visitors}), 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 of strokes or one solid shape 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()