# Faceless page: Codex-д өгөх setup файл

## Худалдан авагчид

Энэ файлыг Codex-д нэг удаа өгөхөд `faceless-page` skill суулгана. Дараа нь Codex тантай хамт
page-ийн тань байнгын дүрийг зохиож, character sheet зураг гаргана. Постын санаагаа сонгоход тэр
дүртэй carousel пост, caption бэлдэж өгнө.

**Юу хэрэгтэй вэ**

- ChatGPT Plus эсвэл түүнээс дээш эрх. Codex нь ChatGPT-ийн эрхэд багтдаг.
- Codex app эсвэл Codex CLI. Энгийн ChatGPT чат дээр энэ файл ажиллахгүй. Учир нь чат таны
  компьютерт программ суулгаж, файл хадгалах боломжгүй.
- Windows 10/11 эсвэл macOS, интернэт, 1 GB орчим сул зай.

**Яаж эхлэх вэ**

1. Codex-оо нээгээд ажлын хавтсаа сонгоорой. Жишээ нь Documents дотор "my-page" нэртэй хавтас
   үүсгээд сонгож болно.
2. faceless-page-setup.md файлыг тэр хавтас руу хуулна, эсвэл Codex-ийн чат руу чирч оруулна.
3. "Энэ файлыг уншаад setup хий" гэж бичээрэй. Codex хэрэгтэй зүйлсээ суулгахаас өмнө зөвшөөрөл
   асууна. Юу суулгахыг нь шалгаад зөвшөөрөөрэй. Setup 5-15 минут үргэлжилнэ.
4. Setup дуусмагц шинэ чат нээгээд `$faceless-page` гэж бичээрэй. Дараа нь Codex-ийн асуултад
   хариулаарай.

**Анхаарах зүйл**

- Бусдын дүр, лого, брэнд, постыг хуулахгүй. Зөвхөн постын хэлбэр, бүтцийг жишээ болгон ашиглана.
- Бодит хүний дүр төрхийг зурахгүй.
- Зураг гаргахад API key хэрэггүй. Codex өөрийн зураг гаргах боломжийг ашиглана.
- Нэг постод 5-10 зураг гаргадаг, зарим слайдыг дахин гаргавал түүнээс олон. Энэ нь Codex-ийн хэрэглээний хязгаараас зарцуулагдана.

---

# For Codex: install the `faceless-page` skill

The user handed you this file to set up a skill that builds a faceless social-media page around one
recurring original character: it designs the character with the user, makes a character sheet with
your built-in image generation, collects post ideas, and produces finished carousel slides and
captions. Do exactly what this section lists, nothing else. Talk to the user in their language
(Mongolian when they write Mongolian); keep tool names in English.

Every step checks first and skips what is already there, so running this file again is safe. If
your sandbox blocks a download or an install, ask the user to approve that one command.

## 1. Tell the user the plan and get one OK

List in the user's language what you will do, then ask once and wait for yes:

- Install Python 3.9+ only if it is missing (a system install; Windows may ask for permission).
- Create the skill folder `faceless-page` in Codex's skills folder (usually `~/.codex/skills/`) with
  six files from this document, a Python environment inside it with Pillow, and the Montserrat font
  (SIL Open Font License) downloaded from Google Fonts' GitHub.
- Run a self-test.
- No API key is needed: pictures come from Codex's built-in image generation.

## 2. Python

Detect the OS. Judge each check by what it prints (a version number), not by its exit code.

- **Windows (PowerShell):** run `py -3 --version`. If `py` is missing but `python --version` prints
  3.9 or newer, use `python` wherever this file says `py -3`. Otherwise install:
  `winget install -e --id Python.Python.3.12 --accept-source-agreements --accept-package-agreements`.
  A program installed during this session is not on this session's PATH: from then on, start
  **every** command that calls Python with
  `$env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') + ';' + [Environment]::GetEnvironmentVariable('Path','User');`
- **macOS:** run `python3 --version`. If macOS offers to install its developer tools, ask the user to
  click Install and wait for it to finish, then check again. If `python3` is still missing or older
  than 3.9, ask the user to install Python from https://www.python.org/downloads/macos/ , wait for
  them, then continue. Homebrew is not needed.
