Cotton code
120 lines · 6.1 KB · PythonRaw
#!/usr/bin/env python3"""Generate ONE new tool object for Home, in the set's own lens and light, and cut it to a 600x600 imageset PNG.    python3 scripts/gen-tools/gen_object.py <name> "<what the object is>" [--n 2] [--ref <png>]... [--face "<what is on its face>"]    python3 scripts/gen-tools/gen_object.py <name> [--n 2] [--ref <png>]...   (an object whose spec is committed in SPECS)Writes <cwd>/gen-<name>-<i>.png candidates (transparent, 1024) and, for each, a cut <cwd>/tool-<name>-<i>.png at600x600 with 6 % padding — the shape `export_tool_objects.py` takes. Pick one, copy it over`Media.xcassets/tool-<name>.imageset/tool-<name>.png`, add its print box to `ToolPrint.table` (or its name to`ToolPrint.wordless`), and run `preview_prints.py` to tune the box.HOW IT KEEPS THE SET A SET: the prompt goes to OpenAI's images/edits endpoint with a reference sheet of fourexisting objects (todos, photos, email, alarms) on flat magenta, plus any --ref you add (a previous candidate torefine), so the new object shares the set's top-down camera, its soft upper-left light and its wear. The face theword will be printed on must be asked for BLANK — the name is set live in SwiftUI, never baked in.--face REPLACES the blank-face clause, and exists because of the deck (2026-09-16): an object on a card nolonger carries its own printed name (`ToolObject.Printing.contentOnly`), so an object whose face was left blankFOR that word — the alarm clock's dial, the screenplay's page, the notes sheet — now reads as unfinished ratherthan as quiet. Pass what the face should actually carry ("a printed clock dial with roman numerals and twohands"), and the object comes back able to stand on its own. Leave it off and the face stays blank, which isstill right for an object whose name IS printed live on it (the clipboard, the calendar pad).Key: OPENAI_API_KEY in the environment or ~/.config/cotton/openai.env (see the generate-visual-assets skill).Uses `scripts/gen-caps/gen_image.py` (stdlib) for the call and Pillow + numpy (`/usr/bin/python3`) for the cut."""import pathlib, subprocess, sysimport numpy as npfrom PIL import ImageROOT = pathlib.Path(__file__).resolve().parents[2]CATALOGUE = ROOT / "apps/loom/Sources/CottonPaper/Media.xcassets"GEN = ROOT / "scripts/gen-caps/gen_image.py"REF_SET = ["todos", "photos", "email", "alarms"]STYLE = (    "Match the reference image's objects exactly in style: a photorealistic product photograph seen straight "    "from above, soft diffuse studio light from the upper left, a faint contact shadow, gentle vintage wear, warm "    "cream and paper tones. ONE object only, centred, filling about 85% of the frame, fully transparent "    "background. NO logos and no brand marks anywhere on the object. ")# What the object's face carries when the card prints the name below it instead# of on it — see `--face` in the header.BLANK_FACE = "NO text, NO letters, NO numbers; the face where a word would go is plain and blank."# The committed specs: what an object is and what its face carries, so it is made# again from the repo alone (`gen_object.py <name>`) by whoever holds the key.SPECS = {    # Ahead (money programme step 3, architect's rulings 03:55 G6 and 18:13 IST    # 17 Oct 2026): the money still to come. Money's own object is a leather    # wallet and Calendar's a tear-off pad, so Ahead is neither: the bills and    # payments waiting their turn, filed in order.    "ahead": (        "a small tan kraft-card expanding bill file, an accordion folder seen from above with its flap open, "        "four or five plain paper envelopes and folded bills standing upright in its pockets in a neat row, "        "a short loop of cotton string with a tie button on the flap",        "the envelopes and the pocket tabs are plain paper with NO writing, NO text, NO letters and NO numbers",    ),}def ref_sheet(path):    sheet = Image.new("RGB", (1024, 1024), (255, 0, 255))    for i, n in enumerate(REF_SET):        im = Image.open(CATALOGUE / f"tool-{n}.imageset" / f"tool-{n}.png").convert("RGBA").resize((480, 480))        sheet.paste(im, ((i % 2) * 512 + 16, (i // 2) * 512 + 16), im)    sheet.save(path)def cut(src, dst):    im = Image.open(src).convert("RGBA")    a = np.asarray(im)[..., 3]    ys, xs = np.where(a > 20)    obj = im.crop((xs.min(), ys.min(), xs.max() + 1, ys.max() + 1))    w, h = obj.size    side = int(max(w, h) * 1.12)    c = Image.new("RGBA", (side, side), (0, 0, 0, 0))    c.paste(obj, ((side - w) // 2, (side - h) // 2), obj)    c.resize((600, 600), Image.LANCZOS).save(dst)def main():    args = sys.argv[1:]    if not args:        raise SystemExit(__doc__)    name = args[0]    if name in SPECS and (len(args) == 1 or args[1].startswith("--")):        (what, face), rest = SPECS[name], args[1:]    elif len(args) >= 2:        what, face, rest = args[1], BLANK_FACE, args[2:]    else:        raise SystemExit(f"no spec for {name!r}: say what the object is\n\n{__doc__}")    n, refs = 2, []    while rest:        flag = rest.pop(0)        if flag == "--n":            n = int(rest.pop(0))        elif flag == "--ref":            refs.append(rest.pop(0))        elif flag == "--face":            face = rest.pop(0)        else:            raise SystemExit(f"unknown flag {flag}")    here = pathlib.Path.cwd()    sheet = here / "gen-ref-sheet.png"    ref_sheet(sheet)    # gpt-image-1, not -2: the cut needs a transparent ground, and gpt-image-2    # refuses `background: transparent` outright (HTTP 400, 3 Oct 2026).    cmd = [sys.executable, str(GEN), "--model", "gpt-image-1", "--quality", "high", "--transparent", "--n", str(n),           "--ref", str(sheet)] + [x for r in refs for x in ("--ref", r)] + \          ["--out", str(here / f"gen-{name}.png"), "--prompt", f"{what} {STYLE} {face}"]    subprocess.run(cmd, check=True)    outs = [here / f"gen-{name}.png"] if n == 1 else [here / f"gen-{name}-{i + 1}.png" for i in range(n)]    for i, o in enumerate(outs):        dst = here / (f"tool-{name}.png" if n == 1 else f"tool-{name}-{i + 1}.png")        cut(o, dst)        print("cut", dst)if __name__ == "__main__":    main()