A Claude Code skill to make motion design videos in pure code: HTML + Playwright + ffmpeg. No After Effects, no Remotion license.
Render QA upgrade + director's brief, prompt library and techniques from other public motion skills (#1)
ElRaph211eed5cc8e1d3a
diff --git a/README.md b/README.mdindex 1b2b9c3..e46b8ac 100644--- a/README.md+++ b/README.md@@ -40,7 +40,8 @@ Then mux: `ffmpeg -i out/video.mp4 -i out/audio.wav -map 0:v -map 1:a -c:v libx2- **Flow**: inputs → beat map → 4 stills approved → full render → pop scan → audio → final.- **Engine**: `seek(t)` only (no CSS transitions, no timers), closed-form springs, a camera keyed in log space, shared-element handoffs, color floods that clear the farthest corner, masked word-by-word text, and ports of 21st.dev components (Animated Beam, Border Beam) to `seek(t)`.-- **Render**: Playwright screenshots, N subframes per frame blended with `tmix`, BT.709 TV-range encode, single-frame pop detection.+- **Render**: Playwright screenshots (fonts ready, Web Animations paused, 2 rAF after each `seek`), a fast 540p `draft` before the master, N subframes per frame on a 180° shutter blended with `tmix` (never across a hard cut), BT.709 TV-range encode, pop + one-frame flash detection, loop seam check in position and velocity, `WEBGL=1` SwiftShader flags.+- **Brief & QA**: brand folder + sourced `facts.md`, a director's brief (named reference style, timed states, layer list, sound plan) before any code, anti-"AI motion" rules, a prompt library (one-shot, branded, UI morph, launch reveal, LinkedIn loops), a symptom → fix table, and techniques borrowed from other public skills (GSAP/WAAPI seeking, adaptive subframes, cut seams, captions, poster frame 0, B-roll over a voice-over).- **Audio**: find the real drop by band energy (never trust an auto beat grid), start the song so the drop hits the key frame, place each SFX by its measured peak, two-pass loudnorm to -14 LUFS.- **Assets**: free sources only (Mixkit music/SFX/video, Pexels, Unsplash, svgl logos, simple-icons). Scripts to search and download them.- **Remake mode** (`skill/motion-design/scripts/remake/`): frame-locked 1:1 remake of any launch video for your brand, the "original | opus 5.5 copy" split-screen. Phase 0 extracts every frame, detects cuts and writes a shot-by-shot spec; phase 1 is a shared `seek(F)` engine with a palette filter; phase 2 runs 4 build agents (one per shot group, each verifying side-by-side compare sheets against the reference) plus 1 audio agent (royalty-free track stretched to the reference BPM, synthesized SFX on the reference hit times); phase 3 renders, encodes the split-screen and a stacked sync check. Brief template included. Never reuse the reference's music, voice or people photos.diff --git a/skill/motion-design/SKILL.md b/skill/motion-design/SKILL.mdindex b73aa66..5040a02 100644--- a/skill/motion-design/SKILL.md+++ b/skill/motion-design/SKILL.md@@ -35,7 +35,10 @@ Workdir: `~/Desktop/Howseen AI/howseen-video/` (one folder per film). Every film## 3. Render (scripts/render_template.py)- Serve the folder over HTTP (`python -m http.server 876x --directory …`, background), Playwright Chromium, viewport = video size (1920×1080, 1080×1350 for LinkedIn 4:5, 1440×1440 square).-- `probe t1 t2…` → `probe/sheet.png`; `beats` → one frame per beat; `full` → **N subframes per frame blended with `tmix`** (6-8 for fast moves, 4 = ghosting), 60 fps; `pops` → frame-diff spikes > 3× neighbours (intentional beat cuts show up too: say so, don't hide).+- `probe t1 t2…` → `probe/sheet.png`; `beats` → one frame per beat; `draft` → 30 fps, 1 capture/frame, 960×540, crf 23 veryfast (**always before the master**: judge rhythm, not sharpness); `full` → **N subframes per frame blended with `tmix`** (6-8 for fast moves, 4 = ghosting) spread over `SHUTTER = 0.5` of the frame (180° film shutter; 1.0 = smeary), 60 fps; `pops` → frame-diff spikes > 3× neighbours (intentional beat cuts show up too: say so, don't hide); `loop` → seam check in **position (last vs frame 0) AND velocity (motion into vs out of frame 0)**.+- Capture hygiene (built into the template): wait `document.fonts.ready`, pause `document.getAnimations()` and kill CSS transitions after load, and **wait 2 `requestAnimationFrame` after every `seek(t)`** before the screenshot. `WEBGL=1` launches Chromium with SwiftShader/ANGLE flags (headless WebGL otherwise renders black).+- Every film page also gets **preview controls** for Raphaël: Space = play/pause, ←/→ = previous/next frame, R = replay, a time readout. Playback calls the same `seek(t)` from a rAF loop (the only place a clock is allowed); the render never touches it.+- **Films > 25 s: always render in 3 parallel chunks** (`h20/lm55/render_par.py chunk <html> <T> k 3` x3 in background, then `concat`): ~20 min for 55 s instead of ~55 min sequential. Raphaël expects fast turnarounds; never launch a long single-process full render. Re-render only the changed seconds when possible (`part`).- Use a separate `sub*/` folder per version so parallel renders don't clash. ~1-1.5 min of wall time per second of film at 8 subframes; run long renders in the background.- Final encode: `scale=in_range=pc:out_range=tv:out_color_matrix=bt709,format=yuv420p`, `-color_range tv -colorspace bt709`, libx264 crf 16, AAC 256k, `+faststart`.@@ -52,7 +55,7 @@ Workdir: `~/Desktop/Howseen AI/howseen-video/` (one folder per film). Every film- **Video**: Mixkit `assets.mixkit.co/videos/<ID>/<ID>-1080.mp4`, Pexels `pexels.com/download/video/<id>/`. Re-encode all-intra (`-g 1`), load as blob URL, await `seeked`.- **Logos**: `scripts/svgl_logos.py` (svgl.app API, colour SVGs: openai, gemini, perplexity, google, claude, youtube, reddit, trustpilot, linkedin, shopify, wordpress, webflow, framer, nextjs); fallback simple-icons (`cdn.jsdelivr.net/npm/simple-icons@13/icons/<name>.svg`); Howseen marks in `promo60/logos/logo-mark*.png`. 21st.dev `search_logo` currently returns nothing: go to svgl directly.- **21st.dev** components (Animated Beam id 919, Border Beam 1268, Orbiting Circles 1411…): `scripts/mcp21_client.py tools | call search '{…}' | call get_component '{"id":…}'`, key in `~/.config/21st.key` (free tier: 2 code retrievals/day). They're React/framer-motion: **port the idea to seek(t)**, never run them live.-- **Memes**: yt_dlp from the video venv (if YouTube says "page needs to be reloaded", pass `extractor_args={"youtube":{"player_client":["tv","web_safari","android","ios"]}}` and `ffmpeg_location=imageio_ffmpeg.get_ffmpeg_exe()`), `ytsearch6:<meme> meme template`, check a contact sheet (no burned-in captions, no watermarks, cut "Subscribe / link in description" end cards), re-encode H.264 1280 wide + AAC + setsar=1. Library in `promo60/memes/` (Michael Scott, DiCaprio pointing, Travolta, Keanu whoa, Bateman walk, This is fine, Homer bushes, Carrey typing fast, Gatsby toast, Peele sweating).+- **Memes**: yt_dlp from the video venv (if YouTube says "page needs to be reloaded", pass `extractor_args={"youtube":{"player_client":["tv","web_safari","android","ios"]}}` and `ffmpeg_location=imageio_ffmpeg.get_ffmpeg_exe()`), `ytsearch6:<meme> meme template`, check a contact sheet (no burned-in captions, no watermarks, cut "Subscribe / link in description" end cards), re-encode H.264 1280 wide + AAC + setsar=1. Library in `~/Desktop/Howseen AI/illustrations/memes/` (clips/ ready to post, legendes/ captions, sources-brutes/ raw downloads, planches/ check sheets) (Michael Scott, DiCaprio pointing, Travolta, Keanu whoa, Bateman walk, This is fine, Homer bushes, Carrey typing fast, Gatsby toast, Peele sweating).### 5b. Resource shortlist (checked 28/09/2026)- **3D icons: 3dicons.co**, CC0 (commercial use, no attribution), 1,500+ renders. Fits the Howseen "glossy 3D on cream" look for videos, LinkedIn visuals and article covers. Download PNGs, cut-out already transparent; look at them on a contact sheet first.@@ -96,6 +99,55 @@ Open them and **score 1-10**: hook in the first 2 s · readability at 360 px ·- **Synthesized sound option**: when no track is supplied, SFX can be synthesized in code (click = short decaying sine, pop = rising sine, thump = falling sine, whoosh = windowed noise) on the same timeline.- **Effort**: medium for small fixes, xhigh for a new film, max when the first 3 seconds carry a launch.+## 9b. Studio conventions & director's brief (from the "Playbook Opus 5.5" doc, 02/10/2026)+"The prompt is 10 %, the harness is 90 %."+- **Film folder** = `brand/` (logo.svg, palette.txt, screenshots/, reference.mp4 optional but decisive) + **`facts.md`** (every number with its source + date; "no invented metric") + `<name>.html` + `render.py` + `out/`. No facts.md → no numbers on screen. For Howseen, facts come from the app/PostHog/Stripe or a sourced page.+- **Director's brief before any code** (first message, effort max): duration, master format, deliverable formats from the SAME timeline (16:9, 1:1, 9:16), subject + one-line promise, audience, channel, **a named reference style** ("Linear launch", "Stripe docs", "Apple bumper", never "premium modern"), then **states** with timestamps (hook type 0-2.5 → shape becomes screen 1 → transforms to screen 2 with cursor click → proof with a real number → logo + URL, back to state 0 if loop). Expected output: 6 beats + **layer list** + **sound plan** (silence / coded SFX / Mixkit track), then STOP for OK.+- **Anti-"AI motion" rules** (on top of §0/§2): ONE accent colour; **one thing moves at a time** (unless a slider drives a continuous transform); one shape/visual system from start to end, transformations not cuts; springs with damping ratio ≥ 0.72, tiny overshoot, never cartoon bounce; banned: rainbow gradients, particles, glowing chrome, emoji, lorem ipsum, gratuitous 3D flips; type big enough for a phone; 9:16 safe zone decided at storyboard (text inside the centre 1080×1080).+- **Silent "one sentence" test**: show the loop muted to someone; if they summarise it in one sentence ("the button became a player"), it works; if they hesitate, too much moves.+- **Prompt library** (adapt, never paste raw for a client):+ - *One-shot viral* (Stephan Livera, 24/09): "make a dynamic 15-second motion graphics video that shows what an incredible motion designer you are, like it's your showreel for a résumé. go all out." Use once to see the engine; generic output.+ - *One-shot branded*: "Make a 15-second showreel at 1920x1080, 30fps. Keep it in one self-contained index.html. HTML, CSS, JS, SVG or Canvas only. No CDN, no external URLs. Bold type and simple shapes. End on [BRAND]. Play and Replay. window.seek(t). Do not render the MP4 yet." + one accent hex + "no gradient template".+ - *UI morph* (@twoclipping): one shape through 8-12 UI states (button → loader → player → slider → toggle → tabs → chart → command palette → toast), a real slider, ~120 BPM, exact loop.+ - *Product launch / landing reveal* (@notdwd open prompt): inputs → direction → frame-by-frame structure → seek(t) build → gotchas → 4 stills before the full film.+ - *LinkedIn loops* (Eric Djavid): pure HTML/CSS, one charter, one "A becomes B" transform, 5-9 s loop, one thing moves, easings `cubic-bezier(.6,0,.2,1)` and `cubic-bezier(.2,.8,.2,1)`; micro-prompts: button → player, search → results, card → workspace, SVG curve, magnetic dock, hidden title.+ - *SaaS / app*: web = point at the repo (real design tokens); mobile = screenshots + "invent no feature"; storyboard first.+- **Critique prompt** (2-4 rounds, where the "AI look" goes away): capture a frame at every beat and 0.3 s after, contact sheet, score each shot /10 on readability, rhythm, shape continuity, branding, loop; fix only ≤ 7, don't touch shots at 9+.+- **Other routes** (only if asked): HyperFrames (HTML + GSAP, `npx skills add heygen-com/hyperframes`, CLI preview/render: brand content factory) and Remotion (React templates, `npx skills add remotion-dev/skills`: data-driven template library). Our route = bare HTML + seek(t), the one Opus picks on its own.++**Diagnostic when it's ugly**+| Symptom | Cause → fix |+|---|---|+| Same film as all of X | Livera prompt pasted with no charter/states → brief + facts + named style |+| Blurry text / washed logo | Went through a pixel video model → back to code, real SVG |+| Stutters on export | Timers / CSS transitions → pure seek(t), 2 rAF wait |+| Loop jumps | Position matched, velocity not → add the spring tails of the previous 2 cycles; `render.py loop` |+| Cheap, bouncy | Bounce easing → springs, damping ≥ 0.72 |+| Invented feature | No screenshots / repo / facts.md |+| Black WebGL | `WEBGL=1` (SwiftShader/ANGLE flags) |+| Cost explodes | Effort max on micro-fixes → medium for patches |++## 9c. Stolen from the other public motion skills (scan 02/10/2026)+- **Seek third-party libs instead of banning them** (HyperFrames adapters): GSAP skips the redraw when asked for the same time, so `tl.pause(); tl.totalTime(t + 0.001, true); tl.totalTime(t, true)`. WAAPI/CSS: `document.getAnimations().forEach(a => { a.pause(); a.currentTime = t * 1000 })`. Lottie `goToAndStop(t*1000)`, anime.js `seek`. Video sources: pre-extract frames with ffmpeg rather than waiting on `seeked` when it flakes.+- **Deterministic Chromium flags** for pixel-identical reruns: `--deterministic-mode --run-all-compositor-stages-before-draw --disable-threaded-animation --disable-checker-imaging --font-render-hinting=none --force-color-profile=srgb`. GPU WebGL on the Mac: `--use-angle=metal`.+- **Adaptive subframes** (Kimeur): measure the fastest element's px/frame; still → 1 sample, ≤ 20 px → 4, above → `ceil(px/5)` up to 64. Huge time saver vs a fixed 8 on mostly static films. **Never blur across a hard cut**: list the cuts in `CUTS` (template clamps subframes to the frame's side of the cut).+- **Targeted blur > full-frame blur** (HyperFrames): blur only the 1-3 slam moves; never blur text meant to be read or any move < one element width per frame. **Supersample 2×** (`device_scale_factor=2`, Lanczos down) for razor text, cheaper than tmix on static type.+- **Cut seams** (HyperFrames seam gate): cut at peak velocity; direction AND speed match on both sides; zoom keeps the sign of d(scale)/dt across the cut; seam blur scales with size (≈ 10 px text, 18-20 px full frame).+- **QA additions**: one-frame flash detector (built into `pops`: frame n differs from both neighbours while n-1 ≈ n+1); `loop` checks seek(0) vs seek(T), T-1f, T-1.75f; cycles must be integer `cyc(t, n)`. **Judge ≠ builder**: run the critique as a separate read-only sub-agent, and have a fresh agent restate the message from the frames alone (if it can't, the film fails).+- **Poster in frame 0** (X/Slack/Discord ignore the cover): `-filter_complex "[0:v][1:v]overlay=0:0:enable='eq(n,0)'[v]"` with the poster PNG as input 1.+- **Music cues** (brag): onset strength per track, intensity = 0.45·onset + 0.25·contrast + 0.20·rms + 0.10·bass; reveals may shift ≤ 0.15 s (small entrances ≤ 0.10 s) to snap onto a cue. Silence detection adaptive: read `input_thresh` from `loudnorm print_format=json`, feed `silencedetect=noise=<thresh>dB`.+- **Captions** (Kimeur/HyperFrames): pop 1-3 words or karaoke 3-7, ≥ 0.7 s on screen, ≤ 17 chars/s, no 1-3 frame gaps, a word lights on its start frame never before; Whisper word timings, drop words hallucinated over trailing silence.+- **Preview HUD** (QasimTalkin): clickable scrubber, ←/→ ±0.5 s (Shift = 1 frame), clock synced to `out/mix.wav`, beat number shown, `?t=` deep link.+- **B-roll over a talking head** (Barty-Bart `/motion-broll`): full-frame cutaways 3-10 s with ≥ 2 s of face between, or transparent panels in the empty space; alpha clips via `screenshot(omit_background=True)` → `format=gbrap` → ProRes 4444; never `will-change` on an element the camera scales.++## 9d. From the YouTube walkthroughs (Bart Slodyczka, Moritz, Jack Roberts, 24-25/09; transcripts in vault `30 Ressources/.raw/`)+- **B-roll over an existing VO / talking head**: ask the **density** first (≈ 33 s: medium = 3 clips, heavy = 4-5; pick heavy, cutting is easier than adding). Input = word-timestamped transcript (whisper). Plan line by line, each graphic tagged *full cutaway* / *face stays* / *transparent panel in the empty space*, approved before rendering. Graphics land on the spoken word. The creator pre-edits (cuts + shrinks themself to a third of the frame) so the empty space is known. Deliver all clips in one local review page. Medium effort is enough.+- **VO pipeline**: TTS (Cartesia/ElevenLabs), speed up slightly + trim silences with ffmpeg (adaptive `silencedetect`, §9c), local whisper.cpp for word timings → ONE timing file that drives both captions and animation cues. Check words clipped at edits.+- **Long → Short**: one topic per Short (split rather than compress), faster cuts, quick real-face shots from the original footage, regenerate VO in pieces, model the creator's own short-form scripts.+- **Brand intake**: Firecrawl `scrape` with the **`branding` format** (not markdown) pulls a site's colours/fonts/identity into `brand/` (needs a Firecrawl key; otherwise Playwright screenshots + pixel sampling as in §11).+- **Fight the fingerprint**: Claude's default font and crowded vertical layouts are recognisable: always set the brand font, and on 9:16 talking heads keep speaker bottom / one graphic top / captions, nothing else.+- **Use cases that worked**: explainer from a doc/SOP/skill ("make it fun, not too serious"); a **mascot SVG narrator** carrying the story; a **video version of a sales proposal** with real discovery-call numbers (anonymised); static HTML slides → animated slide loops (5-20 s); 3 s logo sting + jingle (batchable: 100 logos, each in the brand's main colour); restyle from a reference image (savee.com / Pinterest), add a grain/film-burn pass if it falls flat. One-prompt launch films can fan out to parallel sub-agents per section (like remake Phase 2).+## 10. Remake mode — frame-locked 1:1 copy of an existing video (scripts/remake/)Use when asked to "remake / recreate this launch video for my brand" (the split-screen "original | opus 5.5 copy" format). Proven on the Gojiberry launch (65 s, 28 shots) on 28/09/2026.- **Phase 0, analysis (no building):** download REF (yt_dlp in the video venv, no browser cookies) → `remake_analyze.py` extracts all frames 0-based to ref/full, audio to ref/audio.wav, detects hard cuts (mean-abs-diff spikes) and writes 6-frame contact sheets. Read the sheets, write SPEC.md: shot table (id, f0–f1, REF content, brand swap), swap rules. Most "cuts" in modern launch films are continuous camera/morph moves: expect only ~10-15 hard cuts, and expect SPEC boundaries to be a few frames off (agents fix them).diff --git a/skill/motion-design/scripts/render_template.py b/skill/motion-design/scripts/render_template.pyindex 2cb913d..81638c1 100644--- a/skill/motion-design/scripts/render_template.py+++ b/skill/motion-design/scripts/render_template.py@@ -1,7 +1,13 @@-"""Render film.html frame by frame.-probe t1 t2 ... -> probe/sheet.png | beats -> one frame per beat | full -> N subframes/frame blended with tmix, 60 fps -> out/video.mp4 | pops -> single-frame pop scan.-Serve the folder first: python -m http.server 8000 (FILM_URL overrides the page URL)."""-import asyncio, shutil, subprocess, sys+"""frame. film renderer.+probe t1 t2 ... -> probe/p_XX.png + probe/sheet.png (4 columns)+beats -> one frame per beat (54) -> probe/beats.png+draft -> 30 fps, 1 capture per frame, 960x540, crf 23 veryfast -> out/draft.mp4 (judge rhythm, not sharpness)+full -> SUB subframes per frame on a SHUTTER (0.5 = 180 deg) blended with tmix, 60 fps -> out/crave_video.mp4+pops -> scan out/crave_video.mp4 for single-frame pops (diff spikes 3x their neighbours)+loop -> loop seam check: frame 0 vs last (position) and first vs last motion (velocity)+WEBGL=1 env -> launch Chromium with SwiftShader/ANGLE flags (headless WebGL renders black otherwise)+"""+import asyncio, os, shutil, subprocess, sysfrom pathlib import Pathimport numpy as npimport imageio_ffmpeg@@ -9,24 +15,33 @@ from playwright.async_api import async_playwrightHERE = Path(__file__).parentFF = imageio_ffmpeg.get_ffmpeg_exe()-import os-URL = os.environ.get("FILM_URL", "http://localhost:8000/film.html")-FPS, T, SUB = 60, 24.0, 8+URL = "http://localhost:8767/crave.html"+FPS, T, SUB = 60, 32 * 60 / 130, 8+SHUTTER = 0.5 # fraction of the frame interval the subframes cover (0.5 = 180 deg film look, 1.0 = smeary)+CUTS = [] # hard-cut times (s): subframes never straddle a cut (no double exposure on the cut frame)+ARGS = ["--autoplay-policy=no-user-gesture-required"]+if os.environ.get("WEBGL"): ARGS += ["--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist"]async def open_page(p):- b = await p.chromium.launch(args=["--autoplay-policy=no-user-gesture-required"])- pg = await b.new_page(viewport={"width": 1080, "height": 1350}, device_scale_factor=1)+ b = await p.chromium.launch(args=ARGS)+ pg = await b.new_page(viewport={"width": 1920, "height": 1080}, device_scale_factor=1)errs = []pg.on("pageerror", lambda e: errs.append(str(e)))pg.on("console", lambda m: errs.append("console: " + m.text) if m.type in ("error", "warning") else None)await pg.goto(URL)await pg.wait_for_function("window.ready === true", timeout=120000)+ await pg.evaluate("document.fonts.ready")+ # freeze anything that would run on the wall clock (stray CSS animations/transitions, Web Animations)+ await pg.add_style_tag(content="*,*::before,*::after{transition:none!important;caret-color:transparent!important}")+ await pg.evaluate("document.getAnimations().forEach(a => a.pause())")return b, pg, errsasync def shot(pg, t, path, fmt="png"):await pg.evaluate(f"window.seek({t})")+ # 2 rAF: let layout/paint of the seeked frame land before the capture+ await pg.evaluate("new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))")el = await pg.query_selector("#stage")await el.screenshot(path=str(path), type=fmt, **({"quality": 95} if fmt == "jpeg" else {}))@@ -51,12 +66,14 @@ async def probe(times, name="sheet.png", cols=4):async def full():sub = HERE / "sub"; shutil.rmtree(sub, ignore_errors=True); sub.mkdir()n, k = int(round(T * FPS)), 0- offs = [(j - (SUB - 1) / 2) / (FPS * SUB) for j in range(SUB)]+ offs = [(j - (SUB - 1) / 2) * SHUTTER / (FPS * SUB) for j in range(SUB)]async with async_playwright() as p:b, pg, errs = await open_page(p)for i in range(n):for o in offs:t = min(T - 1e-3, max(0.0, i / FPS + o))+ for c in CUTS: # keep every subframe on the same side of a cut as the frame centre+ if (t < c) != (i / FPS < c): t = c if i / FPS >= c else c - 1e-4await shot(pg, t, sub / f"s_{k:05d}.jpg", "jpeg"); k += 1if i % 60 == 0: print(f"frame {i}/{n}", flush=True)await b.close()@@ -64,12 +81,44 @@ async def full():(HERE / "out").mkdir(exist_ok=True)subprocess.run([FF, "-v", "error", "-y", "-framerate", str(FPS * SUB), "-i", str(sub / "s_%05d.jpg"),"-vf", f"tmix=frames={SUB},select='eq(mod(n\\,{SUB})\\,{SUB - 1})',setpts=N/{FPS}/TB", "-r", str(FPS),- "-c:v", "libx264", "-crf", "14", "-preset", "slow", "-pix_fmt", "yuv420p", str(HERE / "out/video.mp4")], check=True)- print("video ->", HERE / "out/video.mp4")+ "-c:v", "libx264", "-crf", "14", "-preset", "slow", "-pix_fmt", "yuv420p", str(HERE / "out/crave_video.mp4")], check=True)+ print("video ->", HERE / "out/crave_video.mp4")+++async def draft(fps=30):+ sub = HERE / "sub_draft"; shutil.rmtree(sub, ignore_errors=True); sub.mkdir()+ n = int(round(T * fps))+ async with async_playwright() as p:+ b, pg, errs = await open_page(p)+ for i in range(n): await shot(pg, min(T - 1e-3, i / fps), sub / f"d_{i:05d}.jpg", "jpeg")+ await b.close()+ if errs: print("PAGE ERRORS:", errs[:8])+ (HERE / "out").mkdir(exist_ok=True)+ subprocess.run([FF, "-v", "error", "-y", "-framerate", str(fps), "-i", str(sub / "d_%05d.jpg"), "-vf", "scale=960:-2",+ "-c:v", "libx264", "-crf", "23", "-preset", "veryfast", "-pix_fmt", "yuv420p", str(HERE / "out/draft.mp4")], check=True)+ print("draft ->", HERE / "out/draft.mp4")+++def frames_gray(path, size=180):+ raw = subprocess.run([FF, "-v", "quiet", "-i", str(path), "-vf", f"scale={size}:{size},format=gray", "-f", "rawvideo", "-"],+ capture_output=True, check=True).stdout+ return np.frombuffer(raw, np.uint8).reshape(-1, size, size).astype(np.float32)+++def loop_check(path=None):+ """A loop must match in position AND velocity: last frame ~ frame 0, and the motion entering frame 0+ (last -> 0) ~ the motion leaving it (0 -> 1). Fix velocity by adding the spring tails of the previous cycle."""+ fr = frames_gray(path or HERE / "out/crave_video.mp4")+ steps = np.abs(np.diff(fr, axis=0)).mean(axis=(1, 2))+ seam = np.abs(fr[-1] - fr[0]).mean()+ med = float(np.median(steps)) or 0.3+ print(f"seam diff {seam:.2f} (median frame step {med:.2f}) -> {'OK' if seam <= 2 * med else 'JUMP: fix positions at t=0/T'}")+ vin, vout = np.abs(fr[-1] - fr[-2]).mean(), np.abs(fr[1] - fr[0]).mean()+ print(f"velocity in {vin:.2f} / out {vout:.2f} -> {'OK' if abs(vin - vout) <= max(1.0, 0.5 * max(vin, vout)) else 'SPEED BREAK at the seam'}")def pops(path=None):- path = path or HERE / "out/video.mp4"+ path = path or HERE / "out/crave_video.mp4"raw = subprocess.run([FF, "-v", "quiet", "-i", str(path), "-vf", "scale=180:180,format=gray", "-f", "rawvideo", "-"],capture_output=True, check=True).stdoutfr = np.frombuffer(raw, np.uint8).reshape(-1, 180, 180).astype(np.float32)@@ -80,11 +129,22 @@ def pops(path=None):if d[i] > 3 * nb and d[i] > 2.0: hits.append((i + 1, round((i + 1) / FPS, 3), round(float(d[i]), 2), round(float(nb), 2)))print("pops:", len(hits))for h in hits: print(" frame", h[0], "t", h[1], "diff", h[2], "neighbours", h[3])+ # one-frame flash: two big diffs side by side mask each other above; frame n differs from both+ # neighbours while n-1 and n+1 look alike+ flashes = []+ for n in range(1, len(fr) - 1):+ a, b = d[n - 1], d[n]+ skip = np.abs(fr[n + 1] - fr[n - 1]).mean()+ if min(a, b) > 2.0 and skip < 0.35 * min(a, b): flashes.append((n, round(n / FPS, 3), round(float(min(a, b)), 2), round(float(skip), 2)))+ print("one-frame flashes:", len(flashes))+ for f in flashes: print(" frame", f[0], "t", f[1], "diff", f[2], "n-1 vs n+1", f[3])if __name__ == "__main__":cmd = sys.argv[1]if cmd == "probe": asyncio.run(probe([float(x) for x in sys.argv[2:]]))- elif cmd == "beats": asyncio.run(probe([b * 0.5 + 0.45 for b in range(48)], "beats.png", cols=9))+ elif cmd == "beats": asyncio.run(probe([b * 60 / 130 + 0.45 for b in range(32)], "beats.png", cols=9))+ elif cmd == "draft": asyncio.run(draft())elif cmd == "full": asyncio.run(full())elif cmd == "pops": pops()+ elif cmd == "loop": loop_check()