- **Linux or WSL:** use `python3` (3.9+). If creating the environment below fails because `venv` is
  missing, ask the user to run `sudo apt install python3-venv` (or their distro's package), then retry.
- A failed install: show the error to the user in plain words and stop. Do not work around it.

## 3. Write the skill

The six files are in the **Files** section at the end of this document. Each is everything between
its `~~~~` fence lines and must land byte for byte. Do not change, shorten or "improve" them.

- **You know this document's path:** write the script below to a temp file `extract.py` and run it:
  `py -3 extract.py "<this document>"` (Windows) or `python3 extract.py "<this document>"`. It finds
  Codex's skills folder itself (`CODEX_HOME`, else `~/.codex`), writes the six files, and prints the
  skill folder and whether image generation is present.
- **You only have the text** (the user pasted it): write each file with your file tool, exactly as it
  stands, into `<CODEX_HOME or ~/.codex>/skills/faceless-page/`.

```python
import io, os, re, sys

for stream in (sys.stdout, sys.stderr):
    try:
        stream.reconfigure(encoding="utf-8", errors="replace")
    except Exception:
        pass
doc = sys.argv[1]
home = os.path.expanduser(os.environ.get("CODEX_HOME") or "~/.codex")
dest = os.path.abspath(os.path.expanduser(sys.argv[2])) if len(sys.argv) > 2 else os.path.join(home, "skills", "faceless-page")
text = io.open(doc, encoding="utf-8-sig").read().replace("\r\n", "\n").replace("\r", "\n")
files = re.findall(r"^## ([\w./-]+)\n\n~~~~\w*[ \t]*\n(.*?)\n~~~~[ \t]*$", text, re.S | re.M)
if len(files) != 6:
    sys.exit("expected 6 files, found %d" % len(files))
for name, body in files:
    path = os.path.join(dest, *name.split("/"))
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with io.open(path, "w", encoding="utf-8", newline="\n") as h:
        h.write(body + "\n")
    print("wrote", path)
print("skill folder:", dest)
found = os.path.isfile(os.path.join(home, "skills", ".system", "imagegen", "SKILL.md"))
print("image generation:", "found" if found else "missing")
```

If it prints `image generation: missing`, finish the steps below anyway, then tell the user to update
Codex (the app updates itself; the CLI: `npm install -g @openai/codex@latest`) before making pictures.

Then the Python environment and the font. Use the skill folder `extract.py` printed:

- Windows (PowerShell):
  ```
  $skill = "<the skill folder>"
  py -3 -m venv "$skill\.venv"
  & "$skill\.venv\Scripts\python.exe" -m pip install -r "$skill\tools\requirements.txt"
  & "$skill\.venv\Scripts\python.exe" "$skill\tools\compose.py" fetch-font
  ```
- macOS / Linux:
  ```
  skill="<the skill folder>"
  python3 -m venv "$skill/.venv"
  "$skill/.venv/bin/python" -m pip install -r "$skill/tools/requirements.txt"
  "$skill/.venv/bin/python" "$skill/tools/compose.py" fetch-font
  ```
- If pip or the font download fails, run that one command once more (a first run can time out).
  `fetch-font` keeps a file only when its bytes match the expected font, so a broken download is
  replaced on the next run.

## 4. Self-test

- Windows: `& "$skill\.venv\Scripts\python.exe" "$skill\tools\compose.py" --selftest "$env:TEMP\faceless-selftest"`
- macOS / Linux: `"$skill/.venv/bin/python" "$skill/tools/compose.py" --selftest "${TMPDIR:-/tmp}/faceless-selftest"`

It makes test slides with Mongolian words, checks them, and must print `SELFTEST OK`. On
`SELFTEST FAIL` or a crash, run `fetch-font` once more and the self-test once more. If it still
fails, show the output to the user and stop. Never edit the skill's files to make it pass. Delete
the self-test folder at the end.

## 5. Hand over

Tell the user, in their language. In Mongolian, use this text:

> Setup дууслаа. Одоо ингэж ашиглаарай:
> 1. Codex-д шинэ чат нээгээд `$faceless-page` гэж бичээрэй.
> 2. Codex таны page-ийн сэдэв, нэр, хэл, өнгийг асууж, дүрийн 3 санал гаргана.
> 3. Таалагдсан дүрээ сонгоход 6 өнцгөөс харуулсан character sheet зураг гаргана. Хүсвэл дүрээ засварлуулж болно.
> 4. Дараа нь постын хэдэн санаа санал болгоно. Та нэгийг нь сонгоход 5-10 слайдтай carousel пост, caption бэлдэж өгнө.
>
> `$faceless-page` гарч ирэхгүй байвал Codex-оо хаагаад дахин нээгээрэй.

If Python was installed with winget, add that they must quit Codex completely and reopen it first.

---

# Files

## SKILL.md

~~~~markdown
---
name: faceless-page
description: Build and run a faceless Instagram page around one recurring original character. Designs the character with the user, makes its character sheet with the built-in image generation, collects post ideas, then makes finished 3:4 carousel slides (artwork by image generation, words set exactly by a script) and the caption. Use when the user says "$faceless-page", "faceless page", "faceless пост", "page-ийн дүр", "дүртэй page" or asks for the next post of their faceless page.
---

# Faceless page

One recurring character carries every post. The character is designed once, drawn once on a
character sheet, and then held exactly the same in every picture. The image model draws artwork
only; `tools/compose.py` sets the words, so every letter comes out exactly as written.

**Paths.** `SKILL_DIR` = this skill's folder (`$CODEX_HOME/skills/faceless-page`, usually
`~/.codex/skills/faceless-page`; Windows `%USERPROFILE%\.codex\skills\faceless-page`).
`PY` = `SKILL_DIR/.venv/bin/python` (macOS/Linux) or `SKILL_DIR\.venv\Scripts\python.exe` (Windows).
`COMPOSE` = `SKILL_DIR/tools/compose.py`. Run them by absolute path.

**Images.** Use the built-in image generation (the `imagegen` skill's default built-in `image_gen`
tool). Never offer its CLI/API fallback unless the user asks for it; that needs an API key, and this
skill is sold as needing none. Send each filled template from the references word for word: do not
restructure it into another prompt schema, because the order (identity reminder and artwork-only
sentence last) is part of the method. Generated files land under `$CODEX_HOME/generated_images/`;
copy every image you keep into the work folder. To use the character sheet as the identity
reference, load it with `view_image` right before each generation, so it is always in view.
If image generation is unavailable or the usage limit runs out: stop, keep `plan.md` and
`prompts.md` as they are, tell the user plainly (try again later, or update Codex), and continue
from the first missing image next time.

**Talk** to the user in their language (Mongolian when they write Mongolian). Keep tool names in English.

**Work folder** (in the current workspace):

```
page/
  brand/brand.json          name, handle, language, colour (hex + shadow + highlight)
  brand/CHARACTER.md        the character bible
  brand/WORLD.md            the world lock
  brand/character-sheet.png the one approved sheet, and sheet-prompt.txt beside it
  ideas.md
  posts/<YYYY-MM-DD>-<slug>/  plan.md, prompts.md, raw/, post.json, slides/, caption.txt
```

Folder and file names use only Latin letters, digits and dashes (a slug like `2026-11-02-money-habits`),
even when the post is in Mongolian.

## 0. Start

- Quick check: `PY COMPOSE --selftest <a temp folder>` prints `SELFTEST OK`. If not, tell the user to
  run the setup file again. Do not work around it.
- If `page/brand/brand.json` is missing, do **Part A** first. Otherwise ask, in one line, what the
  user wants: a new post (Part B), new ideas, or a change to the character.

## Part A. The character (once)

### A1. Ask once, all together

Ask only what the user has not already given. In Mongolian:

> Page-ийнхээ дүрийг хамт зохиоё. Мэдэхгүй асуултаа алгасаж болно, би санал болгоно:
> 1. Page чинь ямар сэдэвтэй вэ? Хэнд зориулсан бэ? (жишээ нь: оюутнуудад мөнгөө зөв зарцуулах талаар зөвлөгөө өгөх)
> 2. Page-ийн нэр, handle юу вэ? (жишээ нь: @money.mind)
> 3. Постын текст ямар хэлээр байх вэ?
> 4. Ямар дүртэй баймаар байна? (амьтан, дайчин, ид шидтэн, энгийн залуу гэх мэт) Санаа байхгүй бол би 3 дүр санал болгоё.
> 5. Page-ийнхээ гол өнгийг сонгосон уу? Үгүй бол би санал болгоё.

The page colour must be vivid and bright (it is also the colour of the key words on a dark band):
not white, black, grey or pastel. `compose.py` refuses a pale or dark colour. If the user wants one,
suggest the nearest vivid shade and explain why.

