1#!/usr/bin/env bash
2#
3# build.sh: the images for "The Perfect Drug"
4#
5# A poetry-to-image project after the song by Nine Inch Nails (1997): longing, absence and a
6# green hunger, retold as a gothic adult comic in eight movements of three images each. The
7# lyrics are copyrighted and are not reproduced here; the scenes below are original
8# interpretations of the song's mood. Read the words at the source:
9#
10# Lyrics: https://genius.com/Nine-inch-nails-the-perfect-drug-lyrics
11# Model: https://replicate.com/black-forest-labs/flux-3-image
12# Mood: Gothic, absinthe, ruin, purple velvet and green liquor, wolves, night, full moon,
13# blood, subtle horror, dark underworld adult comics
14#
15# Two reference portraits (the Poet and the Green Lady) are generated first and then handed to
16# every shot that features them, so the cast stays consistent across the whole story.
17#
18# Usage: ./build.sh [options] (REPLICATE_API_TOKEN must be set)
19# -p, --part N[,N...] only these movements (1-8)
20# -k, --shot N[,N...] only these shots (1-3)
21# -a, --aspect RATIO aspect ratio of the shots (default 3:2)
22# -r, --resolution RES 768sq, 1k, 1.5k, 2k or 4k (default 1.5k)
23# -j, --jobs N parallel predictions (default 4)
24# -f, --force regenerate shots that already exist
25# --refs regenerate the two reference portraits too (changes the cast)
26# -n, --dry-run print the prompts and payloads, generate nothing
27# -h, --help
28#
29# Output: perfect-drug-<movement>-<shot>.jpg, ref-poet.jpg and ref-lady.jpg next to this file.
30# FLUX 3 has no seed input, so a rerun gives new takes on the same prompts; keep the images you
31# like, they are skipped. Web grounding is switched off so the model invents its own imagery.
32# When all 24 shots exist, the post's `draft` flag is cleared.
33
34set -Eeuo pipefail
35
36HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
37ROSE="${ROSE_PY:-$HERE/../../../rose.py}"
38
39MODEL="black-forest-labs/flux-3-image"
40ASPECT="3:2"
41RESOLUTION="1.5k"
42JOBS=4
43FORMAT="jpg"
44QUALITY=92
45FORCE=0
46REFS=0
47DRY=0
48PART_ONLY=""
49SHOT_ONLY=""
50
51PARTS=8
52SHOTS=3
53
54# ---------------------------------------------------------------------------------------
55# The look and the cast, reused in every prompt
56# ---------------------------------------------------------------------------------------
57TITLE="The Perfect Drug"
58
59STYLE="Dark underground adult graphic novel art, gothic horror comic illustration: heavy black \
60inks, rough crosshatching, scratchy linework over painterly gouache washes, brutal film-noir \
61chiaroscuro, grime and paper grain. Palette of ink black, bruised purple velvet and sickly \
62absinthe green, cold full moonlight, small accents of blood red. Crumbling gothic ruin, \
63decadent and rotten, subtle creeping horror."
64
65NEGATIVE="One single full-bleed illustration: no text, no lettering, no speech balloons, no \
66panels, no borders, no signature, no watermark."
67
68POET="The Poet: a gaunt pale man of about thirty with long lank raven hair, sharp hollow cheeks, \
69a thin scar through his left eyebrow, wearing a frayed purple velvet frock coat with a high \
70collar over an open black shirt."
71
72LADY="The Green Lady: a spectral adult woman born of absinthe vapour, luminous emerald eyes, very \
73long hair drifting like green smoke, ashen skin, a high-necked gown of torn antique lace that \
74dissolves into mist."
75
76# ---------------------------------------------------------------------------------------
77# Eight movements, three shots each. shot <movement> <shot> <cast: -, P, L or PL> <scene>
78# ---------------------------------------------------------------------------------------
79declare -A CAST SCENE
80shot() { CAST["$1-$2"]=$3; SCENE["$1-$2"]=$4; }
81
82# I. The Hollow Hours
83shot 1 1 P "Wide view of a ruined gothic mansion hall at night, roof torn open to a huge full moon, \
84the Poet sits alone and small in a rotting purple velvet armchair among stopped clocks and dead leaves."
85shot 1 2 P "Tight close-up of the Poet's sleepless face lit from one side by moonlight, red-rimmed \
86eyes staring at nothing, cobwebs and shadow behind him."
87shot 1 3 - "Still life on a warped table: stopped pocket watch, guttered candle, an empty cut-crystal \
88absinthe glass with a green dreg, a dead moth, moonlight through broken shutters."
89
90# II. The Green Pour
91shot 2 1 P "The Poet bends over a tarnished silver absinthe fountain in a derelict parlour hung with \
92purple velvet, green light from the liquor underlighting his face."
93shot 2 2 - "Extreme close-up of the absinthe ritual: iced water dripping onto a sugar cube on a \
94slotted silver spoon, green liquor clouding into swirling pale opal in the glass."
95shot 2 3 P "Seen from above, the Poet raises the glowing green glass to his lips, his shadow on the \
96wall stretching into the shape of a wolf."
97
98# III. The Apparition
99shot 3 1 PL "The Green Lady unfurls out of the vapour rising from the glass and towers over the \
100seated Poet in the dark parlour, her smoke hair filling the room."
101shot 3 2 L "Intimate close-up of the Green Lady's face emerging from green mist, emerald eyes wide \
102open, a faint cruel smile, drops of liquor like tears."
103shot 3 3 PL "In profile, the Green Lady's pale fingers hover a hair's breadth from the Poet's cheek \
104while he closes his eyes, moonlight between them."
105
106# IV. The Craving
107shot 4 1 PL "The Poet reaches out with both open hands toward the Green Lady, a clear gap between \
108them and no touching, as she dissolves into green smoke and drifts away out of his reach among torn \
109purple velvet curtains."
110shot 4 2 P "The Poet on his knees on a cracked chequered floor, clawing at the air, mouth open in a \
111silent cry, green vapour slipping through his fingers."
112shot 4 3 - "A hand-shaped print of green frost on a black mirror, a shattered glass below it, spilled \
113absinthe spreading like a living stain toward a thin thread of blood."
114
115# V. The Wolves
116shot 5 1 - "A pack of huge gaunt black wolves with green eyes prowls into a roofless ruined cathedral \
117under an enormous full moon, breath steaming."
118shot 5 2 P "The Poet backs against a broken stone angel as wolves circle him in the moonlit ruin, \
119low dramatic angle, coat torn."
120shot 5 3 - "Extreme close-up of a snarling wolf's muzzle, one glowing green eye, wet fangs, a bead \
121of blood on its fur, moon reflected in the eye."
122
123# VI. The Fracture
124shot 6 1 P "The Poet faces a tall shattered gilt mirror; every shard reflects a different distorted \
125version of him, one of them grinning."
126shot 6 2 PL "In the splintered mirror the Green Lady stands behind the Poet's reflection although \
127the room behind him is empty."
128shot 6 3 - "Close-up of a pale bleeding palm clutching a long mirror shard, one emerald eye reflected \
129in the shard, dark red drops on purple velvet."
130
131# VII. The Barren Night
132shot 7 1 P "The Poet staggers alone through a dead forest of black twisted trees and leaning graves, \
133tiny beneath a colossal full moon, wolves far behind him."
134shot 7 2 P "Close view of the Poet sheltering against a mossy headstone in driving rain, wet hair over \
135his face, looking up at the full moon with quiet longing, a green glass bottle in the grass beside him."
136shot 7 3 L "Far off between the black trees one single Green Lady, only one figure, seen from behind, \
137small and faintly glowing as she walks away into the dark, thorny roots and ground fog in the \
138foreground."
139
140# VIII. The Last Glass
141shot 8 1 PL "In the ruined hall at the end of night the Green Lady cradles the motionless Poet's head \
142in her lap on a heap of purple velvet, sleeping wolves around them, the moon sinking."
143shot 8 2 L "The Green Lady rises alone over the ruin as dawn greys the sky, her form thinning into a \
144vast plume of green smoke, sad and victorious."
145shot 8 3 - "An overturned absinthe glass on the abandoned purple velvet armchair, a last green drop \
146about to fall, wolf paw prints in the dust, pale moon in a broken window."
147
148# ---------------------------------------------------------------------------------------
149# Helpers
150# ---------------------------------------------------------------------------------------
151if [[ -t 2 ]]; then
152 B=$'\033[1m' D=$'\033[2m' R=$'\033[31m' G=$'\033[32m' Y=$'\033[33m' C=$'\033[36m' Z=$'\033[0m'
153else
154 B="" D="" R="" G="" Y="" C="" Z=""
155fi
156say() { printf '%s\n' "$*" >&2; }
157die() { say "${R}error:${Z} $*"; exit 2; }
158usage() { sed -n '/^# Usage:/,/^# -h/p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; }
159squash() { tr -s '[:space:]' ' '; }
160file_of() { printf '%s/perfect-drug-%d-%d' "$HERE" "$1" "$2"; } # movement shot -> path, no extension
161have() { compgen -G "$(file_of "$1" "$2").*" >/dev/null; }
162
163shot_prompt() { # movement shot -> one-line prompt
164 local key="$1-$2" cast who=""
165 cast=${CAST[$key]}
166 case $cast in
167 P) who="The reference image shows the Poet: keep his face, hair and coat, but compose a completely new scene. $POET" ;;
168 L) who="The reference image shows the Green Lady: keep her face, hair and gown, but compose a completely new scene. $LADY" ;;
169 PL) who="The first reference image shows the Poet and the second the Green Lady: keep their faces, hair and clothes, but compose a completely new scene. $POET $LADY" ;;
170 esac
171 printf '"%s", a gothic comic. %s %s %s %s' "$TITLE" "${SCENE[$key]}" "$who" "$STYLE" "$NEGATIVE" | squash
172}
173
174run_rose() { # prompts_file out_dir aspect [reference images...]
175 local prompts=$1 out=$2 aspect=$3 ref
176 shift 3
177 local args=(replicate "$MODEL" --prompts-file "$prompts" --jobs "$JOBS" --timeout 900
178 --aspect-ratio "$aspect" --resolution "$RESOLUTION" --no-grounding
179 --output-format "$FORMAT" --output-quality "$QUALITY" --output-dir "$out" --no-meta)
180 for ref in "$@"; do args+=(--images "$ref"); done
181 ((DRY)) && args+=(--dry-run)
182 python3 "$ROSE" "${args[@]}"
183}
184
185result() { # out_dir index -> the file rose.py saved for that prompt, if any
186 find "$1" -maxdepth 1 -type f -name "*-$(printf '%02d' "$2").*" 2>/dev/null | head -n1 || true
187}
188
189# ---------------------------------------------------------------------------------------
190# Options
191# ---------------------------------------------------------------------------------------
192while (($#)); do
193 case "$1" in
194 -p | --part) PART_ONLY="${2:?--part needs a value}"; shift 2 ;;
195 -k | --shot) SHOT_ONLY="${2:?--shot needs a value}"; shift 2 ;;
196 -a | --aspect) ASPECT="${2:?--aspect needs a value}"; shift 2 ;;
197 -r | --resolution) RESOLUTION="${2:?--resolution needs a value}"; shift 2 ;;
198 -j | --jobs) JOBS="${2:?--jobs needs a value}"; shift 2 ;;
199 -f | --force) FORCE=1; shift ;;
200 --refs) REFS=1; shift ;;
201 -n | --dry-run) DRY=1; shift ;;
202 -h | --help) usage; exit 0 ;;
203 *) die "unknown option: $1 (try --help)" ;;
204 esac
205done
206
207[[ -f "$ROSE" ]] || die "rose.py not found at $ROSE (set ROSE_PY)"
208command -v python3 >/dev/null || die "python3 is required"
209[[ -n "${REPLICATE_API_TOKEN:-}" ]] || die "REPLICATE_API_TOKEN is not set"
210
211if [[ -n "$PART_ONLY" ]]; then
212 IFS=',' read -r -a WANT <<<"$PART_ONLY"
213 for n in "${WANT[@]}"; do [[ "$n" =~ ^[1-8]$ ]] || die "movement must be 1-8, got '$n'"; done
214else
215 WANT=(1 2 3 4 5 6 7 8)
216fi
217if [[ -n "$SHOT_ONLY" ]]; then
218 IFS=',' read -r -a SHOT_WANT <<<"$SHOT_ONLY"
219 for n in "${SHOT_WANT[@]}"; do [[ "$n" =~ ^[1-3]$ ]] || die "shot must be 1-3, got '$n'"; done
220else
221 SHOT_WANT=(1 2 3)
222fi
223
224TMP="$(mktemp -d)"
225trap 'rm -rf "$TMP"' EXIT
226failed=0
227
228say "${B}${TITLE}${Z} ${D}${MODEL} · ${ASPECT} · ${RESOLUTION}${Z}"
229
230# ---------------------------------------------------------------------------------------
231# 1. The cast: two reference portraits
232# ---------------------------------------------------------------------------------------
233REF_POET="$HERE/ref-poet.$FORMAT"
234REF_LADY="$HERE/ref-lady.$FORMAT"
235
236if ((REFS || DRY)) || [[ ! -f "$REF_POET" || ! -f "$REF_LADY" ]]; then
237 say ""
238 say "${C}${B}the cast${Z} ${D}(2 reference portraits)${Z}"
239 : >"$TMP/refs.txt"
240 for who in "$POET" "$LADY"; do
241 printf 'Character reference portrait, half length, facing the viewer, plain dark backdrop. %s %s %s\n' \
242 "$who" "$STYLE" "$NEGATIVE" | squash >>"$TMP/refs.txt"
243 printf '\n' >>"$TMP/refs.txt"
244 done
245 run_rose "$TMP/refs.txt" "$TMP/refs" "2:3" || die "could not generate the reference portraits"
246 if ((!DRY)); then
247 mv -f "$(result "$TMP/refs" 1)" "$REF_POET"
248 mv -f "$(result "$TMP/refs" 2)" "$REF_LADY"
249 say "${G}saved${Z} ref-poet.$FORMAT ref-lady.$FORMAT"
250 fi
251fi
252
253# ---------------------------------------------------------------------------------------
254# 2. The story: one batch per cast, so each batch gets the right reference images
255# ---------------------------------------------------------------------------------------
256for cast in - P L PL; do
257 todo=()
258 for m in "${WANT[@]}"; do
259 for k in "${SHOT_WANT[@]}"; do
260 [[ "${CAST[$m-$k]}" == "$cast" ]] || continue
261 if ((FORCE || DRY)) || ! have "$m" "$k"; then todo+=("$m $k"); fi
262 done
263 done
264 ((${#todo[@]})) || continue
265
266 case $cast in
267 -) label="no cast" refs=() ;;
268 P) label="the Poet" refs=("$REF_POET") ;;
269 L) label="the Green Lady" refs=("$REF_LADY") ;;
270 PL) label="the Poet and the Green Lady" refs=("$REF_POET" "$REF_LADY") ;;
271 esac
272 # a dry run before the portraits exist cannot attach them
273 if ((DRY)) && [[ ! -f "$REF_POET" || ! -f "$REF_LADY" ]]; then refs=(); fi
274
275 say ""
276 say "${C}${B}${label}${Z} ${D}(${#todo[@]} shot(s))${Z}"
277 prompts="$TMP/cast-$cast.txt"
278 : >"$prompts"
279 for item in "${todo[@]}"; do
280 read -r m k <<<"$item"
281 shot_prompt "$m" "$k" >>"$prompts"
282 printf '\n' >>"$prompts"
283 done
284
285 if ! run_rose "$prompts" "$TMP/out-$cast" "$ASPECT" ${refs[@]+"${refs[@]}"}; then
286 say "${Y}some shots failed, rerun to retry them${Z}"
287 failed=1
288 fi
289 ((DRY)) && continue
290
291 i=0
292 for item in "${todo[@]}"; do
293 i=$((i + 1))
294 read -r m k <<<"$item"
295 src="$(result "$TMP/out-$cast" "$i")"
296 [[ -n "$src" ]] || continue
297 mv -f "$src" "$(file_of "$m" "$k").${src##*.}"
298 say "${G}saved${Z} perfect-drug-$m-$k.${src##*.}"
299 done
300done
301
302# ---------------------------------------------------------------------------------------
303# Publish the post once everything exists
304# ---------------------------------------------------------------------------------------
305if ((!DRY)); then
306 missing=0
307 for ((m = 1; m <= PARTS; m++)); do
308 for ((k = 1; k <= SHOTS; k++)); do have "$m" "$k" || missing=$((missing + 1)); done
309 done
310 if ((missing)); then
311 say ""
312 say "${Y}${missing} shot(s) still missing.${Z}"
313 elif [[ -f "$HERE/index.md" ]] && grep -q '^draft: true$' "$HERE/index.md"; then
314 sed -i 's/^draft: true$/draft: false/' "$HERE/index.md"
315 say ""
316 say "${G}All $((PARTS * SHOTS)) shots exist: draft flag cleared in index.md.${Z}"
317 fi
318fi
319
320exit "$failed"