#!/usr/bin/env python3"""Cut `paper-{dye}` — the SURFACE of every sheet in the paper kit — out of thesix photographed card masters. python3 scripts/gen-cards/export_paper.py [<out-dir from make_cards.py>]`export_cards.py` writes `card-*`: the six papers as the todo board drew thembefore the kit, cut at ALPHA > 24 so the soft shadow under the card is KEPT —it is what made the card lie on the plaster. That is exactly what a stretchablesheet cannot have: a shadow baked into the picture grows with the picture, and asheet that is drawn at four sizes would wear four different shadows. So thisexporter cuts the same masters again at ALPHA > 200 — the caps' threshold(`scripts/gen-caps/export_caps.py::trimmed`), the paper and nothing but thepaper — and the lift becomes SwiftUI's, one shadow pair for every size(`Paper/Paper.swift`, `PaperLift`).WHERE THE SOURCE COMES FROM. The generator's own out-dir (`make_cards.py--out-dir`, default `scripts/gen-cards/out`) is not committed and is not on thismachine, and no larger master exists anywhere on disk — so the source is theCOMMITTED imageset PNGs, `Media.xcassets/card-*.imageset/card-*.png`, 720x453 at2x. Pass an out-dir and the generator's own `card-*.png` files are used instead,which is the path to take the day the masters are regenerated at a higherresolution. Either way the cut is the MASTER's (cream's) box, so the eightpapers share one geometry and a sheet changes colour without moving a pixel.WHAT IT DOES, in order: 1. cuts every card with cream's ALPHA > 200 box — the card, without its shadow; 2. fills the little that is left translucent (the master's own rounded corners, ~18 px of arc) by growing the opaque paper into it, so the picture is a full opaque rectangle. The OUTLINE is drawn by `PaperShape` and clips this, so a photographed corner would only fight it; 3. writes it at 720x453 — the `card-*` geometry exactly, so one test holds both sets and a sheet's own aspect IS `PaperMetrics.cardAspect`, which is what makes a card drawn at that aspect a UNIFORM scale of the photograph rather than a nine-slice that has to compensate; 4. TONES every sheet toward the pictures (`toned`): the photographed masters are an aged tan with heavy stains, and the owner's pictures (`02-generated/14-email-open`, `15-money-accounts`, `09-calendar-day`) are pale clean cream and pale blue with a faint grain. Each channel is moved so the sheet's CENTRE mean lands on the dye's `TARGET` (read off those pictures' bare paper), and every pixel's distance from that mean is kept at `CONTRAST` of the photograph's — the fibre, the rim's wear and the deckle stay, at a lighter density. A levels move, never a repaint; 5. and writes `paper-newsprint`, which was never photographed: cream, carried to the cool off-white measured off the owner's news reference. Synthesised, and said so here, because `PaperDye` is total over eight cases and a sheet with no surface would be the one dye that is still a drawing.The means the exporter prints are `PaperDye.measured` — copy them there when atarget moves, so the paint a sheet is filled with agrees with its photograph.Opaque RGB, not RGBA: `PaperShape` is the outline and nothing reads an alphachannel. PNG, not JPEG: the sheet is magnified at page size and JPEG ringingalong a fibre reads as a halo.Needs Pillow (`python3 -m pip install pillow`)."""import jsonimport pathlibimport sysfrom PIL importImage, ImageStatROOT = pathlib.Path(__file__).resolve().parents[2]CATALOGUE = ROOT / "apps/loom/Sources/CottonPaper/Media.xcassets"# catalogue name → the `card-*` master it is cut from. Cream is the master of# masters: every other paper is cut with ITS box.DYES = ["cream", "buff", "blue", "sage", "pink", "straw", "peach"]MASTER = "cream"# A paper cut from ANOTHER dye's master: buff is the cream card, toned darker.CUT_FROM = {"buff": "cream"}# The generator's own file names, for the `--out-dir` path.GENERATED = {"cream": "card-a.png","blue": "card-blue.png","sage": "card-sage.png","pink": "card-pink.png","straw": "card-straw.png","peach": "card-peach.png",}# The paper and not its shadow. The caps' threshold, for the caps' reason.ALPHA = 200# The `card-*` geometry, kept exactly: 1.5894, which is `PaperMetrics.cardAspect`.WIDTH, HEIGHT = 720, 453SCALE = 2# The bare paper of each dye in the owner's pictures, 0–255, read as the median# of a text-free patch: cream off 14's letter and 15's passbook card, blue off# 15's card and 09's call strip, sage off 15's Cash card and 09's dinner strip,# pink off 09's birthday strip. Peach is in no picture and is lifted toward# white by `LIFT`, the fraction of the way cream travelled.TARGET = {# A plain sheet lies AT the ground or a hair lighter, the way 03 and 11# draw it (ground ≈ 238,226,212, sheet ≈ 238–240,225–227,210–213): the# ground token `ground_muted` (#EEE3D6) plus two. It was (243,235,223),# cooler and brighter than the plaster, when the plaster was the ground."cream": (240, 229, 216),# THE TODO INDEX CARD — a shade darker and yellower than the board it# lies on, as the approved `ref-todos-indexcards` draws it (a cream card# reads −2,−9,−15 against its ground there). The sheets and the cards were# one cream until the sheets moved to sit at the ground, and one cream# cannot both sit at the ground and read darker than it, so the card has# its own (`PaperDye.buff`, `PaperDye.indexCard`)."buff": (236, 218, 199),"blue": (222, 229, 237),"sage": (225, 226, 212),"pink": (241, 216, 213),# In no picture. Lifted by `LIFT` alone it landed 0.03 from cream and the# board's yellow project read as a cream one (`PaperDyeTests`), so it is# set as a pale straw that keeps its yellow."straw": (245, 234, 205),}LIFT = 0.55# How much of the photograph's own variation around its mean is kept: the# stains, the lighting gradient, the fibre and the rim's wear, at under half.CONTRAST = 0.45# The centre a sheet's mean is read over — the master without its rim# (`PaperPhoto.rimPixels`), so a worn edge does not darken the target.RIM = 32# The cool off-white read off the news reference (0–255). The sheet is the toned# cream CARRIED there by a per-channel ratio of the two means, so it keeps# cream's fibre, wear and rim — and it is anchored to its own reading, not to# cream's, so moving cream's target does not move newsprint.NEWSPRINT = (230.06, 227.97, 221.98)def alpha_box(image: Image.Image) -> tuple[int, int, int, int]: box = image.getchannel("A").point(lambda v: 255if v > ALPHA else0).getbbox()if box isNone:raiseSystemExit("nothing solid in the picture")return boxdef filled(image: Image.Image) -> Image.Image:"""The opaque paper grown outward into what is left translucent. The master's corners are rounded and its last pixel or two at every side fades, so a straight crop leaves a fringe. Growing the paper into it — each thin pixel taking the mean of its solid neighbours, repeated until the picture is solid — keeps the pale worn pulp that is actually AT the corner rather than painting the dye back over it, which is the one thing the acceptance comparison said the drawn paper got wrong. """ width, height = image.size pixels = image.convert("RGBA").load() solid = [[pixels[x, y][3] > ALPHA for x in range(width)] for y in range(height)] out = Image.new("RGB", (width, height)) out_px = out.load()for y in range(height):for x in range(width): out_px[x, y] = pixels[x, y][:3]for _ in range(64): thin = [ (x, y)for y in range(height)for x in range(width)ifnot solid[y][x] ]ifnot thin:break grown = []for x, y in thin: neighbours = [ out_px[nx, ny]for nx, ny in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1))if0 <= nx < width and0 <= ny < height and solid[ny][nx] ]ifnot neighbours:continue count = len(neighbours) grown.append( ( x, y, ( sum(n[0] for n in neighbours) // count, sum(n[1] for n in neighbours) // count, sum(n[2] for n in neighbours) // count, ), ) )ifnot grown:breakfor x, y, colour in grown: out_px[x, y] = colour solid[y][x] = Truereturn outdef carried(image: Image.Image, frm: tuple, to: tuple) -> Image.Image:"""One dye carried to another, as a per-channel ratio.""" ratio = [to[i] / frm[i] for i in range(3)]returnImage.merge("RGB", [ channel.point(lambda v, r=ratio[i]: min(255, int(round(v * r))))for i, channel in enumerate(image.split()) ], )def centre_mean(image: Image.Image) -> tuple[float, float, float]: width, height = image.size centre = image.crop((RIM, RIM, width - RIM, height - RIM))return tuple(ImageStat.Stat(centre).mean[:3])def toned(image: Image.Image, dye: str) -> Image.Image:"""The sheet moved to its dye's target with its variation at `CONTRAST`.""" mean = centre_mean(image) target = TARGET.get(dye) or tuple(m + (255 - m) * LIFT for m in mean)returnImage.merge("RGB", [ channel.point(lambda v, m=mean[i], t=target[i]: max(0, min(255, int(round(t + (v - m) * CONTRAST)))) )for i, channel in enumerate(image.split()) ], )def write(name: str, image: Image.Image) -> None: folder = CATALOGUE / f"{name}.imageset" folder.mkdir(parents=True, exist_ok=True) image.save(folder / f"{name}.png", "PNG", optimize=True) (folder / "Contents.json").write_text( json.dumps( {"images": [ {"filename": f"{name}.png", "idiom": "universal", "scale": f"{SCALE}x"} ],"info": {"author": "xcode", "version": 1}, }, indent=2, separators=(",", " : "), ) + "\n" ) print("wrote", folder.relative_to(ROOT), image.size)def source(dye: str, out_dir: pathlib.Path | None) -> pathlib.Path:if out_dir isnotNone:return out_dir / GENERATED[CUT_FROM.get(dye, dye)] card = CUT_FROM.get(dye, dye)return CATALOGUE / f"card-{card}.imageset/card-{card}.png"def main() -> None: out_dir = pathlib.Path(sys.argv[1]) if len(sys.argv) > 1elseNone master = source(MASTER, out_dir)ifnot master.exists():raiseSystemExit(f"{master}: the master is missing — every paper is cut with its box") box = alpha_box(Image.open(master).convert("RGBA")) print("cut at alpha >", ALPHA, "→", box) cream = Nonefor dye in DYES: path = source(dye, out_dir)ifnot path.exists(): print("skip", dye)continue cut = Image.open(path).convert("RGBA").crop(box) sheet = toned(filled(cut).resize((WIDTH, HEIGHT), Image.LANCZOS), dye)if dye == MASTER: cream = sheet write(f"paper-{dye}", sheet) print(" measured", tuple(round(v / 255, 4) for v in centre_mean(sheet)))if cream isnotNone: newsprint = carried(cream, centre_mean(cream), NEWSPRINT) write("paper-newsprint", newsprint) print(" measured", tuple(round(v / 255, 4) for v in centre_mean(newsprint)))if __name__ == "__main__": main()