Without a character idea, offer **three original concepts**. Each: an archetype (an animal, a
stylized human, a creature), **one signature item** that makes a clear silhouette even as a small
thumbnail (a helmet, a mask, a hat, ears, a scarf), a personality in five words, and **one saturated
colour**. Explain why in one line each. Never base a concept on another page's character, a real
person, a celebrity, or a brand mascot.

### A2. Write the bible and the world

Read `SKILL_DIR/references/character.md` and `SKILL_DIR/references/world.md`, then write
`page/brand/CHARACTER.md`, `page/brand/WORLD.md` and `page/brand/brand.json`
(`{"name": ..., "handle": ..., "language": ..., "color": "#RRGGBB", "shadow": "#RRGGBB", "highlight": "#RRGGBB"}`).
The rules that matter most are in those files: the character's colour is the page's text colour,
the eyes are another colour, an adult is written and drawn as an adult, and five traits never change.

Show the user the character in 6-8 plain lines and ask for an OK or changes.

### A3. The character sheet

1. Build the prompt from the sheet template in `references/character.md`, filled from `CHARACTER.md`.
   Save it to `page/brand/sheet-prompt.txt`.
2. Generate one landscape image.
3. Check it against the five never-change traits, the adult cues, the outfit, and "no words, no
   logos". Measure the colour: `PY COMPOSE colour <image> <#hex>`. `PASS` is good; `CHECK` means look:
   judge the hue first, because shading darkens the colour. `COLOUR NOT FOUND` means judge by eye;
   never generate again for that alone.
4. At most two more tries, each with one targeted change. Then show the best one to the user.
5. When the user approves, copy it to `page/brand/character-sheet.png`. **The sheet is the authority
   from now on**: if `CHARACTER.md` and the sheet disagree on anything, rewrite `CHARACTER.md` to
   describe the sheet, and say so. Keep one sheet only.

**Changing the character later** (the user asked for it): move the current sheet and its prompt to
`page/brand/old/<YYYY-MM-DD>-character-sheet.png` and `...-sheet-prompt.txt`, update `CHARACTER.md`
and `brand.json`, then make and approve a new sheet at the same path, exactly as in A3. Every post
after that uses the new sheet.

## Part B. A post

### B1. The idea

Ask for a topic, or propose 10 ideas for the page's audience (`references/posts.md`, "Ideas").
Save the list to `page/ideas.md` and let the user pick one.

### B2. The words first

Write `plan.md` before any image (images cost the most): the cover line, each slide's top and
bottom line, the final slide, and per slide one short scene description for each half. Follow
`references/posts.md` ("Carousel", "Words on slides"). Check spelling and grammar line by line.
Show the plan; go on after the user's OK.

### B3. The pictures

1. Before each slide: `view_image` on `page/brand/character-sheet.png`.
2. One image per slide, built from the per-slide template in `references/posts.md`, with the full
   `WORLD.md` block pasted in, the identity reminder at the end, and the "artwork only" sentence as
   the last line. Ask for a tall portrait image holding two stacked scenes (the `split` layout), or
   one scene for a `single` slide.
3. Save each prompt to `prompts.md` and copy each kept image to `raw/NN.png`.
4. Check every image (`references/posts.md`, "Check"). Redo a failed slide at most twice, each time
   with one targeted change. A slide that still fails: tell the user which rule it breaks.

### B4. The words on the pictures

Write `post.json` (size `[1080, 1440]`, the page colour, the handle, one entry per slide; words to
show in the page colour go between `*stars*`) and run `PY COMPOSE post <post.json>`. Look at every
file in `slides/`: the words readable, nothing important under them, nothing cut off. Fix the words
in `post.json`, never the check.

### B5. The caption and the hand-over

Write `caption.txt` from `references/posts.md` ("Caption"). Check its spelling. Then give the user:
the `slides/` folder path, the caption, and 3-4 lines on what to check before posting.

## Rules

- **Original only.** Never draw another page's character, a real person, a celebrity, a brand
  mascot, a logo, or readable brand names. Learning a format is fine; copying a post is not.
- **One sheet, one source.** Every rule lives in one file. When a trait changes, update the sheet
  prompt, `CHARACTER.md`, `WORLD.md` and every template that repeats it, together.
- **Never write "photo", "photograph" or "photorealistic"** in an image prompt. Write "drawn,
  stylized 3D, not photoreal".
- **Images cost the user's usage limit.** A post takes 5-10 images, more when a slide is redone;
  the sheet takes up to 3. Make the words right before any image.
- **Words are never drawn by the image model.** Every prompt ends with the artwork-only sentence.
- **Dated advice is labelled as dated.** Platform rules change; say "as of 2026" when you quote one.
~~~~

## references/character.md

~~~~markdown
# The character: bible and sheet

## Why these rules exist

Each rule below fixed a real failure on a working faceless page.

- **The character wears the page's ink.** On the strongest faceless pages the character's skin or
  body colour is the same colour as the words on the slides (a yellow character with yellow words,
  a blue one with blue words). "Close enough" reads as two different colours. Pick one hex and use
  it for both.
- **The eyes are not that colour.** When skin and eyes share the brand colour, the face reads flat.
  Give the eyes a neutral (light grey, dark brown) or a clearly different colour.
- **Write proportions as a number that matches the sheet.** A bible once said "head to body 1:4"
  while the sheet showed an adult of about 1:6.5. The image model followed the number and drew a
  child. For an adult, state the age first and call it the most important trait.
- **Ban the child cues by name** for an adult character: large round eyes, a small button nose,
  chubby cheeks, a soft chinless jaw, a big head on a short body.
- **Full-length trousers by default** for an adult. Bare legs make a grown character read as a
  schoolchild. Shorts only when a scene asks for sport or summer.
- **Give the signature item exact counts and wrong shapes.** "Exactly one stone. It is NOT a tall
  brush, NOT a cap, NOT a crown." Without this the model swaps or reshapes it.
- **Calm beats loud.** A character who notices and says little reads as wiser and more relatable
  than one who shouts. Ban big grins and open mouths in the expression list.
- **One colour, one hero.** Only the main character carries the saturated colour. Everyone else
  is desaturated (see `world.md`).

## CHARACTER.md template

Fill every section. Keep it to about two pages.

