---
name: whiteboard-doodle-ad
description: "A classic whiteboard explainer: a real hand sketches every doodle stroke by stroke as the voiceover tells your story, from pain to solution to CTA. Just paste your website, or send your own script."
---

# Whiteboard Doodle Ad (images-first, code-animated)

Makes one VideoScribe-style whiteboard ad: a real hand with a marker draws every doodle stroke by stroke, never stopping, synced to the voiceover. No AI video model is used. Arcads makes the images, voice, music and SFX, and `wb.py` (below) does the animation and the mix.

Proven pipeline: the SilverShield Health demo (senior health insurance), approved by Damien.

## Rules
- Deliver exactly ONE final video. Never regenerate anything automatically, and never analyze, transcribe or rate the final video: Damien gives the feedback.
- The only approval stop is the script. After that, run to the end without asking.
- Create one Arcads project per run (`arcads_create_project`) and pass `projectId` + `productId` to every generation. If the brand doesn't exist, create it with `arcads_create_brand`.
- Download Arcads files with `arcads_get_asset` (use `waitSeconds`), then `curl` its `downloadUrl`. Work in `~/wbad/<brand>/` with `img/`, `audio/` and `prep/` subfolders.

## Step 0: Intake (strict order, one question at a time, in plain text)
1. **Always ask for the company website URL first.** Don't use a multiple-choice question for it; just ask "What's the company's website URL?" and wait.
2. **Then scrape the site** (Step 1) and ask about the script. Offer two choices: "Here's a script I suggest: …" (show the full suggested script + beats), or "Send me the client's script instead".
3. Only after the script is settled: voice. Default to the last voice Damien used (Finn, `5h1dyTzF2QlF4g0L9HR8`) unless he names another. Language is English unless told otherwise.
4. Format is 9:16 and about 20–30s unless told otherwise. Infer the target audience from the site; don't ask.

## Step 1: Script
- **Website:** scrape it with `firecrawl_scrape` (markdown). Pull out the product, audience, main pain point, 3 concrete benefits, the signup/CTA mechanic and the brand name.
- Write 55–75 words (about 20–25s of voice) in short punchy sentences, one idea per sentence, because each sentence becomes one doodle. Structure:
  1. **Hook:** a question or call-out to the audience (≤6 words).
  2. **Curiosity line:** e.g. "Here's what nobody tells you."
  3. **Pain escalation:** 3 quick beats ("One X. Then Y. Then Z.").
  4. **Consequence:** one line.
  5. **The switch:** "That's why … are switching to BRAND."
  6. **3 benefits:** 2–4 words each.
  7. **CTA:** an easy action plus a time or effort claim.
  8. **Brand name + tagline.**
  - Avoid unverifiable stats ("thousands of…") unless they're on the site.
- **Client script:** use it verbatim. Only split it into beats.
- Show the suggested script plus the planned 10–12 doodle beats (one line each). Damien either approves it or sends the client script. This is the only approval.

## Step 2: Voice
- `arcads_text_to_speech` with the approved script and voice. Download it as `audio/vo.wav`.
- `arcads_transcribe` on it with `mediaType:'audio'` and `format:'srt'`, to get when each beat starts.
- Map each beat to the start time (`vo_start`) of its first word. Each beat must last ≥1.0s; otherwise merge it with a neighbor. Aim for 10–12 scenes, and make the last scene the end card (brand + tagline), starting on the brand name.

