⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
motion-design
Code-only motion design pipeline (no After Effects) for Raphaël / Howseen: launch films, showreels, product promos, LinkedIn/X videos, meme clips. Use when asked to make a motion design video, a promo/launch film, a showreel, "remake this video", a video from a prompt (e.g. "make a 15s motion graphics video…"), to change a video's music/SFX, or to prepare memes for posts. Covers the brief → beat map → stills → seek(t) HTML engine → Playwright render → ffmpeg → music/SFX → QA flow, plus asset sou
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
Not yet listed on ClawHub or SkillsMP
// README
claude-motion-design
A Claude Code skill to make motion design videos in pure code: HTML + Playwright + ffmpeg. No After Effects, no Remotion license, no editing app.
Every frame is computed from time, rendered frame by frame, blended for motion blur, and cut to the beat of the music. Every sound effect lands on its measured peak.
The example above is the launch video of Howseen (AI visibility tracking: see if ChatGPT, Gemini and Perplexity recommend your brand). It was made with Claude Opus 5.5 and this skill, in 5 iterations. Its full source is in examples/howseen-launch.
Why code instead of an editor
- Deterministic: the whole film is one
seek(t)function. Same input, same frames, every time. Fix one scene without touching the rest. - Free: Chromium, ffmpeg, Python. No license, no subscription.
- Beat-synced by construction: scenes are placed on a beat map, the music drop is aligned to the key visual moment, SFX are placed by peak.
- Iterable by an AI: "make the transitions faster", "change the music", "add a 3D cube on the drop" are just code changes.
Install
- Copy the skill into Claude Code:
mkdir -p ~/.claude/skills && cp -r skill/motion-design ~/.claude/skills/ - Python deps:
pip install playwright imageio-ffmpeg numpy pillow && python -m playwright install chromium - In Claude Code, ask for a video, or type
/motion-design.
Run the example
cd examples/howseen-launch
python fetch_assets.py # downloads the free music, SFX, logos and font (not redistributed here)
python -m http.server 8000 & # serve the film
python render.py probe 1 8 15 20 # quick stills -> probe/sheet.png
python render.py full # 24 s, 60 fps, subframe motion blur -> out/video.mp4
python audio.py # music + SFX by peak, -14 LUFS -> out/audio.wav
Then mux: ffmpeg -i out/video.mp4 -i out/audio.wav -map 0:v -map 1:a -c:v libx264 -crf 16 -c:a aac -shortest out/final.mp4
What the skill covers
- 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) toseek(t). - Render: Playwright screenshots (fonts ready, Web Animations paused, 2 rAF after each
seek), a fast 540pdraftbefore the master, N subframes per frame on a 180° shutter blended withtmix(never across a hard cut), BT.709 TV-range encode, pop + one-frame flash detection, loop seam check in position and velocity,WEBGL=1SwiftShader 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 sharedseek(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. - Honesty rules: illustrative data is labelled "Example data" on screen; captions stay true.
Credits and licenses
Code: MIT. Third-party media is downloaded by fetch_assets.py and stays under its own license (Mixkit free license, Pexels/Unsplash licenses, OFL for Geist). Brand logos belong to their owners. The Howseen mark in the example belongs to Howseen AI.
Made by Raphaël Aubry, founder of Howseen.
// HOW IT'S BUILT
// FILES
16 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
skill/motion-design/SKILL.md33 KB623ce4a863b1truncatedupstream ↗
Showing the inlined prefix. The rest is in the upstream file.
--- name: motion-design description: Code-only motion design pipeline (no After Effects) for Raphaël / Howseen: launch films, showreels, product promos, LinkedIn/X videos, meme clips. Use when asked to make a motion design video, a promo/launch film, a showreel, "remake this video", a video from a prompt (e.g. "make a 15s motion graphics video…"), to change a video's music/SFX, or to prepare memes for posts. Covers the brief → beat map → stills → seek(t) HTML engine → Playwright render → ffmpeg → music/SFX → QA flow, plus asset sourcing (Mixkit, Pexels, Unsplash, svgl, 21st.dev) and every gotcha hit so far. --- # Motion design, 100 % code (Howseen pipeline) Built and battle-tested 25-27/09/2026 on: promo60 (60 s VO ad), loop, launch film, showreel v1/v2, frame. (Apple-keynote prompt), Crave (food-app prompt), reel15 (howseen.ai in 1 prompt + "make it better" pass), Baguette Pro (Apple framework parody), Howseen LinkedIn v1→v5 (4:5). Workdir: `~/Desktop/Howseen AI/howseen-video/` (one folder per film). Every film folder = `<name>.html` + `render.py` + `audio.py` + `out/`. **Our stack vs the "AI motion" stack people post** (Opus + Higgsfield + Blender + After Effects + Suno + Soundly): we replace Blender/After Effects with a deterministic HTML engine rendered frame by frame, Higgsfield with real stock (Pexels/Unsplash) or coded visuals, Suno with Mixkit music, Soundly with Mixkit SFX. 0 € and fully reproducible. Suno/Envato/Higgsfield only if Raphaël asks and has credits. ## 00. Start from the library (fastest path) - **Read `howseen-video/INDEX.md` first**: every film we made, its final file and what to reuse. Copy the closest folder instead of starting from zero. - **Brief given as frame tables** (f0–fN, hard cuts, per-frame px lists, "motion law p(n)=…"): copy `launch20/` (02/10/2026). It has the frame-number engine (`core.js`: `T`/`L`/`kf` registered tables, `law()`, `settleT`/`exitT`/`joinT`, `scanTables()` that blocks one-frame outliers, `makeField` colour field, `makeBadge`, macOS cursor), fictional Mac apps in em units (`ui.js`: chat, call, notes, files, board, dock icons, `lineIcon` set, `tx` helper), shot registry split in files so **3 agents build shot groups in parallel** (one file each), `render.py` (deviceScaleFactor 2 = 4K, `PROBE=<dir>` per agent, `frames a b` in 3 parallel processes, `encode` with frame count check, no `-shortest`), `audio.py` (music + SFX 100 % synthesized on exact frames, two-pass −14 LUFS / TP −1.3). - Workflow that worked on launch20 (≈2 h brief → v2): inputs (AskUserQuestion) → 4 stills → BRIEF.md in the folder → 3 build agents + 1 side task in parallel → scan → parallel render → encode → **motion critic + design critic as separate read-only agents (default reject)** → FIXES file split per agent → v2. - Lessons from the critics (apply from the first pass): never key settles in 3-frame steps (per-frame law, fastest step first), exits geometric ×1.5, **no frozen frame anywhere except the final hold** (keep a micro settle/drift alive, also on still end cards), the next shot enters already moving in the exit's direction, real icons (no empty placeholder squares), one face per name everywhere, grade photos to remove banned hues with a continuous per-pixel formula (hue thresholds blotch JPEG blocks), traffic lights/details sized in the component's em units. - People in fictional UIs: AI-generated faces (thispersondoesnotexist.com/random-person.jpeg, crop centre 76 % to drop the watermark), names chosen to match each face, never a real person. Photos: picsum (Unsplash licence) when Unsplash napi returns 401; build a contact sheet and pick by eye (an agent can do it). ## 0. Non-negotiables - **Zero fabrication on screen**: real data is sourced on screen (e.g. "12 logged-out ChatGPT answers · 25 Sep 2026"); anything illustrative is labelled **"Example data" / "Example answer" / "Illustration"**. Never claim product features that don't exist (check the app code). Native CMS = WordPress, Shopify, Ghost, BigCommerce; others "via webhook". - **Captions must stay true**: no "made in 10 minutes" if it wasn't, no "0 external tools" if Cartesia/Mixkit were used, no "one shot" after iterations. Mixkit SFX are *placed* by code, not generated. - Illustrations/covers: **no Howseen name/logo** in AI-generated images (rule 25/09). Howseen can appear in our own coded promo films. - No em/en dashes in any copy we write. ## 1. Flow (always in this order) 1. **Inputs**: if the brief has an `<inputs>` block, ask for them (AskUserQuestion, recommended defaults first). Otherwise pick sensible defaults and say so. 2. **Beat map** (`BEATMAP.md`): BPM → beat length, every scene on a beat, the **music drop on the key visual moment** (flood, logo, big reveal). Nothing still for > 1 s. 3. **4 stills** (or a one-frame-per-beat sheet) → look at them (Read) → fix → only then the full render. 4. Full render → pops scan → audio → mux → **open -R** the file and give the path + a true caption. ## 2. The engine (one HTML file) - Everything computed from time inside `window.seek = async (t) => {…}`; **no CSS transitions, no timers, no state between frames**. Declare all constants before the first `seek()`. Set `window.ready = true` after fonts/images load. - **Springs** = closed-form step response `step(tau, f, z)`; a value with many targets = sum of one spring per change. Easings: `io` (cubic in-out), `out`, `in`, `o5`, `expo`. Linear motion = cheap, never. - **Camera** = one transform on a container, keys `[t, zoom, x, y]`, eased segments, **zoom interpolated in log space**, never zoom in/out back-to-back. Beat punches: `+0.012` per beat, `+0.03` per bar after the drop, exp decay. - **Shared elements** for every handoff (the bubble carries its words into the flood, the button carries its label into the page). Text that swaps inside a morphing shape gets its own mask. - **Masked text rise** (translateY 105% inside overflow:hidden), word-by-word stagger (55 ms) with a small rotation; accent words with a moving gradient (`background-clip:text`). - **Floods**: circle from the source object, must **clear the farthest corner** (`hypot` to the 4 corners ×1.05) in ~0.3-0.35 s, then contract into the next object. - Glass / goo / iris / variable-font squeeze / 3D cube / equalizer / blob mask / animated beam / border beam: reference implementations in `frame/frame.html` (liquid glass via canvas displacement, goo, 6-blade iris, Archivo wdth squeeze), `reel2/reel2.html` (morph shapes, cube, EQ, blob), `h20/h28.html` (21st.dev Animated Beam + Border Beam ported to seek(t), dotted grid, drifting blobs, sheen sweep, sparkles). - `z-index` on every layer. `visibility:inherit` (not `visible`) on children of hidden parents. - Look: warm off-white `#f5f5f2`/`#f7f7f5` or ink `#0b0b0c`; Howseen sky `#38bdf8`, ink `#0f172a`, lime `#cdf24f`, orange `#ff6a2a`, violet `#a78bfa`. Fonts in `crave/fonts/geist-latin.woff2`, `frame/fonts/archivo-var.woff2` (wdth 62-125), `crave/fonts/instrument-serif.woff2`. ## 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; `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 everyskill/motion-design/scripts/analyze_song.py1.2 KB414a2026a3f3upstream ↗
"""Estimate BPM (onset autocorrelation) and print a 1-second energy profile (full + low band) for each file.""" import subprocess, sys import numpy as np, imageio_ffmpeg FF, SR = imageio_ffmpeg.get_ffmpeg_exe(), 22050 for f in sys.argv[1:]: x = np.frombuffer(subprocess.run([FF, "-v", "quiet", "-i", f, "-ac", "1", "-ar", str(SR), "-f", "f32le", "-"], capture_output=True).stdout, np.float32) hop = 256; fr = len(x) // hop env = np.array([np.sqrt((x[i * hop:(i + 1) * hop] ** 2).mean()) for i in range(fr)]) on = np.maximum(0, np.diff(np.log(env + 1e-6))); on -= on.mean() ac = np.correlate(on[:6000], on[:6000], "full")[5999:] fps = SR / hop; lags = np.arange(len(ac)) / fps best = max(((60 / l, ac[i]) for i, l in enumerate(lags) if 0.33 < l < 1.0), key=lambda z: z[1]) print(f"\n== {f.split('/')[-1]} dur {len(x) / SR:.1f}s BPM~{best[0]:.1f}") lp = np.convolve(x, np.ones(60) / 60, "same") row = [] for s in range(0, int(len(x) / SR)): seg = x[s * SR:(s + 1) * SR]; ls = lp[s * SR:(s + 1) * SR] row.append(f"{s:3d}:{10 * np.log10((seg ** 2).mean() + 1e-12):5.1f}/{10 * np.log10((ls ** 2).mean() + 1e-12):5.1f}") for i in range(0, min(len(row), 48), 6): print(" " + " ".join(row[i:i + 6]))skill/motion-design/scripts/audio_template.py3.2 KB8c44ed12b851upstream ↗
"""Howseen LinkedIn v4 soundtrack (24 s): Mixkit 'Cat Walk. (Arulo, 130 BPM) from 6.77 s so its big hit (song 37.66 s) lands on the sky flood at 8.0 s. SFX by measured peak, fade the last 0.9 s, loudnorm -14 LUFS.""" import json, subprocess from pathlib import Path import numpy as np import imageio_ffmpeg HERE = Path(__file__).parent; ROOT = HERE.parent FF, SR, T = imageio_ffmpeg.get_ffmpeg_exe(), 48000, 24.0 N = int(round(T * SR)); START = 14.769 - 8.0 def load(p): raw = subprocess.run([FF, "-v", "quiet", "-i", str(p), "-ac", "2", "-ar", str(SR), "-f", "f32le", "-"], capture_output=True, check=True).stdout return np.frombuffer(raw, np.float32).reshape(-1, 2).copy() mix = load(HERE / "assets/audio/cat-walk.mp3")[int(START * SR):][:N].copy() fi = int(0.25 * SR); mix[:fi] *= np.linspace(0, 1, fi)[:, None] S = {k: load(HERE / f"assets/sfx/{v}.mp3") for k, v in dict(soft=1117, key=2568, click=1125, pop=2357, rise="w1489", impact=1143, whoosh="w1490", success=2865, sparkle=3083).items()} EV = [(0.1, "soft", .08), (0.35, "soft", .08)] + [(0.5 + i * .05, "pop", .04) for i in range(8)] + [(1.35, "soft", .08)] EV += [(2.5, "whoosh", .05)] + [(2.8 + i * .054, "key", .05) for i in range(13)] + [(3.85, "click", .2)] EV += [(4.55, "whoosh", .05)] + [(4.7 + i * .06, "pop", .06) for i in range(5)] + [(5.3 + i * .09, "soft", .04) for i in range(8)] EV += [(6.6 + i * .08, "pop", .05) for i in range(5)] + [(7.0 + i * .08, "soft", .05) for i in range(5)] + [(7.2, "rise", .12)] EV += [(8.0, "impact", .2), (8.45, "sparkle", .09)] + [(8.45 + i * .1, "pop", .06) for i in range(3)] EV += [(10.05, "whoosh", .05)] + [(10.45 + i * .07, "pop", .035) for i in range(6)] + [(12.05, "whoosh", .05)] EV += [(12.35 + i * .05, "pop", .035) for i in range(6)] + [(14.05, "whoosh", .05)] + [(14.3 + i * .08, "soft", .05) for i in range(5)] EV += [(16.05, "whoosh", .05)] + [(16.3 + i * .04, "key", .045) for i in range(16)] + [(17.2, "click", .2), (17.35, "success", .12)] EV += [(18.1, "whoosh", .05)] + [(18.15 + i * .06, "pop", .05) for i in range(9)] EV += [(20.1, "sparkle", .11), (21.1, "pop", .09), (22.35, "click", .2)] for t, name, gain in EV: s = S[name] / (np.abs(S[name]).max() + 1e-9) * gain i0 = int(round(t * SR)) - int(np.abs(s).sum(1).argmax()) lo, hi = max(0, i0), min(N, i0 + len(s)) if hi > lo: mix[lo:hi] += s[lo - i0:hi - i0] f0 = int(23.1 * SR); mix[f0:] *= np.linspace(1, 0, N - f0)[:, None] ** 1.3 rawp = HERE / "out/raw.wav"; rawp.parent.mkdir(exist_ok=True) subprocess.run([FF, "-v", "error", "-y", "-f", "f32le", "-ar", str(SR), "-ac", "2", "-i", "-", str(rawp)], input=mix.astype(np.float32).tobytes(), check=True) m = subprocess.run([FF, "-hide_banner", "-i", str(rawp), "-af", "loudnorm=I=-14:TP=-1:LRA=11:print_format=json", "-f", "null", "-"], capture_output=True, text=True).stderr j = json.loads(m[m.rindex("{"):m.rindex("}") + 1]) af = (f"loudnorm=I=-14:TP=-1:LRA=11:measured_I={j['input_i']}:measured_TP={j['input_tp']}:measured_LRA={j['input_lra']}" f":measured_thresh={j['input_thresh']}:offset={j['target_offset']}:linear=true") subprocess.run([FF, "-v", "error", "-y", "-i", str(rawp), "-af", af, "-ar", str(SR), str(HERE / "out/audio.wav")], check=True) print("audio ->", HERE / "out/audio.wav")skill/motion-design/scripts/mcp21_client.py2.1 KB546aae5f3c3fupstream ↗
"""Minimal MCP client for 21st.dev (streamable HTTP + x-api-key). usage: mcp21.py tools | mcp21.py call <tool> '<json>'""" import json, os, sys, urllib.request KEY = os.environ.get("API_KEY_21ST") or open(os.path.expanduser("~/.config/21st.key")).read().strip() URL = "https://21st.dev/api/mcp" SID = None def rpc(method, params=None, id_=1): global SID body = {"jsonrpc": "2.0", "method": method} if id_ is not None: body["id"] = id_ if params is not None: body["params"] = params h = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", "x-api-key": KEY, "User-Agent": "claude-code-mcp-client/1.0"} if SID: h["Mcp-Session-Id"] = SID try: r = urllib.request.urlopen(urllib.request.Request(URL, data=json.dumps(body).encode(), headers=h), timeout=90) except urllib.error.HTTPError as e: print("HTTP", e.code, e.read().decode()[:600]); sys.exit(1) SID = r.headers.get("Mcp-Session-Id") or SID raw = r.read().decode() if not raw.strip(): return None if raw.lstrip().startswith("{"): return json.loads(raw) for line in raw.splitlines(): if line.startswith("data:"): d = json.loads(line[5:].strip()) if d.get("id") == id_: return d return raw rpc("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "claude-code-raph", "version": "1"}}) rpc("notifications/initialized", None, None) if sys.argv[1] == "tools": for t in rpc("tools/list", {}, 2)["result"]["tools"]: props = list((t.get("inputSchema") or {}).get("properties", {}).keys()) print(f"- {t['name']}({', '.join(props)}): {(t.get('description') or '')[:260]}") else: res = rpc("tools/call", {"name": sys.argv[2], "arguments": json.loads(sys.argv[3] if len(sys.argv) > 3 else "{}")}, 3) r = res.get("result", res) if isinstance(res, dict) else res if isinstance(r, dict) and "content" in r: for c in r["content"]: print(c.get("text", c)[:12000] if isinstance(c.get("text"), str) else c) else: print(json.dumps(r, ensure_ascii=False)[:12000])skill/motion-design/scripts/mixkit_sfx_search.py1011 B67d09a1f51d2upstream ↗
"""List Mixkit SFX (id + title): each card's title is searched between its own id marker and the next one, and before it.""" import re, sys, urllib.request for q in sys.argv[1:]: html = urllib.request.urlopen(urllib.request.Request(f"https://mixkit.co/free-sound-effects/{q}/", headers={"User-Agent": "Mozilla/5.0"}), timeout=20).read().decode("utf8", "ignore") marks = [(m.start(), m.group(1)) for m in re.finditer(r'data-audio-player-item-id-value="(\d+)"', html)] titles = [(m.start(), m.group(1).strip()) for m in re.finditer(r'item-grid-card__title">\s*(?:<[^>]+>\s*)*([^<]+?)\s*<', html)] print("==", q, len(marks), "ids", len(titles), "titles") for i, (p, sid) in enumerate(marks[:14]): nxt = marks[i + 1][0] if i + 1 < len(marks) else len(html) prv = marks[i - 1][0] if i else 0 after = [t for pos, t in titles if p < pos < nxt] before = [t for pos, t in titles if prv < pos < p] print(f" {sid:>5} after={after[:1]} before={before[-1:]}")skill/motion-design/scripts/remake/BRIEF_TEMPLATE.md2.1 KBe15e64802782upstream ↗
# BRIEF — build agents (frame-locked remake of [REF VIDEO] for [BRAND]) Workdir (absolute): [WORKDIR] · Python: [VENV]/bin/python · page: http://localhost:[PORT]/[DIR]/index.html (server already running). ## Acceptance bar Our render must match REF frame-by-frame in LAYOUT, SIZES, POSITIONS, TIMING, EASING, CAMERA, CUTS, BLUR, CURSOR PATH, TYPING CADENCE when shown side by side in sync ("original | copy" split-screen). Only content is swapped. Target: position/size error ≤1-2% of frame, cuts 0 frames off. Differences allowed only where the swap forces them (word widths) — report each. ## Swap rules (edit per project) - [OLD BRAND] → [BRAND] (CORE.appIcon / CORE.mark), accent colours → brand tokens (CORE.T). - Partner/co-brand marks: never imply a partnership that doesn't exist (e.g. "OpenAI ×" → a true co-mark like "Opus 5.5 ×"). - No photos of real people from REF: replace with logo tiles, cards or neutral shapes of the same size/motion. - Copy must be TRUE for the brand; no invented numbers (mock UI numbers must read as examples). - Never reuse REF music, voice or images. ## File rules Write ONLY shots/<G>.js (IIFE, helpers prefixed <G>_, one SHOT({id,f0,f1,render}) per shot, contiguous range). Pure function of F (CORE.rand, never Math.random/Date/timers). Never edit core.js/index.html/scripts. Scratch in out/<G>/ and measure/<G>_*. ## Method 1. Read SPEC.md + core.js API. 2. MEASURE with numpy on ref/full frames (ink bboxes, typing char count, cursor tip, camera scale/offset, fade timing) → drive motion with CORE.samples. 3. Verify loop per shot: `remake_render.py compare out/<G> <frames…>` (first/last, keyframes, 2 frames into every transition, ≤15 per call); read compare_sheet.jpg; iterate. Never claim a match without viewing ref|ours. 4. Pitfalls: measure text widths only after fonts load (lazy); REF cursor is often not the macOS arrow (draw it from REF); REF whips may be crisp; seeded bursts; check REF's real cut frames (SPEC boundaries are often ±4 frames off). ## Report Table: shot | frames | MATCHES/CLOSE/ROUGH | residual diff | frames that would drift | spec errors.skill/motion-design/scripts/remake/core.js9.1 KB90c7f0d64715upstream ↗
/* core.js — shared, deterministic helpers for the frame-locked remake. Everything is a PURE function of the global frame F (24 fps). No timers, no Date, no Math.random. Shot files register with SHOT({id, f0, f1, render(lf, F)}) and return an HTML string for the 1920x1080 stage. */ (function () { const FPS = 24, W = 1920, H = 1080; const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x)); const lerp = (a, b, t) => a + (b - a) * t; const inv = (a, b, x) => clamp((x - a) / (b - a)); // ---- easing set const E = { lin: t => t, inQ: t => t * t, outQ: t => 1 - (1 - t) * (1 - t), ioQ: t => t < .5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2, inC: t => t * t * t, outC: t => 1 - Math.pow(1 - t, 3), ioC: t => t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2, outQuart: t => 1 - Math.pow(1 - t, 4), ioQuart: t => t < .5 ? 8 * t ** 4 : 1 - Math.pow(-2 * t + 2, 4) / 2, outExpo: t => t >= 1 ? 1 : 1 - Math.pow(2, -10 * t), ioExpo: t => t <= 0 ? 0 : t >= 1 ? 1 : t < .5 ? Math.pow(2, 20 * t - 10) / 2 : (2 - Math.pow(2, -20 * t + 10)) / 2, outBack: t => { const c = 1.70158, c3 = c + 1; return 1 + c3 * Math.pow(t - 1, 3) + c * Math.pow(t - 1, 2); }, }; // spring (closed form, underdamped) from 0 -> 1, tau in frames const spring = (tau, f = 2.2, z = 0.55) => { if (tau <= 0) return 0; const t = tau / FPS; const w = 2 * Math.PI * f; return 1 - Math.exp(-z * w * t) * Math.cos(w * Math.sqrt(1 - z * z) * t); }; // kf(F, [[f, v], [f, v], ...], ease|easeArray) -> piecewise interpolation, holds ends function kf(F, keys, ease = E.ioC) { if (F <= keys[0][0]) return keys[0][1]; for (let i = 1; i < keys.length; i++) { if (F <= keys[i][0]) { const [f0, v0] = keys[i - 1], [f1, v1] = keys[i]; const e = Array.isArray(ease) ? (ease[i - 1] || E.ioC) : ease; return lerp(v0, v1, e((F - f0) / (f1 - f0))); } } return keys[keys.length - 1][1]; } // samples(F, f0, arr): linear interp inside a per-frame measured array starting at frame f0 function samples(F, f0, arr) { const x = F - f0; if (x <= 0) return arr[0]; if (x >= arr.length - 1) return arr[arr.length - 1]; const i = Math.floor(x), t = x - i; return lerp(arr[i], arr[i + 1], t); } // seeded hash rand in [0,1) const rand = (n, s = 1) => { let x = Math.sin(n * 127.1 + s * 311.7) * 43758.5453; return x - Math.floor(x); }; // ---- brand tokens (Howseen) const T = { bg: '#ffffff', ink: '#0f172a', sub: '#64748b', line: '#e5e7eb', soft: '#f5f7fa', a1: '#38bdf8', a2: '#a78bfa', aDeep: '#0369a1', blue: '#2f7bf5', green: '#22c55e', grad: 'linear-gradient(90deg,#38bdf8 0%,#a78bfa 100%)', font: "'Geist', 'Inter', -apple-system, 'SF Pro Display', Helvetica, Arial, sans-serif", }; const A = n => 'assets/' + n; // asset path // ---- camera: wraps inner HTML, scale around origin + translate, optional blur function camera(inner, { s = 1, tx = 0, ty = 0, ox = W / 2, oy = H / 2, blur = 0, op = 1, dblur = null } = {}) { const f = []; if (blur > 0.01) f.push(`blur(${blur.toFixed(2)}px)`); const filt = f.length ? `filter:${f.join(' ')};` : ''; const db = dblur ? `filter:url(#${dblur});` : ''; return `<div style="position:absolute;inset:0;transform-origin:${ox}px ${oy}px;transform:translate(${tx}px,${ty}px) scale(${s});opacity:${op};${filt}${db}">${inner}</div>`; } // directional motion blur via SVG filter defs; returns [defsHTML, id] function mblurDefs(id, dx, dy) { return `<svg width="0" height="0" style="position:absolute"><filter id="${id}" x="-20%" y="-20%" width="140%" height="140%"><feGaussianBlur stdDeviation="${Math.abs(dx).toFixed(2)} ${Math.abs(dy).toFixed(2)}"/></filter></svg>`; } // ---- cursor (macOS arrow), tip at (x,y); press 0..1 scales down slightly function cursor(x, y, { press = 0, scale = 1, op = 1 } = {}) { const s = scale * (1 - 0.12 * press); return `<svg style="position:absolute;left:${x}px;top:${y}px;transform-origin:0 0;transform:scale(${s});opacity:${op};overflow:visible;z-index:50" width="28" height="40" viewBox="0 0 28 40"> <path d="M2 2 L2 31 L9.5 24 L14.5 36 L19 34 L14 22.5 L24 22.5 Z" fill="#000" stroke="#fff" stroke-width="2" stroke-linejoin="round"/></svg>`; } // ---- text helpers // reveal chars: returns text truncated to n chars (typing) const typed = (s, n) => s.slice(0, Math.max(0, Math.floor(n))); // per-word reveal spans with opacity/blur/y driven by t (0..1) staggered function words(s, t, { stagger = 0.12, dur = 0.35, y = 14, blur = 6, color = null, accent = [] } = {}) { const ws = s.split(' '); return ws.map((w, i) => { const p = clamp((t - i * stagger) / dur); const e = E.outC(p); const col = accent.includes(i) ? `background:${T.grad};-webkit-background-clip:text;background-clip:text;color:transparent;` : (color ? `color:${color};` : ''); return `<span style="display:inline-block;opacity:${e};transform:translateY(${(1 - e) * y}px);filter:blur(${(1 - e) * blur}px);${col}">${w}</span>`; }).join('<span style="display:inline-block;width:.28em"></span>'); } // gradient text span const gtext = s => `<span style="background:${T.grad};-webkit-background-clip:text;background-clip:text;color:transparent">${s}</span>`; // ---- logos // Howseen mark (black glyph PNG used as mask so any fill works) function mark(size, fill = T.ink) { return `<div style="width:${size}px;height:${size}px;background:${fill};-webkit-mask:url(${A('logo-mark.png')}) center/contain no-repeat;mask:url(${A('logo-mark.png')}) center/contain no-repeat"></div>`; } // app icon tile (rounded square with gradient + white mark), like the REF app icon function appIcon(size, { grad = T.grad } = {}) { return `<div style="width:${size}px;height:${size}px;border-radius:${size * .24}px;background:${grad};display:flex;align-items:center;justify-content:center;box-shadow:0 ${size * .06}px ${size * .18}px rgba(56,189,248,.25)">${mark(size * .62, '#fff')}</div>`; } const img = (n, size, extra = '') => `<img src="${A(n)}" style="width:${size}px;height:${size}px;object-fit:contain;${extra}">`; const ENGINES = [['logo-chatgpt-v2.png', 'ChatGPT'], ['logo-gemini.png', 'Gemini'], ['logo-perplexity.png', 'Perplexity'], ['logo-google.png', 'AI Overviews'], ['logo-claude.png', 'Claude']]; // ---- pixel dissolve: grid of squares covering a rect, each square flips at a seeded threshold function pixelDissolve(x, y, w, h, t, { cell = 24, colors = [T.a1, T.a2, '#e0f2fe', '#ede9fe'], seed = 3 } = {}) { const cols = Math.ceil(w / cell), rows = Math.ceil(h / cell); let out = ''; for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) { const k = r * cols + c, th = rand(k, seed); const on = t > th * 0.8 && t < th * 0.8 + 0.35; if (!on) continue; out += `<div style="position:absolute;left:${x + c * cell}px;top:${y + r * cell}px;width:${cell}px;height:${cell}px;background:${colors[k % colors.length]};opacity:${(0.35 + 0.65 * rand(k, seed + 1)).toFixed(2)}"></div>`; } return out; } // ---- palette filter: re-hue any leftover Gojiberry reds/oranges to Howseen sky/violet (applied to final HTML string) function hexToRgb(h) { h = h.replace('#', ''); if (h.length === 3) h = h.split('').map(c => c + c).join(''); const n = parseInt(h, 16); return [n >> 16 & 255, n >> 8 & 255, n & 255]; } function rgbToHsl(r, g, b) { r /= 255; g /= 255; b /= 255; const mx = Math.max(r, g, b), mn = Math.min(r, g, b); let h = 0, s = 0; const l = (mx + mn) / 2; if (mx !== mn) { const d = mx - mn; s = l > .5 ? d / (2 - mx - mn) : d / (mx + mn); h = mx === r ? (g - b) / d + (g < b ? 6 : 0) : mx === g ? (b - r) / d + 2 : (r - g) / d + 4; h /= 6; } return [h * 360, s, l]; } function hslToHex(h, s, l) { h /= 360; const f = n => { const k = (n + h * 12) % 12, a = s * Math.min(l, 1 - l); const c = l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); return Math.round(c * 255).toString(16).padStart(2, '0'); }; return '#' + f(0) + f(8) + f(4); } function paletteFilter(html) { return html.replace(/#[0-9a-fA-F]{6}\b/g, m => { const [r, g, b] = hexToRgb(m); const [h, s, l] = rgbToHsl(r, g, b); if (s > 0.35 && (h < 45 || h > 330)) { const nh = h > 330 || h < 15 ? 262 : 199; return hslToHex(nh, Math.min(s, .9), l); } return m; }); } // ---- registry + seek const SHOTS = []; window.SHOT = def => { SHOTS.push(def); SHOTS.sort((a, b) => a.f0 - b.f0); }; window.CORE = { FPS, W, H, clamp, lerp, inv, E, spring, kf, samples, rand, T, A, camera, mblurDefs, cursor, typed, words, gtext, mark, appIcon, img, ENGINES, pixelDissolve, paletteFilter }; window.seek = t => { const F = Math.round(t * FPS); const st = document.getElementById('stage'); const s = SHOTS.find(x => F >= x.f0 && F < x.f1) || SHOTS[SHOTS.length - 1]; let html = ''; if (s && F >= s.f0 && F < s.f1) { try { html = s.render(F - s.f0, F); } catch (e) { html = `<div style="color:red;font:30px monospace;padding:40px">${s.id} error: ${e}</div>`; console.error(s.id, e); } } else html = `<div style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font:40px monospace;color:#bbb">F${F} — no shot</div>`; st.innerHTML = paletteFilter(html); return F; }; })();skill/motion-design/scripts/remake/index.html1.2 KBd399b2c92ecaupstream ↗
<!doctype html> <html><head><meta charset="utf-8"><title>Howseen remake</title> <style> @font-face{font-family:'Geist';src:url(fonts/geist-latin.woff2) format('woff2');font-weight:100 900;font-display:block} html,body{margin:0;background:#fff} #stage{position:relative;width:1920px;height:1080px;overflow:hidden;background:#fff;font-family:'Geist',-apple-system,Helvetica,Arial,sans-serif;color:#0f172a;-webkit-font-smoothing:antialiased} #stage *{box-sizing:border-box} </style></head> <body><div id="stage"></div> <script src="core.js"></script> <script src="shots/G1.js"></script> <script src="shots/G2.js"></script> <script src="shots/G3.js"></script> <script src="shots/G4.js"></script> <script> (async () => { await document.fonts.load("600 40px Geist"); await document.fonts.ready; const srcs = ['logo-mark.png','logo-chatgpt-v2.png','logo-claude.png','logo-gemini.png','logo-google.png','logo-perplexity.png','shopify.svg','reddit.svg','wordpress.svg','g2.svg','trustpilot.svg']; await Promise.all(srcs.map(s => new Promise(r => { const i = new Image(); i.onload = i.onerror = () => r(); i.src = 'assets/' + s; }))); window.seek(0); window.ready = true; })(); </script></body></html>skill/motion-design/scripts/remake/remake_analyze.py2.1 KB5c29b4d9844dupstream ↗
"""Phase 0: extract all frames + audio, detect cuts by mean-abs-diff spikes, build per-cut contact sheets.""" import subprocess, json from pathlib import Path import numpy as np, imageio_ffmpeg from PIL import Image FF = imageio_ffmpeg.get_ffmpeg_exe() H = Path(__file__).parent ref = H / "ref/reference.mp4" full = H / "ref/full"; full.mkdir(parents=True, exist_ok=True) if not any(full.iterdir()): subprocess.run([FF, "-v", "error", "-i", str(ref), "-start_number", "0", "-q:v", "3", str(full / "f%04d.jpg")], check=True) subprocess.run([FF, "-v", "error", "-y", "-i", str(ref), "-vn", "-ac", "2", "-ar", "48000", str(H / "ref/audio.wav")], check=True) frames = sorted(full.glob("f*.jpg")) print("frames", len(frames)) small = [np.asarray(Image.open(f).convert("L").resize((192, 108)), dtype=np.float32) for f in frames] d = np.array([0.0] + [np.abs(small[i] - small[i - 1]).mean() for i in range(1, len(small))]) np.save(H / "ref/diff.npy", d) # spike = diff much larger than local median cuts = [] for i in range(1, len(d)): lo, hi = max(1, i - 6), min(len(d), i + 7) loc = np.median(np.concatenate([d[lo:i], d[i + 1:hi]])) if hi - lo > 1 else 0 if d[i] > 6 and d[i] > 3.5 * (loc + 0.5): cuts.append(i) print("cuts", cuts) json.dump({"fps": 24, "n": len(frames), "cuts": cuts, "diff": [round(float(x), 2) for x in d]}, open(H / "ref/cuts.json", "w")) # contact sheet: every 6th frame with frame numbers, 2 per second thumbs = [] for i in range(0, len(frames), 6): im = Image.open(frames[i]).resize((256, 144)) thumbs.append((i, im)) cols = 10 from PIL import ImageDraw for page in range(0, len(thumbs), 80): chunk = thumbs[page:page + 80] rows = (len(chunk) + cols - 1) // cols sheet = Image.new("RGB", (cols * 256, rows * 160), "white") dr = ImageDraw.Draw(sheet) for k, (i, im) in enumerate(chunk): x, y = (k % cols) * 256, (k // cols) * 160 sheet.paste(im, (x, y)) dr.text((x + 4, y + 146), f"f{i}" + (" CUT" if i in cuts else ""), fill="red") sheet.save(H / f"ref/sheet/sheet_{page // 80}.jpg", quality=80) print("sheets done")skill/motion-design/scripts/remake/remake_qa.py1.5 KBc191388a35adupstream ↗
"""QA sheets: ref|ours per second (2 pages) + group seams (last 2 / first 2 frames) + old-brand colour scan.""" from pathlib import Path import numpy as np from PIL import Image, ImageDraw H = Path(__file__).parent Q = H / "out/qa"; Q.mkdir(parents=True, exist_ok=True) def pair(F): r = Image.open(H / f"ref/full/f{F:04d}.jpg").convert("RGB").resize((480, 270)) o = Image.open(H / f"out/full/o_f{F:04d}.png").convert("RGB").resize((480, 270)) c = Image.new("RGB", (970, 290), "white"); c.paste(r, (0, 20)); c.paste(o, (490, 20)) ImageDraw.Draw(c).text((4, 4), f"F{F}", fill="red"); return c def sheet(frames, name, cols=3): tiles = [pair(F) for F in frames]; rows = -(-len(tiles) // cols) s = Image.new("RGB", (cols * 970, rows * 290), "white") for i, t in enumerate(tiles): s.paste(t, ((i % cols) * 970, (i // cols) * 290)) s.save(Q / name, quality=78) secs = list(range(0, 1557, 24)) sheet(secs[:33], "persec_1.jpg"); sheet(secs[33:], "persec_2.jpg") sheet([526, 527, 528, 529, 902, 903, 904, 905, 906, 907, 1152, 1153, 1154, 1155], "seams.jpg", cols=2) # old-brand colour scan: reddish/orange saturated pixels in ours bad = [] for F in range(0, 1557, 4): a = np.asarray(Image.open(H / f"out/full/o_f{F:04d}.png").convert("RGB").resize((480, 270)), dtype=np.int16) r, g, b = a[..., 0], a[..., 1], a[..., 2] m = (r > 180) & (r - g > 60) & (r - b > 60) & (g > 60) if m.sum() > 150: bad.append((F, int(m.sum()))) print("old-brand-colour frames:", bad[:40], "count", len(bad))skill/motion-design/scripts/remake/remake_render.py3.2 KB37cadb4525bdupstream ↗
"""render.py — Playwright renderer for the frame-locked remake. usage: render.py stills OUT F1 F2 ... -> OUT/o_FNNNN.png render.py compare OUT F1 F2 ... -> OUT/c_FNNNN.jpg (ref | ours, labelled) + OUT/compare_sheet.jpg render.py full OUT F0 F1 -> OUT/fNNNN.png for F0 <= F < F1 Use a separate OUT dir per agent (e.g. out/G2) so parallel runs never collide. Max ~15 frames per call for stills/compare. """ import asyncio, sys, subprocess from pathlib import Path from PIL import Image, ImageDraw, ImageFont import imageio_ffmpeg from playwright.async_api import async_playwright H = Path(__file__).parent FF = imageio_ffmpeg.get_ffmpeg_exe() import os URL = os.environ.get("REMAKE_URL", "http://localhost:8768/remake/index.html") # set REMAKE_URL to your served index.html FPS = 24 async def run(frames, out: Path, fmt="png"): out.mkdir(parents=True, exist_ok=True) async with async_playwright() as p: b = await p.chromium.launch(args=["--disable-gpu-vsync", "--font-render-hinting=none"]) 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 == "error" else None) await pg.goto(URL) await pg.wait_for_function("window.ready === true", timeout=120000) el = await pg.query_selector("#stage") paths = [] for F in frames: await pg.evaluate(f"window.seek({F / FPS + 1e-6})") await pg.evaluate("new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))") pth = out / f"o_f{F:04d}.png" await el.screenshot(path=str(pth)) paths.append(pth) await b.close() if errs: print("PAGE ERRORS:", errs[:10]) return paths def compare(frames, out: Path): paths = asyncio.run(run(frames, out)) try: font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 34) except Exception: font = ImageFont.load_default() tiles = [] for F, p in zip(frames, paths): ref = Image.open(H / f"ref/full/f{F:04d}.jpg").convert("RGB").resize((960, 540)) ours = Image.open(p).convert("RGB").resize((960, 540)) c = Image.new("RGB", (1930, 590), "white"); c.paste(ref, (0, 50)); c.paste(ours, (970, 50)) d = ImageDraw.Draw(c); d.text((10, 8), f"REF f{F}", fill="red", font=font); d.text((980, 8), f"OURS f{F}", fill="blue", font=font) cp = out / f"c_f{F:04d}.jpg"; c.save(cp, quality=85); tiles.append(c) cols = 2; rows = -(-len(tiles) // cols) sheet = Image.new("RGB", (cols * 965, rows * 295), "white") for i, t in enumerate(tiles): sheet.paste(t.resize((965, 295)), ((i % cols) * 965, (i // cols) * 295)) sheet.save(out / "compare_sheet.jpg", quality=80) print("compare ->", out / "compare_sheet.jpg") if __name__ == "__main__": mode, out = sys.argv[1], H / sys.argv[2] nums = [int(x) for x in sys.argv[3:]] if mode == "stills": asyncio.run(run(nums, out)); print("stills ->", out) elif mode == "compare": compare(nums, out) elif mode == "full": asyncio.run(run(list(range(nums[0], nums[1])), out)); print("full", nums, "->", out)skill/motion-design/scripts/remake/remake_stub.py627 B10098a114f29upstream ↗
from pathlib import Path H = Path(__file__).parent groups = {"G1": (0, 528), "G2": (528, 906), "G3": (906, 1154), "G4": (1154, 1557)} for g, (a, b) in groups.items(): p = H / f"shots/{g}.js" if not p.exists(): p.write_text(f"""(function () {{ const C = CORE; // {g}: frames {a}-{b}. Replace this placeholder with real shots (SHOT per shot id). SHOT({{ id: '{g}_placeholder', f0: {a}, f1: {b}, render: (lf, F) => `<div style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font:48px Geist;color:#94a3b8">{g} · F${{F}}</div>` }}); }})(); """) print("stub", g)skill/motion-design/scripts/remake/remake_sync.py2.5 KB6e3fd3570a21upstream ↗
"""sync.py — build the deliverables from full-render frames in out/full/o_fNNNN.png. sync.py encode -> out/remake_silent.mp4 (24 fps, h264 BT.709) and out/remake.mp4 (muxed with out/mix.wav if present) sync.py split -> out/split_screen.mp4 : REF left | OURS right, labelled "original" / "opus 5.5 copy", white bg (the X post format) sync.py stacked -> out/sync_check.mp4 : REF top / OURS bottom, frame-locked, for QA """ import subprocess, sys from pathlib import Path import imageio_ffmpeg H = Path(__file__).parent FF = imageio_ffmpeg.get_ffmpeg_exe() OUT = H / "out"; FULL = OUT / "full"; REF = H / "ref/reference.mp4" ENC = ["-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "16", "-preset", "slow", "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-movflags", "+faststart"] mode = sys.argv[1] if mode == "encode": subprocess.run([FF, "-v", "error", "-y", "-framerate", "24", "-i", str(FULL / "o_f%04d.png"), *ENC, str(OUT / "remake_silent.mp4")], check=True) mix = OUT / "mix.wav" if mix.exists(): subprocess.run([FF, "-v", "error", "-y", "-i", str(OUT / "remake_silent.mp4"), "-i", str(mix), "-c:v", "copy", "-c:a", "aac", "-b:a", "256k", "-shortest", "-movflags", "+faststart", str(OUT / "remake.mp4")], check=True) print("encoded") elif mode == "split": font = "/System/Library/Fonts/Helvetica.ttc" lab = lambda txt, x: f"drawbox=x={x}:y=246:w={len(txt) * 13 + 24}:h=34:color=black@1:t=fill,drawtext=fontfile={font}:text='{txt}':x={x + 12}:y=253:fontsize=22:fontcolor=white" vf = ("[0:v]scale=880:-2,pad=920:496:0:0:0xF3F4F6[a];[1:v]scale=880:-2,pad=880:496:0:0:white[b];" "[a][b]hstack=inputs=2:shortest=1,pad=1920:1080:60:292:0xF3F4F6[s];" f"[s]{lab('original', 60)},{lab('opus 5.5 copy', 980)},setsar=1[v]") src = OUT / ("remake.mp4" if (OUT / "remake.mp4").exists() else "remake_silent.mp4") audio = ["-map", "1:a?"] if (OUT / "remake.mp4").exists() else [] subprocess.run([FF, "-v", "error", "-y", "-i", str(REF), "-i", str(src), "-filter_complex", vf, "-map", "[v]", *audio, *ENC, "-c:a", "aac", "-b:a", "256k", str(OUT / "split_screen.mp4")], check=True) print("split ->", OUT / "split_screen.mp4") elif mode == "stacked": src = OUT / "remake_silent.mp4" subprocess.run([FF, "-v", "error", "-y", "-i", str(REF), "-i", str(src), "-filter_complex", "[0:v]scale=960:540[a];[1:v]scale=960:540[b];[a][b]vstack=inputs=2:shortest=1[v]", "-map", "[v]", *ENC, str(OUT / "sync_check.mp4")], check=True) print("stacked ->", OUT / "sync_check.mp4")skill/motion-design/scripts/render_template.py8.0 KB81638c1c05a0upstream ↗
"""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, sys from pathlib import Path import numpy as np import imageio_ffmpeg from playwright.async_api import async_playwright HERE = Path(__file__).parent FF = imageio_ffmpeg.get_ffmpeg_exe() 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=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, errs async 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 {})) def sheet(folder, pattern, n, out, cols=4, size=360): rows = -(-n // cols) subprocess.run([FF, "-v", "error", "-y", "-i", str(folder / pattern), "-vf", f"scale={size}:-1,tile={cols}x{rows}:padding=6:color=white", "-frames:v", "1", str(out)], check=True) async def probe(times, name="sheet.png", cols=4): out = HERE / "probe"; shutil.rmtree(out, ignore_errors=True); out.mkdir() async with async_playwright() as p: b, pg, errs = await open_page(p) for i, t in enumerate(times): await shot(pg, t, out / f"p_{i:02d}.png") await b.close() if errs: print("PAGE ERRORS:", errs[:8]) sheet(out, "p_%02d.png", len(times), out / name, cols=cols) print("probe:", len(times), "->", out / name) 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) * 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-4 await shot(pg, t, sub / f"s_{k:05d}.jpg", "jpeg"); k += 1 if i % 60 == 0: print(f"frame {i}/{n}", flush=True) 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 * 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/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/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).stdout fr = np.frombuffer(raw, np.uint8).reshape(-1, 180, 180).astype(np.float32) d = np.abs(np.diff(fr, axis=0)).mean(axis=(1, 2)) hits = [] for i in range(1, len(d) - 1): nb = max(d[i - 1], d[i + 1], 0.3) 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 * 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()skill/motion-design/scripts/svgl_logos.py1.2 KBd4b92843bcddupstream ↗
"""Download colour SVG logos from svgl.app for sources + CMS into h20/assets/svg/.""" import json, urllib.parse, urllib.request from pathlib import Path OUT = Path("assets/svg"); OUT.mkdir(parents=True, exist_ok=True) UA = {"User-Agent": "Mozilla/5.0"} WANT = {"youtube": "youtube", "reddit": "reddit", "trustpilot": "trustpilot", "wikipedia": "wikipedia", "linkedin": "linkedin", "shopify": "shopify", "wordpress": "wordpress", "webflow": "webflow", "wix": "wix", "ghost": "ghost", "bigcommerce": "bigcommerce", "framer": "framer", "nextjs": "next"} for name, q in WANT.items(): try: res = json.loads(urllib.request.urlopen(urllib.request.Request("https://api.svgl.app?search=" + urllib.parse.quote(q), headers=UA), timeout=30).read()) except Exception as e: print(name, "ERR", e); continue pick = next((r for r in res if r["title"].lower().replace(".", "").startswith(q.replace(".", ""))), res[0] if res else None) if not pick: print(name, "none"); continue route = pick["route"] if isinstance(pick["route"], str) else pick["route"].get("light") (OUT / f"{name}.svg").write_bytes(urllib.request.urlopen(urllib.request.Request(route, headers=UA), timeout=30).read()) print(name, "<-", pick["title"], route)README.mdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
Plain-text copy, no login: /skill-bundles/howseen-ai-claude-motion-design-skill-motion-design.md