```markdown
# <NAME>: character bible

## Who
<One line: who they are and what they stand for on this page. They are a relatable storyteller,
not an expert.>

## Age and look
<Age in years (for an adult: "a grown <man/woman> of about <AGE>, not a child, not a teenager").
Overall look in three lines.>

## Proportions
<Body about <N> head-heights tall (an adult: about 6 to 7). Shoulders vs hips. Build. Hands: five
fingers, simple shapes.>

## Colour
Base <#HEX> (= RGB r, g, b; hue <h> degrees), a <which-way>-leaning <colour>. It is NOT <the
neighbour colours it could drift to>. Shadow <#HEX>, highlight <#HEX>. Uniform and matte: no pores,
veins, spots, gloss or plastic shine. The same colour as the words on the page's slides.

## Face
<Jaw, cheekbones, nose, mouth, eyebrows. For an adult: adult-sized eyes, a defined jaw.>

## Eyes
<Size (adult-sized), iris colour that is NOT the base colour, dark pupils, clean whites.>

## Signature item
<Shape, material, colour. Exact counts ("exactly one <detail>"). It is NOT <wrong shapes>.>

## Outfit
<Default outfit, plain, no logos, prints or writing. Full-length trousers for an adult. Allowed
swaps by scene (hoodie, jacket, business casual). The item, colour and eyes never change.>

## Style
Premium stylized 3D animation: 75% stylized, 25% realism. Simple shapes, soft volume, matte
materials, clean shading. Readable as a small thumbnail.

## Personality
Is: <5-8 traits>. Never: <shouts, preaches, brags, poses theatrically, grins widely>.

## Poses
<6-9 everyday poses, e.g. hands in pockets, looking at a phone, sitting back, one raised eyebrow.>

## Expressions
1. Calm neutral 2. Slightly unimpressed 3. One raised eyebrow 4. Small closed-mouth smile
5. Thinking 6. Tired but calm 7. Mildly surprised 8. Focused, decided 9. Disappointed at a phone
10. Quietly proud. No wide grins, open mouths or childlike joy.

## Topics
<The page's 6-10 recurring topics.>

## Voice
<3-5 sample lines: short, plain, true. What they never say.>

## Five traits that never change
1. <colour> 2. <eyes> 3. <signature item> 4. <its detail> 5. <silhouette or another marker>

## What they must never look like
A real person, a celebrity, a historical figure, a superhero, a chibi or baby mascot, a plastic
toy, an anime character, a clown, <the neighbours of this concept that would confuse it>.
```

## The sheet

One landscape image, 16:9, on a plain neutral warm-grey studio backdrop with soft shadows and no
words. Six views of the same character at the same scale and light:

- **Left half:** two full-body views side by side. Front, arms relaxed at the sides; three-quarter,
  relaxed, one hand in a pocket.
- **Right half:** four head-and-shoulders views in a 2x2 grid. Front, neutral; three-quarter, small
  closed-mouth smile; full side profile; the other three-quarter, one eyebrow slightly raised.

### Sheet prompt template

Fill the `<...>` parts from `CHARACTER.md`. Keep the order.

```text
Create a character reference sheet for ONE original character in premium stylized 3D animation
(75% stylized, 25% realism), clean matte surfaces, soft studio light. Drawn, stylized 3D, not photoreal.

LAYOUT: one landscape 16:9 image on a plain neutral warm-grey studio backdrop with soft contact
shadows and nothing else. Six views of the SAME character at the same scale and lighting. Left
half, two full-body views side by side: (1) front, standing straight, arms relaxed at the sides;
(2) three-quarter, relaxed, one hand in a pocket. Right half, four head-and-shoulders close-ups in
a 2x2 grid: (3) front, neutral; (4) three-quarter, small closed-mouth smile; (5) full side profile;
(6) the other three-quarter, one eyebrow slightly raised.

CHARACTER: <a GROWN <man/woman> of about <AGE>, not a child, not a teenager, not a chibi mascot | an
<animal/creature archetype>>. Body about <N> head-heights tall, <shoulders vs hips>, <build>.
Face: <jaw>, <cheekbones>, <nose>, <mouth>, <eyebrows>. Eyes: adult-sized, <iris colour that is
NOT the skin colour>, dark pupils, clean whites.

COLOUR, THE ONE THING THAT MUST BE EXACT: completely uniform matte <colour name>, exactly <#HEX> =
RGB (<r>, <g>, <b>), hue <h> degrees, a <which-way>-leaning <colour>; it is NOT <neighbour colours>.
Shadow <#HEX>, highlight <#HEX>. No pores, veins, spots, gloss, plastic sheen or metallic finish.
A stylized character whose skin is a flat brand colour, not sickly, alien, robotic or a toy.

SIGNATURE ITEM: <shape, material, colour>, with exactly <one> <detail>. It is NOT <wrong shapes>.
OUTFIT: <plain default outfit; full-length trousers for an adult>, no logos, prints or writing.
EXPRESSION: <base expression>.
Do not add: a second <detail>, horns, crowns, armour, jewellery, patterns, tattoos, extra props.

The character is a GROWN <man/woman> of about <AGE>. If they could be mistaken for a child of
twelve, the picture is wrong.
Render artwork only: no words, letters, numbers, labels, logos, watermarks or glyph-like marks.
```

### Checking the sheet

- The five traits are all present in all six views, identical.
- An adult reads as an adult: proportions, jaw, eye size, trousers.
- `PY COMPOSE colour <image> <#hex>`: `PASS`, or a `CHECK` whose hue is right (shading darkens the
  measured colour; the hue matters most). After two misses, accept the closest and say so.
- No words, letters, logos, or a second copy of the signature detail.
~~~~

## references/world.md

~~~~markdown
# The world lock

Every picture happens in the same world, and that world is described once, in one block, pasted
unchanged into every image prompt. "Two copies of a rule become two different rules": keep the
block in `page/brand/WORLD.md` only and paste it from there.

## What goes in it

- **A fictional place** that fits the page's audience: neither a real city nor a historical set.
  Modern daily life (cafés, offices, homes, shops, phones, laptops) inside a fixed material palette.
- **3-6 materials** and one accent light colour, plus 2-3 subtle cultural echoes in the shapes.
- **One lighting recipe** and matte surfaces, the same style ratio as the character (75% stylized
  3D, 25% realism).
- **Bans:** real brands, logos, readable signs, flags, watermarks, photoreal real-world places.
  The model likes to decorate crowds and poles with flags: if the scene does not ask for one, poles
  stand bare.
- **Supporting people:** everyone except the main character is desaturated (a warm stone grey works
  well), with dark-grey non-glowing eyes, slightly smaller heads, simplified faces and quiet muted
  clothes. They never get the hero's colour, signature item or equal prominence. The strongest
  faceless pages do exactly this: one saturated hero among grey people.