## Step 3: Images (Nano Banana 2.1, 9:16, 2K)
Style block, used verbatim in every doodle prompt:
> Whiteboard doodle illustration on a pure flat white background (#FFFFFF), no whiteboard edges, no marker, no hand, no shadows, no paper texture. Thick confident black marker line art in a simple friendly cartoon style like a VideoScribe explainer video, with flat fills only in marker blue (#2B6CE6) and marker red (#E53935), no gradients, no shading, no grey. Centered composition with a generous white margin all around.

(Swap the blue for the brand's main color if it has one; keep red for pain.)

1. Generate scene 1 first: style block + subject + `Hand-lettered black text at the top: "<2–5 WORDS>"`.
2. Then all the other scenes in parallel, each with `referenceImages:[scene1 asset id]` and the prompt starting "Same exact whiteboard doodle style as the reference image: pure flat white background, thick black marker line art, flat fills only in the same marker blue and marker red, no gradients, no shading, no grey, generous white margin, same hand-lettered font." followed by the subject and title text.
   - Pain scenes: visual metaphors (red price tags "$", "$$", "$$$", a stack of bills cracking a piggy bank, a worried face plus a big red "?").
   - Benefit scenes: a big brand-color check mark.
   - End card: a logo-like shield/icon in the brand color + the brand name + the tagline.
3. **Hand:** reuse `hand_marker_cutout_v1` (asset `c1742878-7b3e-4be8-b262-34cdf489ed0a`) if `arcads_get_asset` returns it. Otherwise generate it with this prompt: "Photorealistic studio photo of a single adult human right hand holding a black whiteboard marker like a pen, ready to write. Seen from above, the hand and forearm enter from the bottom-right corner of the frame, and the marker tip points toward the upper-left; the marker tip is the top-left-most point of the subject. Natural skin, short clean nails, a plain light grey shirt cuff at the wrist. Isolated on a pure flat solid white background, soft even lighting, no shadow, no surface, no text." (1:1, 2K). Then run `arcads_remove_background` with `mediaType:'image'` and save it as `img/hand.png` (RGBA). `wb.py` finds the marker tip automatically.
4. **Text check:** make a contact sheet of all doodles and look at it. Then crop each title at full size and check it letter by letter. Nano Banana sometimes smudges one letter.
   - Fix it once with an edit (`referenceImages:[that image]`, "Redraw the title so it reads exactly "…" in the same font, same size and position; keep everything else identical").
   - If the edit is still smudged, patch it with PIL: the edit keeps the same letter positions, so paste the clean letter columns from the other version. Never ship a smudged letter.

## Step 4: Music
`arcads_create_music` (elevenlabs) with `duration` = ceil(vo_offset 0.4 + VO length + tail 1.4). Default prompt: "Upbeat, playful, bouncy explainer-video music: bright ukulele strumming, hand claps, glockenspiel accents, light kick and snare, 118 BPM, major key, warm and optimistic, leaves room for a voiceover". Adapt the mood to the brand.

## Step 5: Sound FX (`arcads_create_sound_effect`, in parallel)
- `scribble`: "Fast squeaky dry-erase marker scribbling quickly on a whiteboard, continuous energetic drawing strokes, close mic" (6s, loop)
- `whoosh`: "Short fast airy whoosh swipe, left to right, clean, for a quick camera pan transition" (0.7s)
- `pop`: "Single bright playful cartoon pop, short and punchy, like a bubble pop UI sound" (0.5s)
- `chime`: "Cheerful bright chime sparkle ding, positive success sound, short" (1.2s)
- `kaching`: "Cash register ka-ching, short, comedic" (1s). Only if there are price/cost scenes.

## Step 6: Animate
1. Write `wb.py` (below) into the work folder.
2. Write `plan.json`: scenes in order, each with `img`, `vo_start` (seconds into the VO) and an optional `extra` list. Use `["kaching"]` on price-tag scenes and `["chime"]` on the solution/brand reveal and the end card. Set `"out":"/mnt/user-data/outputs/<brand>_whiteboard_ad.mp4"`.
3. `python3 wb.py prep plan.json`, then `python3 wb.py test plan.json`. Look at `test/test_frames.jpg` (frames mid-drawing) to check the hand is on the stroke and the reveal looks right.
4. `nohup python3 wb.py all plan.json > log.txt 2>&1 &`, then poll `log.txt` with `sleep` until it prints `final`. A ~24s ad takes about 2.5 min.
5. `SendUserFile` the output with a one-line caption. Also give the Arcads project link and the credits spent (voice + music + SFX, roughly 40 credits).

### What the engine does
- Line art is skeletonized and traced stroke by stroke (DFS), and every ink pixel is revealed when its nearest skeleton point is reached. Then the color fills are scribbled in zig-zag bands.
- The hand follows the exact pen position and wobbles slightly.
- Each scene starts 0.2s before its words with a motion-blurred whip-slide (alternating left/up), has a slow 5% push-in, and draws for up to 82% of its time (max 2.6s), so it is always drawing.
- On the end card the hand exits, then a slow zoom.

### Audio mix (levels Damien approved; keep them)
- Voice is on top.
- Music 0.08 under the voice, rising to 0.30 after the voice ends, with a fade-out.
- SFX: scribble 0.09, pop 0.16, whoosh 0.18, ka-ching 0.12, chime 0.18.
- Final pass: compressor + loudnorm at -14 LUFS.
- To change only the sound later, edit `LEVELS` and run `python3 wb.py mix plan.json` then `final`. The video isn't re-rendered.

### Changes after feedback
- **One doodle:** fix its image, then `prep`, re-render that scene and the next one with `python3 wb.py render plan.json K,K+1` (the next one holds the transition out of the changed scene), then `mix` and `final`.
- **New voice or script:** redo Steps 2 and 6.

## wb.py
```python
#!/usr/bin/env python3
"""Whiteboard draw-on ad engine.
usage: python3 wb.py <cmd> plan.json [scenes]   cmd = prep | test | render | mix | final | all   (render 3,4 = only those scenes)
plan.json:
{ "size":[1080,1920], "fps":30, "vo":"audio/vo.wav", "vo_offset":0.4, "tail":1.4,
  "hand":"img/hand.png", "music":"audio/music.wav",
  "sfx":{"scribble":"audio/scribble.wav","whoosh":"audio/whoosh.wav","pop":"audio/pop.wav",
         "chime":"audio/chime.wav","kaching":"audio/kaching.wav"},
  "scenes":[{"img":"img/01.png","vo_start":0.12,"extra":["kaching"]}, ...],
  "out":"/mnt/user-data/outputs/ad.mp4" }
"""
import sys, os, json, subprocess, numpy as np, cv2
from PIL import Image
from scipy import ndimage as ndi
from scipy.io import wavfile
from skimage.morphology import skeletonize

P = json.load(open(sys.argv[2]))
W, H = P.get('size', [1080, 1920]); FPS = P.get('fps', 30)
SR = 44100; TR = 0.2
N8 = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]
SC = P['scenes']; N = len(SC)

def wav(path):
    sr, a = wavfile.read(path)
    if a.dtype == np.int16: a = a.astype(np.float32) / 32768
    elif a.dtype == np.int32: a = a.astype(np.float32) / 2147483648
    else: a = a.astype(np.float32)
    if a.ndim == 1: a = np.stack([a, a], 1)
    if sr != SR:
        idx = np.linspace(0, len(a) - 1, int(len(a) * SR / sr)); a = np.stack([np.interp(idx, np.arange(len(a)), a[:, c]) for c in (0, 1)], 1).astype(np.float32)
    return a[:, :2]

VO_OFF = P.get('vo_offset', 0.4)
VO_LEN = len(wav(P['vo'])) / SR
END = VO_OFF + VO_LEN + P.get('tail', 1.4)
T = [0.0] + [s['vo_start'] + VO_OFF - TR for s in SC[1:]] + [END]

# ---------------- prep: draw order ----------------
def load_img(path):
    im = Image.open(path).convert('RGB'); s = max(W / im.width, H / im.height)
    im = im.resize((round(im.width * s), round(im.height * s)), Image.LANCZOS)
    x0, y0 = (im.width - W) // 2, (im.height - H) // 2
    return np.asarray(im.crop((x0, y0, x0 + W, y0 + H))).astype(np.uint8)

def dfs(skel, start, vis):
    out, st = [], [start]
    while st:
        y, x = st.pop()
        if vis[y, x]: continue
        vis[y, x] = True; out.append((y, x))
        for dy, dx in N8:
            ny, nx = y + dy, x + dx
            if 0 <= ny < H and 0 <= nx < W and skel[ny, nx] and not vis[ny, nx]: st.append((ny, nx))
    return out

def greedy(labels, n, start):
    objs = ndi.find_objects(labels); pts = []
    for i in range(1, n + 1):
        sl = objs[i - 1]; ys, xs = np.nonzero(labels[sl] == i)
        pts.append(np.stack([ys + sl[0].start, xs + sl[1].start], 1))
    cent = np.array([p.mean(0) for p in pts]) if pts else np.zeros((0, 2))
    rem, cur, order = set(range(n)), np.array(start), []
    while rem:
        r = np.array(sorted(rem)); cand = r[np.argsort(((cent[r] - cur) ** 2).sum(1))[:6]]; best = None
        for c in cand:
            d = ((pts[c] - cur) ** 2).sum(1); j = d.argmin()
            if best is None or d[j] < best[0]: best = (d[j], c, tuple(pts[c][j]))
        _, c, e = best; order.append((e, pts[c])); rem.discard(c); cur = pts[c][-1]
    return order

def prep_one(path, out):
    img = load_img(path); f = img.astype(np.int16)
    mx, mn, lum = f.max(2), f.min(2), f.mean(2)
    ink = mn < 232; color = ink & ((mx - mn) > 70) & (lum > 60)
    skel = skeletonize(ndi.binary_closing(lum < 120, iterations=1))
    lab, n = ndi.label(skel, structure=np.ones((3, 3))); vis = np.zeros_like(skel); path = []
    for e, _ in greedy(lab, n, (0, 0)): path += dfs(skel, e, vis)
    path = np.array(path, np.int32).reshape(-1, 2)
    sr = np.full((H, W), -1, np.int32); sr[path[:, 0], path[:, 1]] = np.arange(len(path))
    _, (iy, ix) = ndi.distance_transform_edt(sr < 0, return_indices=True)
    rd = sr[iy, ix].astype(np.float32) / max(len(path) - 1, 1)
    clab, cn = ndi.label(color, structure=np.ones((3, 3))); fp = []
    for e, pts in greedy(clab, cn, tuple(path[-1]) if len(path) else (0, 0)):
        ys, xs = pts[:, 0], pts[:, 1]; band = (ys - ys.min()) // 28
        fp.append(pts[np.argsort(band * 4096 + np.where(band % 2 == 0, xs, 4095 - xs), kind='stable')])
    fp = np.concatenate(fp) if fp else np.zeros((0, 2), np.int32)
    rank = np.full((H, W), 9.0, np.float32); m = ink & ~color; rank[m] = rd[m] * 0.68
    if len(fp): rank[fp[:, 0], fp[:, 1]] = 0.70 + 0.30 * np.arange(len(fp)) / max(len(fp) - 1, 1)
    K = 2000; hp = np.zeros((K, 2), np.float32)
    for k in range(K):
        p = k / (K - 1)
        if p <= 0.68 or not len(fp): hp[k] = path[int(min(p / 0.68, 1) * (len(path) - 1))][::-1]
        elif p < 0.70: hp[k] = fp[0][::-1]
        else: hp[k] = fp[int((p - 0.70) / 0.30 * (len(fp) - 1))][::-1]
    np.savez_compressed(out, img=img, rank=rank, hand=hp); print('prep', out, len(path), len(fp))

# ---------------- render ----------------
HS = W / 2160  # hand scale (2048px source -> ~half frame width)
def hand_assets():
    h = Image.open(P['hand']).convert('RGBA')
    a = np.asarray(h)[:, :, 3]; ys, xs = np.nonzero(a > 128); i = (xs + ys).argmin()  # tip = top-left-most point
    tip = np.array([xs[i], ys[i]], np.float32) * HS
    h = h.resize((int(h.width * HS), int(h.height * HS)), Image.LANCZOS); A = np.asarray(h).astype(np.float32)
    al = A[:, :, 3:] / 255
    return A[:, :, :3], al, tip, cv2.GaussianBlur(al[:, :, 0], (0, 0), 14)[:, :, None] * 0.28

def blend(fr, rgb, a, x, y):
    h, w = a.shape[:2]; x0, y0, x1, y1 = max(x, 0), max(y, 0), min(x + w, W), min(y + h, H)
    if x1 <= x0 or y1 <= y0: return
    s = fr[y0:y1, x0:x1]; aa = a[y0 - y:y1 - y, x0 - x:x1 - x]
    s[:] = s * (1 - aa) if rgb is None else s * (1 - aa) + rgb[y0 - y:y1 - y, x0 - x:x1 - x] * aa

CACHE = {}
def scene(k):
    if k not in CACHE:
        d = np.load(f'prep/{k:02d}.npz'); CACHE[k] = (d['img'], d['rank'], d['hand'])
    return CACHE[k]

def window(k):
    t0 = T[k] + (TR if k else 0); L = T[k + 1] - t0
    return t0, (min(0.82 * L, 2.6) if k < N - 1 else min(2.4, 0.7 * L))

def frame_at(t, k, hs, HA):
    HR, HAL, TIP, SH = HA
    img, rank, hp = scene(k); t0, D = window(k); u = (t - t0) / D
    p = float(np.clip(u, 0, 1)) ** 0.92 if u > 0 else 0.0
    b = np.full_like(img, 255); msk = rank <= (p if u < 1 else 2.0); b[msk] = img[msk]
    su = (t - T[k]) / (T[k + 1] - T[k])
    z = 1.0 + 0.05 * su + (0.06 * max(0, (t - t0 - D) / 2.0) if k == N - 1 else 0)
    M = np.array([[z, 0, (1 - z) * W / 2], [0, z, (1 - z) * H * 0.48]], np.float32)
    out = cv2.warpAffine(b.astype(np.float32), M, (W, H), borderValue=(255, 255, 255))
    drawing = 0 < u < 1
    if u <= 0 or drawing or t - (t0 + D) < 0.35:
        if u <= 0: tg = hp[0]
        elif drawing: tg = hp[min(int(p * (len(hp) - 1)), len(hp) - 1)]
        else: q = (t - t0 - D) / 0.35; tg = hp[-1] + np.array([700, 900]) * q * q
        tg = np.array(tg, np.float32); cur = hs.get('pos')
        cur = tg if cur is None else cur + (tg - cur) * 0.55; hs['pos'] = cur
        wob = np.array([np.sin(t * 37) * 3, np.cos(t * 29) * 3]) if drawing else 0
        px = M[:, :2] @ cur + M[:, 2] + wob; x, y = int(px[0] - TIP[0]), int(px[1] - TIP[1])
        blend(out, None, SH, x + 30, y + 34); blend(out, HR, HAL, x, y)
    return out

def transition(a, b, e, kind):
    acc = np.zeros_like(a)
    for s in np.linspace(-0.035, 0.035, 7):
        o = int(np.clip(e + s, 0, 1) * (W if kind == 'x' else H)); f = np.full_like(a, 255)
        if kind == 'x': f[:, :W - o] = a[:, o:]; f[:, W - o:] = b[:, :o]
        else: f[:H - o] = a[o:]; f[H - o:] = b[:o]
        acc += f
    return acc / 7

yy, xx = np.mgrid[0:H, 0:W]
VIG = ((1 - 0.07 * np.clip(np.sqrt(((xx - W / 2) / (W * .75)) ** 2 + ((yy - H / 2) / (H * .75)) ** 2), 0, 1.3) ** 2)[:, :, None]
       * np.array([0.995, 0.995, 0.985])).astype(np.float32)

def render_scene(k, HA):
    path = f'scenes/s{k:02d}.mp4'; tmp = path[:-4] + '.tmp.mp4'
    pr = subprocess.Popen(['ffmpeg', '-y', '-loglevel', 'error', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', f'{W}x{H}', '-r', str(FPS),
                           '-i', '-', '-c:v', 'libx264', '-crf', '18', '-preset', 'veryfast', '-pix_fmt', 'yuv420p', tmp], stdin=subprocess.PIPE)
    prev = frame_at(T[k] - 1e-3, k - 1, {}, HA) if k else None; hs = {}
    for n in range(round(T[k] * FPS), round(T[k + 1] * FPS)):
        t = n / FPS
        if k and t < T[k] + TR:
            e = (t - T[k]) / TR; e = e * e * (3 - 2 * e)
            f = transition(prev, frame_at(T[k] + TR, k, {}, HA), e, 'x' if k % 2 else 'y')
        else: f = frame_at(t, k, hs, HA)
        pr.stdin.write(np.clip(f * VIG, 0, 255).astype(np.uint8).tobytes())
    pr.stdin.close()
    if pr.wait() != 0: raise SystemExit(f'ffmpeg failed scene {k}')
    os.replace(tmp, path); print('scene', k, flush=True)

# ---------------- mix (levels approved by the client: voice on top) ----------------
LEVELS = dict(music=0.08, music_end=0.30, scribble=0.09, pop=0.16, whoosh=0.18, kaching=0.12, chime=0.18)
def mix():
    L = int(END * SR) + 1; out = np.zeros((L, 2), np.float32)
    def add(a, t, g, dur=None, fade=0.03):
        s = int(t * SR)
        if dur is not None: a = np.tile(a, (int(dur * SR) // len(a) + 2, 1))[:int(dur * SR)].copy()
        a = a * g; f = int(fade * SR)
        if f and len(a) > 2 * f: r = np.linspace(0, 1, f)[:, None]; a[:f] *= r; a[-f:] *= r[::-1]
        e = min(s + len(a), L); out[s:e] += a[:e - s]
    vo = wav(P['vo']); mu = wav(P['music']); fx = {k: wav(v) for k, v in P['sfx'].items()}
    env = np.full(L, LEVELS['music'], np.float32); i0 = int((VO_OFF + VO_LEN) * SR); r = int(0.4 * SR)
    seg = env[i0:i0 + r]; env[i0:i0 + r] = np.linspace(LEVELS['music'], LEVELS['music_end'], len(seg)); env[i0 + r:] = LEVELS['music_end']
    fo = int(0.8 * SR); env[-fo:] *= np.linspace(1, 0, fo)
    m = mu[:L] if len(mu) >= L else np.pad(mu, ((0, L - len(mu)), (0, 0))); out += m * env[:, None]
    add(vo, VO_OFF, 1.0, fade=0)
    for k in range(N):
        t0, D = window(k)
        add(fx['scribble'], t0, LEVELS['scribble'], dur=D); add(fx['pop'], t0 + D, LEVELS['pop'])
        if k: add(fx['whoosh'], T[k] - 0.05, LEVELS['whoosh'])
        for x in SC[k].get('extra', []):
            if x in fx: add(fx[x], t0 + (0.72 * D if x == 'kaching' else D - 0.1), LEVELS.get(x, 0.15))
    out *= 0.89 / max(np.abs(out).max(), 1e-6)
    wavfile.write('audio/mix.wav', SR, (out * 32767).astype(np.int16)); print('mix', END)

def final():
    with open('list.txt', 'w') as f:
        for k in range(N): f.write(f"file 'scenes/s{k:02d}.mp4'\n")
    subprocess.run(['ffmpeg', '-y', '-loglevel', 'error', '-f', 'concat', '-safe', '0', '-i', 'list.txt', '-c', 'copy', 'video.mp4'], check=True)
    subprocess.run(['ffmpeg', '-y', '-loglevel', 'error', '-i', 'video.mp4', '-i', 'audio/mix.wav', '-map', '0:v', '-map', '1:a', '-c:v', 'copy',
                    '-af', 'acompressor=threshold=-20dB:ratio=3:attack=5:release=80,loudnorm=I=-14:TP=-1.5:LRA=9', '-ar', '44100',
                    '-c:a', 'aac', '-b:a', '192k', '-shortest', P['out']], check=True)
    print('final', P['out'])

def test(HA):
    os.makedirs('test', exist_ok=True); tiles = []
    for k in sorted({0, N // 3, (2 * N) // 3, N - 1}):
        t0, D = window(k)
        for fr in (0.4, 0.85):
            f = np.clip(frame_at(t0 + D * fr, k, {}, HA) * VIG, 0, 255).astype(np.uint8)
            tiles.append(Image.fromarray(f).resize((W // 4, H // 4)))
    sheet = Image.new('RGB', (W // 4 * len(tiles), H // 4))
    for i, t in enumerate(tiles): sheet.paste(t, (i * W // 4, 0))
    sheet.save('test/test_frames.jpg'); print('test/test_frames.jpg')

if __name__ == '__main__':
    cmd = sys.argv[1]; os.makedirs('prep', exist_ok=True); os.makedirs('scenes', exist_ok=True)
    print('timeline', [round(x, 2) for x in T])
    if cmd in ('prep', 'all'):
        for k, s in enumerate(SC): prep_one(s['img'], f'prep/{k:02d}.npz')
    if cmd in ('test', 'render', 'all'): HA = hand_assets()
    if cmd == 'test': test(HA)
    if cmd in ('render', 'all'):
        ks = [int(x) for x in sys.argv[3].split(',')] if len(sys.argv) > 3 and cmd == 'render' else range(N)
        for k in ks: render_scene(k, HA)
    if cmd in ('mix', 'all'): mix()
    if cmd in ('final', 'all'): final()
```
