1#!/usr/bin/env bash
2#
3# build.sh: the images for "White Rabbit"
4#
5# A poetry-to-image project after the song by Jefferson Airplane (written by Grace Slick, 1967),
6# which borrows its dream logic from Lewis Carroll's Wonderland. Here it becomes an overexcited,
7# psychedelic, funky cartoon in eight movements of three images each. The lyrics are copyrighted
8# and are not reproduced here; the scenes below are original interpretations. All characters are
9# original designs, and the heroine is a grown woman. Read the words at the source:
10#
11# Lyrics: https://genius.com/Jefferson-airplane-white-rabbit-lyrics
12# Model: https://replicate.com/black-forest-labs/flux-3-image
13# Look: classic slapstick animation crossed with flat cut-out adult sitcom cartoons,
14# 1960s psychedelic poster colours, high definition
15#
16# Two reference portraits (Alice and the White Rabbit) are generated first and then handed to
17# every shot that features them, so the cast stays consistent across the whole trip.
18#
19# Usage: ./build.sh [options] (REPLICATE_API_TOKEN must be set)
20# -p, --part N[,N...] only these movements (1-8)
21# -k, --shot N[,N...] only these shots (1-3)
22# -a, --aspect RATIO aspect ratio of the shots (default 3:2)
23# -r, --resolution RES 768sq, 1k, 1.5k, 2k or 4k (default 1.5k)
24# -j, --jobs N parallel predictions (default 4)
25# -f, --force regenerate shots that already exist
26# --refs regenerate the two reference portraits too (changes the cast)
27# -n, --dry-run print the prompts and payloads, generate nothing
28# -h, --help
29#
30# Output: white-rabbit-<movement>-<shot>.jpg, ref-alice.jpg and ref-rabbit.jpg next to this file.
31# FLUX 3 has no seed input, so a rerun gives new takes on the same prompts; keep the images you
32# like, they are skipped. Web grounding is switched off so the model invents its own imagery.
33# When all 24 shots exist, the post's `draft` flag is cleared.
34
35set -Eeuo pipefail
36
37HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
38ROSE="${ROSE_PY:-$HERE/../../../rose.py}"
39
40MODEL="black-forest-labs/flux-3-image"
41ASPECT="3:2"
42RESOLUTION="1.5k"
43JOBS=4
44FORMAT="jpg"
45QUALITY=92
46FORCE=0
47REFS=0
48DRY=0
49PART_ONLY=""
50SHOT_ONLY=""
51
52PARTS=8
53SHOTS=3
54
55# ---------------------------------------------------------------------------------------
56# The look and the cast, reused in every prompt
57# ---------------------------------------------------------------------------------------
58TITLE="White Rabbit"
59
60STYLE="Super colourful, wildly overexcited psychedelic funky cartoon in crisp high definition: \
61the elastic squash-and-stretch slapstick of classic golden-age theatrical animation crossed with \
62the flat construction-paper cut-out look of crude adult animated sitcoms. Thick wobbly black \
63outlines, flat saturated shapes, huge googly eyes, smear frames, speed lines, impact stars and \
64exploding confetti. 1960s psychedelic poster palette of hot magenta, acid lime, electric blue, \
65tangerine and sunflower yellow, melting swirls and op-art rainbow spirals in the background."
66
67NEGATIVE="Entirely original characters, no existing cartoon or film characters. One single \
68full-bleed illustration: no text, no lettering, no speech balloons, no panels, no borders, no \
69signature, no watermark."
70
71ALICE="Alice: a tall grown woman in her late twenties with adult proportions, wild tangerine hair \
72in two big bouncy buns, enormous excited eyes, a turquoise mini-length pinafore dress with yellow \
73polka dots over a pink blouse, purple tights and chunky red platform boots."
74
75RABBIT="The White Rabbit: a lanky frantic white rabbit with extremely long floppy ears, bulging \
76pink eyes, two big buck teeth, a lime-green checked waistcoat, an orange bow tie and a giant \
77golden pocket watch on a chain."
78
79# ---------------------------------------------------------------------------------------
80# Eight movements, three shots each. shot <movement> <shot> <cast: -, A, R or AR> <scene>
81# ---------------------------------------------------------------------------------------
82declare -A CAST SCENE
83shot() { CAST["$1-$2"]=$3; SCENE["$1-$2"]=$4; }
84
85# Recurring supporting characters, described the same way every time they appear
86QUEEN="a tiny furious Red Queen with a gigantic head, a bright crimson gown covered in hearts and \
87a small golden crown"
88KNIGHT="a clumsy old White Knight with a droopy white moustache in dented shiny white-silver plate \
89armour"
90
91# I. Down the Hole
92shot 1 1 AR "The White Rabbit dives headfirst into a swirling rainbow rabbit hole in a candy-coloured \
93meadow while Alice sprints after him, legs spinning in a blur."
94shot 1 2 A "Alice tumbles in slow-motion freefall down an endless psychedelic tunnel full of floating \
95teacups, armchairs, alarm clocks and playing cards, arms flailing, grinning."
96shot 1 3 - "A tiny golden key and a sparkling swirl-patterned potion bottle bounce on a three-legged \
97glass table at the bottom of a spiral-striped hall full of doors of every size."
98
99# II. Bigger and Smaller
100shot 2 1 A "Giant Alice has grown so huge that her arms and boots burst out of the windows and roof of \
101a tiny crooked cottage, bricks flying, eyes popping with surprise."
102shot 2 2 A "Tiny Alice, no bigger than a sugar cube, rides a spoon like a surfboard across a giant \
103cup of rainbow tea splashing in great waves."
104shot 2 3 - "A table crowded with wobbling sparkly candies, swirl lollipops and fizzing potion bottles, \
105each one stretching and shrinking the furniture around it in rubbery distortion. Only objects, no \
106animals and no people."
107
108# III. The Rabbit's Rush
109shot 3 1 R "The White Rabbit gapes at his enormous pocket watch in comic panic, hopping a metre off \
110the ground, eyes wide, ears shooting straight up with cheerful puffs of cartoon steam."
111shot 3 2 AR "A frantic chase through a forest of giant lollipop trees: the White Rabbit zooms ahead \
112leaving a rainbow smoke trail while Alice skids around a corner behind him."
113shot 3 3 R "The White Rabbit runs on top of a gigantic melting clock face as the numbers fly off in \
114all directions."
115
116# IV. The Caterpillar
117shot 4 1 A "Alice stares up at a plump purple-and-lime caterpillar lounging on a huge spotted \
118mushroom, who blows enormous shimmering soap bubbles from a curly golden bubble pipe."
119shot 4 2 - "Extreme close-up of the smug caterpillar with half-closed eyes and a tiny pair of round \
120tinted spectacles, rainbow soap bubbles floating all around his many wiggling feet."
121shot 4 3 A "Alice floats inside a gigantic soap bubble drifting over a landscape of glowing \
122polka-dot mushrooms and swirling hills."
123
124# V. The Chessboard
125shot 5 1 A "Alice stands on a vast warped chessboard stretching into a swirling sky while huge living \
126chess pieces with cartoon faces all point and shout orders at her."
127shot 5 2 - "Living chess pieces stampede across a bending checkered landscape, a bishop bouncing like \
128a spring and a wooden chess knight horse whinnying with spiral eyes. Only chess pieces, no rabbits."
129shot 5 3 A "Alice cartwheels over the chessboard squares as they flip and ripple like a rainbow wave."
130
131# VI. The Red Queen
132shot 6 1 A "$QUEEN screams at Alice so hard that her tonsils wobble and the blast blows Alice's hair \
133straight back. Only the Queen and Alice, no rabbits."
134shot 6 2 - "An army of googly-eyed playing cards with stick legs tumbles in a giant house-of-cards \
135avalanche around an empty throne shaped like a heart. Only playing cards and the empty throne, no \
136animals."
137shot 6 3 AR "The White Rabbit blows a long curly trumpet while Alice sticks her tongue out and runs \
138past a croquet lawn where a pink flamingo mallet goes flying."
139
140# VII. The White Knight
141shot 7 1 A "$KNIGHT rides his horse backwards, talking nonsense, while Alice walks beside him looking \
142baffled and amused."
143shot 7 2 - "$KNIGHT tumbles upside down off his bouncing horse in a burst of pots, pans, springs and \
144stars. Only the knight and the horse, no rabbits."
145shot 7 3 A "Alice and $KNIGHT, upside down, hang from a tree whose branches are twisting rainbow ribbons, \
146the sky spinning behind them. Only Alice and the knight, no rabbits."
147
148# VIII. The Dormouse Crescendo
149shot 8 1 - "A sleepy round dormouse suddenly leaps out of a giant teapot at a chaotic tea party, \
150shouting with all its might, the table and crockery blasting into the air."
151shot 8 2 A "Alice sits on a hill looking up in joyful wonder as a giant fountain of flying books, \
152planets, stars, flowers and rainbows swirls into the sky above her."
153shot 8 3 AR "Grand finale: Alice and the White Rabbit dance on top of a giant mushroom while all of \
154Wonderland explodes into fireworks, spirals and confetti around them."
155
156# ---------------------------------------------------------------------------------------
157# Helpers
158# ---------------------------------------------------------------------------------------
159if [[ -t 2 ]]; then
160 B=$'\033[1m' D=$'\033[2m' R=$'\033[31m' G=$'\033[32m' Y=$'\033[33m' C=$'\033[36m' Z=$'\033[0m'
161else
162 B="" D="" R="" G="" Y="" C="" Z=""
163fi
164say() { printf '%s\n' "$*" >&2; }
165die() { say "${R}error:${Z} $*"; exit 2; }
166usage() { sed -n '/^# Usage:/,/^# -h/p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; }
167squash() { tr -s '[:space:]' ' '; }
168file_of() { printf '%s/white-rabbit-%d-%d' "$HERE" "$1" "$2"; } # movement shot -> path, no extension
169have() { compgen -G "$(file_of "$1" "$2").*" >/dev/null; }
170
171shot_prompt() { # movement shot -> one-line prompt
172 local key="$1-$2" cast who="" lead="A psychedelic cartoon."
173 cast=${CAST[$key]}
174 # naming the song in a prompt summons a rabbit, so only shots that want one get the title
175 [[ $cast == *R* ]] && lead="\"$TITLE\", a psychedelic cartoon."
176 case $cast in
177 A) who="The reference image shows Alice: keep her face, hair and outfit, but compose a completely new scene. $ALICE" ;;
178 R) who="The reference image shows the White Rabbit: keep his face and clothes, but compose a completely new scene. $RABBIT" ;;
179 AR) who="The first reference image shows Alice and the second the White Rabbit: keep their faces and outfits, but compose a completely new scene. $ALICE $RABBIT" ;;
180 esac
181 printf '%s %s %s %s %s' "$lead" "${SCENE[$key]}" "$who" "$STYLE" "$NEGATIVE" | squash
182}
183
184run_rose() { # prompts_file out_dir aspect [reference images...]
185 local prompts=$1 out=$2 aspect=$3 ref
186 shift 3
187 local args=(replicate "$MODEL" --prompts-file "$prompts" --jobs "$JOBS" --timeout 900
188 --aspect-ratio "$aspect" --resolution "$RESOLUTION" --no-grounding
189 --output-format "$FORMAT" --output-quality "$QUALITY" --output-dir "$out" --no-meta)
190 for ref in "$@"; do args+=(--images "$ref"); done
191 ((DRY)) && args+=(--dry-run)
192 python3 "$ROSE" "${args[@]}"
193}
194
195result() { # out_dir index -> the file rose.py saved for that prompt, if any
196 find "$1" -maxdepth 1 -type f -name "*-$(printf '%02d' "$2").*" 2>/dev/null | head -n1 || true
197}
198
199# ---------------------------------------------------------------------------------------
200# Options
201# ---------------------------------------------------------------------------------------
202while (($#)); do
203 case "$1" in
204 -p | --part) PART_ONLY="${2:?--part needs a value}"; shift 2 ;;
205 -k | --shot) SHOT_ONLY="${2:?--shot needs a value}"; shift 2 ;;
206 -a | --aspect) ASPECT="${2:?--aspect needs a value}"; shift 2 ;;
207 -r | --resolution) RESOLUTION="${2:?--resolution needs a value}"; shift 2 ;;
208 -j | --jobs) JOBS="${2:?--jobs needs a value}"; shift 2 ;;
209 -f | --force) FORCE=1; shift ;;
210 --refs) REFS=1; shift ;;
211 -n | --dry-run) DRY=1; shift ;;
212 -h | --help) usage; exit 0 ;;
213 *) die "unknown option: $1 (try --help)" ;;
214 esac
215done
216
217[[ -f "$ROSE" ]] || die "rose.py not found at $ROSE (set ROSE_PY)"
218command -v python3 >/dev/null || die "python3 is required"
219[[ -n "${REPLICATE_API_TOKEN:-}" ]] || die "REPLICATE_API_TOKEN is not set"
220
221if [[ -n "$PART_ONLY" ]]; then
222 IFS=',' read -r -a WANT <<<"$PART_ONLY"
223 for n in "${WANT[@]}"; do [[ "$n" =~ ^[1-8]$ ]] || die "movement must be 1-8, got '$n'"; done
224else
225 WANT=(1 2 3 4 5 6 7 8)
226fi
227if [[ -n "$SHOT_ONLY" ]]; then
228 IFS=',' read -r -a SHOT_WANT <<<"$SHOT_ONLY"
229 for n in "${SHOT_WANT[@]}"; do [[ "$n" =~ ^[1-3]$ ]] || die "shot must be 1-3, got '$n'"; done
230else
231 SHOT_WANT=(1 2 3)
232fi
233
234TMP="$(mktemp -d)"
235trap 'rm -rf "$TMP"' EXIT
236failed=0
237
238say "${B}${TITLE}${Z} ${D}${MODEL} · ${ASPECT} · ${RESOLUTION}${Z}"
239
240# ---------------------------------------------------------------------------------------
241# 1. The cast: two reference portraits
242# ---------------------------------------------------------------------------------------
243REF_ALICE="$HERE/ref-alice.$FORMAT"
244REF_RABBIT="$HERE/ref-rabbit.$FORMAT"
245
246if ((REFS || DRY)) || [[ ! -f "$REF_ALICE" || ! -f "$REF_RABBIT" ]]; then
247 say ""
248 say "${C}${B}the cast${Z} ${D}(2 reference portraits)${Z}"
249 : >"$TMP/refs.txt"
250 for who in "$ALICE" "$RABBIT"; do
251 printf 'Cartoon character reference portrait, full body, facing the viewer, simple swirl backdrop. %s %s %s\n' \
252 "$who" "$STYLE" "$NEGATIVE" | squash >>"$TMP/refs.txt"
253 printf '\n' >>"$TMP/refs.txt"
254 done
255 run_rose "$TMP/refs.txt" "$TMP/refs" "2:3" || die "could not generate the reference portraits"
256 if ((!DRY)); then
257 mv -f "$(result "$TMP/refs" 1)" "$REF_ALICE"
258 mv -f "$(result "$TMP/refs" 2)" "$REF_RABBIT"
259 say "${G}saved${Z} ref-alice.$FORMAT ref-rabbit.$FORMAT"
260 fi
261fi
262
263# ---------------------------------------------------------------------------------------
264# 2. The story: one batch per cast, so each batch gets the right reference images
265# ---------------------------------------------------------------------------------------
266for cast in - A R AR; do
267 todo=()
268 for m in "${WANT[@]}"; do
269 for k in "${SHOT_WANT[@]}"; do
270 [[ "${CAST[$m-$k]}" == "$cast" ]] || continue
271 if ((FORCE || DRY)) || ! have "$m" "$k"; then todo+=("$m $k"); fi
272 done
273 done
274 ((${#todo[@]})) || continue
275
276 case $cast in
277 -) label="no cast" refs=() ;;
278 A) label="Alice" refs=("$REF_ALICE") ;;
279 R) label="the White Rabbit" refs=("$REF_RABBIT") ;;
280 AR) label="Alice and the White Rabbit" refs=("$REF_ALICE" "$REF_RABBIT") ;;
281 esac
282 # a dry run before the portraits exist cannot attach them
283 if ((DRY)) && [[ ! -f "$REF_ALICE" || ! -f "$REF_RABBIT" ]]; then refs=(); fi
284
285 say ""
286 say "${C}${B}${label}${Z} ${D}(${#todo[@]} shot(s))${Z}"
287 prompts="$TMP/cast-$cast.txt"
288 : >"$prompts"
289 for item in "${todo[@]}"; do
290 read -r m k <<<"$item"
291 shot_prompt "$m" "$k" >>"$prompts"
292 printf '\n' >>"$prompts"
293 done
294
295 if ! run_rose "$prompts" "$TMP/out-$cast" "$ASPECT" ${refs[@]+"${refs[@]}"}; then
296 say "${Y}some shots failed, rerun to retry them${Z}"
297 failed=1
298 fi
299 ((DRY)) && continue
300
301 i=0
302 for item in "${todo[@]}"; do
303 i=$((i + 1))
304 read -r m k <<<"$item"
305 src="$(result "$TMP/out-$cast" "$i")"
306 [[ -n "$src" ]] || continue
307 mv -f "$src" "$(file_of "$m" "$k").${src##*.}"
308 say "${G}saved${Z} white-rabbit-$m-$k.${src##*.}"
309 done
310done
311
312# ---------------------------------------------------------------------------------------
313# Publish the post once everything exists
314# ---------------------------------------------------------------------------------------
315if ((!DRY)); then
316 missing=0
317 for ((m = 1; m <= PARTS; m++)); do
318 for ((k = 1; k <= SHOTS; k++)); do have "$m" "$k" || missing=$((missing + 1)); done
319 done
320 if ((missing)); then
321 say ""
322 say "${Y}${missing} shot(s) still missing.${Z}"
323 elif [[ -f "$HERE/index.md" ]] && grep -q '^draft: true$' "$HERE/index.md"; then
324 sed -i 's/^draft: true$/draft: false/' "$HERE/index.md"
325 say ""
326 say "${G}All $((PARTS * SHOTS)) shots exist: draft flag cleared in index.md.${Z}"
327 fi
328fi
329
330exit "$failed"