- **Visual hierarchy:** the hero carries the idea; grey people are society, customers, coworkers,
  family; accent light and objects mean opportunity, clarity and growth; the architecture sets the
  world.

Keep the world's accent light restrained and different from the hero's colour, or the hero loses
contrast in a small thumbnail.

## WORLD.md template

```markdown
# <WORLD NAME>: world lock

Paste the block below, unchanged, into every image prompt.

WORLD LOCK: Set the scene in <WORLD NAME>, a fictional contemporary <culture> place that is
neither a real city nor a historical set. Modern daily life happens inside architecture of
<3-6 materials>, with <accent colour> glass and restrained <accent colour> practical light. Forms may
subtly echo <2-3 cultural motifs>. Distant <landscape> gives atmospheric depth. Every modern object
is an original unbranded design in this material language. Cinematic <lighting>, clean matte
surfaces, 75% premium stylized 3D and 25% realism, drawn, not photoreal. No real-world brands,
logos, readable signs, flags, watermarks or photoreal real-world places. Poles and walls stand bare
unless the scene asks for something on them.

SUPPORTING PEOPLE LOCK: <HERO> is the only <hero colour> character. Every other person is a
desaturated warm stone-grey stylized 3D figure with dark-grey non-glowing eyes, slightly smaller
heads, simplified clean faces and quiet <muted palette> clothing. They never have <hero colour>
skin or eyes, <signature item>, or equal prominence.

VISUAL HIERARCHY: <hero colour> <HERO> carries the main idea. Grey figures are society, customers,
coworkers, friends or family. <accent colour> light and objects signal opportunity, clarity and
growth. The architecture establishes the world.
```
~~~~

## references/posts.md

~~~~markdown
# Posts: ideas, carousel, prompts, words, caption, check

## Ideas

Ten ideas for the page's audience, each one line: the cover line, then the format.

- Good topics are everyday struggles the audience recognises in one second (money habits,
  discipline, phone addiction, study, work, relationships, rest), told from the character's calm,
  observing point of view. The character is a relatable storyteller, not an expert.
- Formats that work on faceless pages (copy the shape, never another page's words or scenes):
  - **Flaw → fix:** each slide's top half shows a common mistake, the bottom half the better habit.
  - **Refrain:** each slide shows a different situation on top and the same short line underneath.
  - **Steps:** a short numbered path to one result, one step per slide.
  - **This vs that:** two ways to do the same thing, top and bottom.

## Carousel

- **Size** 1080 x 1440 (3:4, the shape the strongest faceless pages use). 5-10 slides; let the
  story set the count and cut any slide that does not earn its swipe.
- **One idea per slide** and one look across all slides.
- **Cover:** the character visible, and a bold verdict, not a neutral summary. Open a loop and keep
  the answer for the inside ("…here is how:", a question, "you" stakes). Never promise what the
  slides do not deliver.
- **Inside:** the most interesting item first. No two neighbouring slides on the same point. Tease
  the next slide so that stopping feels like leaving mid-sentence. A soft "save this" around the
  middle of a long post.
- **Last slide:** the same format, with one action: follow, plus the specific thing the page gives
  every week ("a money habit every day"). Never "follow for more" alone. No fake scarcity.
- **Split layout** (the default): one portrait image, two stacked scenes, top = situation or flaw,
  bottom = answer or reframe. `compose.py` cuts it at the exact middle.

## Words on slides

- At most 2 short lines per half, ALL CAPS is fine, plain words. Gloss any jargon.
- Put 1-3 key words between `*stars*` in `post.json`; they are set in the page colour.
- Write every line in the page's language and check spelling letter by letter before any image is
  made. The words are set by `compose.py`, never drawn by the image model.

## Per-slide image prompt

Fill from `CHARACTER.md`; paste the `WORLD.md` block whole. Keep the order: a long prompt is read
most strongly at its end, so the identity reminder and the artwork-only sentence come last.

```text
Image 1 is the character sheet: use it as the exact identity reference for <HERO>'s face, colour,
eyes and <signature item>. Do not draw the sheet itself.

<HERO> IDENTITY LOCK: <HERO> is <a GROWN <man/woman> of about <AGE> | <archetype>>. Body about <N>
head-heights, <adult cues>. Face: <...>. Do not give <HERO> <child cues>: those are child cues.
Colour: <the colour line from CHARACTER.md: hex, RGB, hue, NOT-list, shadow, highlight>.
Expression: <the slide's expression from the library>.

<ITEM> LOCK, THE SAME OBJECT IN EVERY PICTURE: <positive shape>. Exactly one <detail>. It is NOT
<wrong shapes>. Do not add <extras>.

WARDROBE: <default outfit, full-length trousers>. The sheet is the reference for face, colour, eyes
and <ITEM> only; if the scene names other clothing, the scene wins.

PERSONALITY: <is ...>; never <shouts, preaches, poses theatrically, grins widely>.

<the WORLD.md block, unchanged>

FRAME (split slides): create ONE single portrait image that contains TWO complete scenes stacked
vertically. A single horizontal cut across the exact middle divides the canvas into an upper and a
lower half of identical height. There is NO black bar, NO strip, NO white line, NO gutter, NO
border, NO frame and NO margin; every pixel is picture content. In each half keep the bottom fifth
visually calm (a floor, a desk surface, a wall, a soft out-of-focus background) with no face or
important object there; do not darken it and do not mark it.
[single slides instead: ONE tall portrait scene; keep the bottom third visually calm.]

TOP HALF: <who, doing what, where, light>. The bottom fifth is <plain floor/wall>.
BOTTOM HALF: <scene>. Same light, same style as the upper half. The bottom fifth is <...>.

IN EVERY PART OF THE PICTURE: <HERO> wears the same <ITEM>, never omitted, reduced or redesigned.
EVERY OTHER PERSON has desaturated warm stone-grey skin, including people far in the background,
in a crowd, turned away or out of focus. <HERO> is a GROWN <man/woman> of about <AGE>; if they could
be mistaken for a child of twelve, the picture is wrong. Drawn, stylized 3D, not photoreal.
Render artwork only. Do not generate any words, letters, numbers, captions, labels, logos,
watermarks, readable screens or glyph-like marks anywhere in the image.
```

Variants:
- **POV slide:** the camera is the hero's eyes; only the hero's hands show, in the hero's colour.
  Say "do not pull the camera back to show the head".
- **Hero absent:** say so in the scene ("<HERO> is not in this picture"), or the model invents hands.

## Caption

- First line: one emoji and one complete hook sentence that lands before Instagram's "…more".
- Then short paragraphs of one or two sentences: the idea explained plainly, about 90-200 words.
- One honest caveat near the end where it applies.
- End with one question to the reader, then one call to action (follow, save, or send to a friend).
- 4-5 emoji in total, never inside a sentence. 3-5 hashtags: one or two broad, the rest
  about the page's topic. (Instagram limited posts to 5 hashtags in 2025-2026; check that this is
  still true.)
- Check spelling, names and numbers.

## Check

Every image, before `compose.py`:
- The five never-change traits are there and the same as on the sheet; the colour is the page's
  colour (judge the hue).
- An adult still reads as an adult; trousers unless the scene asks otherwise.
- Every other person is stone grey, even far away or blurred.
- No words, letters, numbers, logos, readable signs, flags or screens with text.
- Split slides: the cut sits at the middle with no band, line or border; the bottom fifth of each
  half is calm.
- Not photographic, not too dark. A dark or muddy picture: generate again rather than brighten.

Every slide after `compose.py`: the words readable and spelled right, nothing important hidden.

Known failures and their fixes:
- **Colour drifts** (e.g. green-teal to cyan): give hex, RGB and hue, name the drift ("NOT cyan"),
  give shadow and highlight. After two misses, accept the closest and say so.
- **Looks like a child:** age first, proportions as a number, child cues banned by name, trousers,
  the "child of twelve" line at the end.
- **Item reshaped or missing:** describe it positively, add the NOT-list, repeat it at the end.
- **Grey people come out in normal skin:** the end reminder must name the background, crowd and
  blurred people.
- **Words or signs appear:** the artwork-only sentence must be the last line.
- **A band between the two scenes:** paste the FRAME block whole; never make the halves as two files.
~~~~

## tools/compose.py

~~~~python
# -*- coding: utf-8 -*-
"""Set the words on faceless-page slides, and check a character's colour.

    python compose.py post <post.json>             build every slide listed in post.json
    python compose.py colour <image> <#RRGGBB>     measure the character's lit colour against the target
    python compose.py fetch-font                   download Montserrat (SIL Open Font License) next to this file
    python compose.py --selftest <folder>          make test slides, print SELFTEST OK or FAIL

The image model draws artwork only; the words are set here, so every letter (Cyrillic included)
comes out exactly as written. post.json:

    {"size": [1080, 1440], "color": "#F0BA34", "handle": "@mypage", "out": "slides",
     "slides": [{"layout": "split", "image": "raw/01.png", "top": "TOP LINE", "bottom": "BOTTOM *KEY* LINE"},
                {"layout": "single", "image": "raw/02.png", "text": "ONE LINE"}]}

Paths are relative to post.json. Words between *stars* are set in the page colour, the rest in white.
A split image holds two stacked scenes; it is cut at the exact middle and each half gets its line.
Every line must fit in two lines; a line that does not fit stops the build with TOO LONG.
"""
from __future__ import annotations

import colorsys
import json
import os
import re
import sys

for _stream in (sys.stdout, sys.stderr):  # paths and words may be Cyrillic; never crash on printing them
    try:
        _stream.reconfigure(encoding="utf-8", errors="replace")
    except Exception:
        pass

from PIL import Image, ImageDraw, ImageFilter, ImageFont

HERE = os.path.dirname(os.path.abspath(__file__))
FONT_DIR = os.path.join(HERE, "fonts")
FONTS = [
    os.path.join(FONT_DIR, "Montserrat.ttf"),
    r"C:\Windows\Fonts\arialbd.ttf",
    "/System/Library/Fonts/Supplemental/Arial Bold.ttf",
    "/Library/Fonts/Arial Bold.ttf",
    "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
]
# One pinned revision of Google Fonts (its files never change), and each file's exact size there.
FONT_SOURCE = "https://github.com/google/fonts/raw/76fca9fd0bb4/ofl/montserrat/"
FONT_FILES = [
    ("Montserrat%5Bwght%5D.ttf", "Montserrat.ttf", 744936),
    ("OFL.txt", "OFL.txt", 4400),
]
LAYOUTS = {"split": ("top", "bottom"), "single": ("text",)}


class Stop(Exception):
    """A problem the user or Codex must fix in post.json; reported, never worked around."""


def font(size):
    for path in FONTS:
        if os.path.exists(path):
            f = ImageFont.truetype(path, size)
            try:  # Montserrat is a variable font: pick the extra-bold weight
                f.set_variation_by_axes([800])
            except Exception:
                pass
            return f
    return ImageFont.load_default(size=size)


def hex_rgb(value):
    value = str(value).strip().lstrip("#")
    if not re.fullmatch(r"[0-9a-fA-F]{6}", value):
        raise Stop("colour must look like #RRGGBB, got %r" % value)
    return tuple(int(value[i:i + 2], 16) for i in (0, 2, 4))


def page_colour(value):
    """The page colour is also the colour of the key words on a dark band: it must be vivid and bright."""
    rgb = hex_rgb(value)
    _, s, v = colorsys.rgb_to_hsv(*(c / 255 for c in rgb))
    if s < 0.35 or v < 0.45:
        raise Stop("colour %s is too pale or too dark to read on the slides; pick a vivid, bright colour" % value)
    return rgb


def cover(img, width, height):
    """Scale to fill width x height, then crop the middle."""
    scale = max(width / img.width, height / img.height)
    resized = img.resize((max(width, round(img.width * scale)), max(height, round(img.height * scale))), Image.LANCZOS)
    left, top = (resized.width - width) // 2, (resized.height - height) // 2
    return resized.crop((left, top, left + width, top + height))


def runs(text):
    """'A *KEY* LINE' -> [('A ', False), ('KEY', True), (' LINE', False)], upper-cased."""
    out, accent = [], False
    for part in text.upper().split("*"):
        if part:
            out.append((part, accent))
        accent = not accent
    return out


def wrap(text, f, width):
    """Lines of (word, accent) pairs that fit the width."""
    words = []
    for part, accent in runs(text):
        words += [(w, accent) for w in part.split()]
    lines, line = [], []
    for word in words:
        trial = " ".join(w for w, _ in line + [word])
        if line and f.getlength(trial) > width:
            lines.append(line)
            line = [word]
        else:
            line.append(word)
    if line:
        lines.append(line)
    return lines


def fit(text, width, start, smallest, max_lines=2):
    """The largest size at which text fits in max_lines; None if it does not fit even at smallest."""
    size = start
    while size >= smallest:
        f = font(size)
        lines = wrap(text, f, width)
        if len(lines) <= max_lines and all(f.getlength(" ".join(w for w, _ in line)) <= width for line in lines):
            return f, lines, size
        size -= 2
    return None


def shade(canvas, box, strength=0.72):
    """A dark gradient that rises from the bottom of box, so white words stay readable."""
    left, top, right, bottom = box
    height = bottom - top
    mask = Image.new("L", (1, height))
    for y in range(height):
        mask.putpixel((0, y), int(255 * strength * (y / max(1, height - 1)) ** 1.6))
    mask = mask.resize((right - left, height))
    canvas.paste(Image.new("RGB", (right - left, height), (0, 0, 0)), (left, top), mask)


def words_at(canvas, fitted, zone, color):
    """Set already-fitted text centred near the bottom of zone (left, top, right, bottom)."""
    f, lines, size = fitted
    left, top, right, bottom = zone
    line_h = int(size * 1.12)
    y = bottom - int((bottom - top) * 0.07) - line_h * len(lines)
    shade(canvas, (left, max(top, y - int(size * 1.6)), right, bottom))
    glow = Image.new("RGBA", canvas.size, (0, 0, 0, 0))
    ink = Image.new("RGBA", canvas.size, (0, 0, 0, 0))
    dg, di = ImageDraw.Draw(glow), ImageDraw.Draw(ink)
    space = f.getlength(" ")
    for line in lines:
        line_w = sum(f.getlength(w) for w, _ in line) + space * (len(line) - 1)
        x = left + ((right - left) - line_w) / 2
        for word, accent in line:
            dg.text((x + 2, y + 3), word, font=f, fill=(0, 0, 0, 230))
            di.text((x, y), word, font=f, fill=(color if accent else (255, 255, 255)) + (255,))
            x += f.getlength(word) + space
        y += line_h
    glow = glow.filter(ImageFilter.GaussianBlur(max(2, size // 18)))
    base = canvas.convert("RGBA")
    base.alpha_composite(glow)
    base.alpha_composite(ink)
    canvas.paste(base.convert("RGB"))


def handle_at(canvas, handle, color):
    f = font(max(22, canvas.width // 40))
    draw = ImageDraw.Draw(canvas)
    x, y = int(canvas.width * 0.045), int(canvas.width * 0.04)
    draw.text((x + 2, y + 2), handle, font=f, fill=(0, 0, 0))
    draw.text((x, y), handle, font=f, fill=color)


def zones(layout, width, height):
    """Each text field's zone and its starting / smallest type size."""
    if layout == "split":
        return {"top": ((0, 0, width, height // 2), width // 15, width // 30),
                "bottom": ((0, height // 2, width, height), width // 15, width // 30)}
    return {"text": ((0, height // 2, width, height), width // 13, width // 28)}


def plan(spec, base, size):
    """Check every slide before anything is written: layout, fields, image, and that each line fits."""
    width, height = size
    problems, fitted = [], []
    for number, item in enumerate(spec.get("slides") or [], 1):
        layout = str(item.get("layout", "single")).strip().lower()
        if layout not in LAYOUTS:
            problems.append("slide %d: layout must be split or single, got %r" % (number, item.get("layout")))
            fitted.append(None)
            continue
        stray = [k for k in ("top", "bottom", "text") if k in item and k not in LAYOUTS[layout]]
        if stray:
            problems.append("slide %d: a %s slide has no %s field (use %s)" % (number, layout, "/".join(stray), "/".join(LAYOUTS[layout])))
        path = os.path.join(base, str(item.get("image", "")))
        if not os.path.isfile(path):
            problems.append("slide %d: image not found: %s" % (number, path))
        fields = {}
        for key, (zone, start, smallest) in zones(layout, width, height).items():
            text = str(item.get(key, "") or "")
            if not text.strip():
                continue
            if not text.replace("*", "").strip():
                problems.append("slide %d %s: only stars, no words" % (number, key))
                continue
            result = fit(text, int((zone[2] - zone[0]) * 0.86), start, smallest)
            if result is None:
                problems.append("slide %d %s: TOO LONG for two lines: %r (shorten it, or split a long word)" % (number, key, text))
                continue
            fields[key] = (result, zone)
        fitted.append((layout, path, fields))
    if not spec.get("slides"):
        problems.append("post.json lists no slides")
    return problems, fitted


def render(layout, path, fields, size, color, handle):
    width, height = size
    img = Image.open(path).convert("RGB")
    ratio = img.width / img.height
    if abs(ratio - 2 / 3) / (2 / 3) > 0.10:
        print("WARN: %s is %dx%d, not a tall 2:3 picture; the crop may cut the character" % (os.path.basename(path), img.width, img.height))
    canvas = Image.new("RGB", (width, height))
    if layout == "split":
        half = img.height // 2
        trim = max(2, img.height // 100)  # drop any hairline at the cut
        canvas.paste(cover(img.crop((0, 0, img.width, half - trim)), width, height // 2), (0, 0))
        canvas.paste(cover(img.crop((0, half + trim, img.width, img.height)), width, height - height // 2), (0, height // 2))
    else:
        canvas.paste(cover(img, width, height), (0, 0))
    for key in ("top", "bottom", "text"):
        if key in fields:
            words_at(canvas, fields[key][0], fields[key][1], color)
    if handle:
        handle_at(canvas, handle, color)
    return canvas


def post(path):
    path = os.path.abspath(path)
    base = os.path.dirname(path)
    with open(path, encoding="utf-8-sig") as h:  # a BOM from Windows editors is fine
        spec = json.load(h)
    size = tuple(int(n) for n in spec.get("size", [1080, 1440]))
    color = page_colour(spec.get("color", ""))
    problems, fitted = plan(spec, base, size)
    if problems:
        raise Stop("nothing was written:\n  " + "\n  ".join(problems))
    out = os.path.join(base, spec.get("out", "slides"))
    os.makedirs(out, exist_ok=True)
    written = []
    for number, (layout, image, fields) in enumerate(fitted, 1):
        target = os.path.join(out, "slide-%02d.png" % number)
        render(layout, image, fields, size, color, str(spec.get("handle", "") or "")).save(target)
        written.append(target)
        print("wrote", target)
    return written


def colour(image_path, target_hex):
    """Lit colour of the pixels that share the target's hue: the 80th-90th brightness band, as the eye reads a lit surface."""
    target = hex_rgb(target_hex)
    th, ts, tv = colorsys.rgb_to_hsv(*(c / 255 for c in target))
    img = Image.open(image_path).convert("RGB")
    img.thumbnail((400, 400))
    data = img.tobytes()
    near = []
    for i in range(0, len(data), 3):
        r, g, b = data[i], data[i + 1], data[i + 2]
        h, s, v = colorsys.rgb_to_hsv(r / 255, g / 255, b / 255)
        if s > 0.25 and v > 0.2 and min(abs(h - th), 1 - abs(h - th)) < 12 / 360:
            near.append((v, (r, g, b)))
    share = len(near) / max(1, img.width * img.height)
    if share < 0.003:
        print("COLOUR NOT FOUND near %s (%.2f%% of the image): judge the colour by eye; do not generate again for this alone" % (target_hex, share * 100))
        return False
    near.sort()
    low = int(len(near) * 0.8)
    band = near[low:max(int(len(near) * 0.9), low + 1)]
    lit = tuple(round(sum(p[1][i] for p in band) / len(band)) for i in range(3))
    diff = max(abs(lit[i] - target[i]) for i in range(3))
    lh = colorsys.rgb_to_hsv(*(c / 255 for c in lit))[0]
    hue_off = round(min(abs(lh - th), 1 - abs(lh - th)) * 360)
    verdict = "PASS" if diff <= 16 and hue_off <= 8 else "CHECK"
    print("%s: lit colour #%02x%02x%02x vs target %s, largest channel gap %d, hue off by %d degrees, %.1f%% of the image" % (
        verdict, lit[0], lit[1], lit[2], target_hex, diff, hue_off, share * 100))
    return verdict == "PASS"


def font_ok(path, size, is_font):
    """The exact size from the pinned revision, and for the font: it loads and draws Ө and Ү."""
    if not os.path.isfile(path) or os.path.getsize(path) != size:
        return False
    if is_font:
        try:
            f = ImageFont.truetype(path, 40)
            return all(f.getmask(letter).getbbox() for letter in "ӨҮ")
        except Exception:
            return False
    return True


def fetch_font():
    """Montserrat covers Latin and Cyrillic (including Mongolian Ө and Ү); its licence travels with it.
    A file is kept only if it checks out; a partial or wrong file is replaced."""
    import urllib.request
    os.makedirs(FONT_DIR, exist_ok=True)
    for remote, local, size in FONT_FILES:
        target, is_font = os.path.join(FONT_DIR, local), local.endswith(".ttf")
        if font_ok(target, size, is_font):
            print("kept", target)
            continue
        part = target + ".part"
        with urllib.request.urlopen(FONT_SOURCE + remote, timeout=60) as response, open(part, "wb") as h:
            h.write(response.read())
        if not font_ok(part, size, is_font):
            os.remove(part)
            raise Stop("the download of %s did not match the expected file; run fetch-font again" % local)
        os.replace(part, target)
        print("wrote", target, os.path.getsize(target), "bytes")


def selftest(folder):
    os.makedirs(os.path.join(folder, "raw"), exist_ok=True)
    art = Image.new("RGB", (1024, 1536), (60, 60, 70))
    draw = ImageDraw.Draw(art)
    draw.rectangle((0, 0, 1024, 767), fill=(150, 110, 80))
    draw.ellipse((380, 250, 640, 560), fill=(240, 186, 52))
    draw.ellipse((380, 1018, 640, 1328), fill=(240, 186, 52))
    art.save(os.path.join(folder, "raw", "01.png"))
    art.save(os.path.join(folder, "raw", "02.png"))
    spec = {"size": [1080, 1440], "color": "#F0BA34", "handle": "@test.page", "out": "slides",
            "slides": [{"layout": "split", "image": "raw/01.png", "top": "Өглөө бүр *Үүнийг* хий",
                        "bottom": "Өөрийнхөө төлөө *ажилла*"},
                       {"layout": "single", "image": "raw/02.png", "text": "Дагаарай: өдөр бүр *нэг* санаа"}]}
    with open(os.path.join(folder, "post.json"), "w", encoding="utf-8") as h:
        json.dump(spec, h, ensure_ascii=False)
    problems = []
    for _, local, size in FONT_FILES:
        if not font_ok(os.path.join(FONT_DIR, local), size, local.endswith(".ttf")):
            problems.append("%s is missing or damaged (run: compose.py fetch-font)" % local)
    written = post(os.path.join(folder, "post.json"))
    for path in written:
        img = Image.open(path).convert("RGB")
        if img.size != (1080, 1440):
            problems.append("%s is %s, expected 1080x1440" % (os.path.basename(path), img.size))
        data = img.crop((0, 1100, 1080, 1440)).tobytes()
        pixels = [data[i:i + 3] for i in range(0, len(data), 3)]
        white = sum(1 for p in pixels if min(p) > 235)
        gold = sum(1 for p in pixels if abs(p[0] - 240) < 20 and abs(p[1] - 186) < 25 and p[2] < 90)
        if white < 300 or gold < 300:
            problems.append("%s: words not found (white %d, accent %d pixels)" % (os.path.basename(path), white, gold))
    long_spec = dict(spec, slides=[{"layout": "single", "image": "raw/02.png", "text": "үг " * 60}])
    with open(os.path.join(folder, "long.json"), "w", encoding="utf-8") as h:
        json.dump(long_spec, h, ensure_ascii=False)
    try:
        post(os.path.join(folder, "long.json"))
        problems.append("a line too long for two lines was not refused")
    except Stop:
        pass
    if not colour(os.path.join(folder, "raw", "01.png"), "#F0BA34"):
        problems.append("colour check did not pass on a flat swatch")
    print("SELFTEST FAIL: " + "; ".join(problems) if problems else "SELFTEST OK")
    return not problems


def main(argv):
    try:
        if len(argv) >= 2 and argv[0] == "--selftest":
            raise SystemExit(0 if selftest(os.path.abspath(argv[1])) else 1)
        if argv == ["fetch-font"]:
            fetch_font()
            return
        if len(argv) == 2 and argv[0] == "post":
            post(argv[1])
            return
        if len(argv) == 3 and argv[0] == "colour":
            raise SystemExit(0 if colour(argv[1], argv[2]) else 1)
    except Stop as problem:
        print("STOP: %s" % problem)
        raise SystemExit(1)
    raise SystemExit(__doc__)


if __name__ == "__main__":
    main(sys.argv[1:])
~~~~

## tools/requirements.txt

~~~~text
pillow>=10.1
~~~~
