⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
khan-explainer
Use when the user wants a Khan Academy style explainer video, a blackboard or whiteboard lesson, a hand-drawn chalk-talk animation, a short narrated video that teaches a concept ("explain X in a video", "explainer video", "teach X in 30 seconds"), or a tutorial that draws hand-written arrows, circles and captions over product screenshots ("draw over the UI", "annotated walkthrough"), or clips cut from a YouTube video or podcast where the speaker's real audio plays under a blackboard drawn to it
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
khan-explainer
A Claude Code skill that makes Khan Academy style explainer videos: a pen draws while a voice explains. You describe the video, Claude writes a scene file, and one command renders the MP4.
Write-up: Claude Code skills for content: how I make Khan Academy style videos for free

It runs on your Mac with an HTML canvas, Playwright, ffmpeg and the built-in say voice. No API keys, no accounts, no editor.
What it makes
| Mode | What you get |
|---|---|
| Blackboard lesson | A diagram drawn stroke by stroke while the voice explains it. |
| Draw-over-UI tutorial | Arrows, circles and numbered steps drawn over your product screenshots. |
| Real-audio clip | A YouTube video or podcast in, vertical shorts out. The speaker's own voice plays while the board is drawn to their words. It can also cut the speaker out and stand them in front of the board. |
Every mode renders as chalk on a blackboard or marker on a whiteboard, landscape or vertical. One flag switches between them, and a single beat can flip the board mid-video.
Why the pen stays in sync
The voice drives the clock. A scene is a list of beats, and a beat is one spoken clause plus the drawing that happens while it is said. The renderer speaks each beat first, measures it, and fits that beat's drawing to its length. Nobody types a timestamp, so the pen cannot run ahead of the words.
scene({
beats: [
{ say: 'What is an AI agent?', draw: p => {
write('What is an AI agent?', 60, 85, p, { size: 56, color: C.yellow });
} },
{ say: "It's software that uses a language model to think,", draw: p => {
stroke(oval(300, 330, 155, 82), seg(p, 0, .4), { color: C.blue });
write('1. THINK', 300, 328, seg(p, .4, 1), { size: 40, color: C.blue, center: true });
} },
],
})
Install
You need macOS, Node 20 or newer, and ffmpeg (brew install ffmpeg).
git clone https://github.com/haiderfarooq3/khan-explainer ~/.claude/skills/khan-explainer
cd ~/.claude/skills/khan-explainer/scripts && npm install && npx playwright install chromium
Use
Ask Claude Code for the video you want:
Make a 30-second Khan-style explainer on how DNS works.
Draw over these screenshots and show a new user how to send their first invoice.
Khanify this YouTube video: find the best moments and clip them, light and dark.
Or render one of the examples yourself:
cd ~/.claude/skills/khan-explainer
node scripts/render.js examples/ai-agents.js agents.mp4 # blackboard
KHAN_THEME=light node scripts/render.js examples/ai-agents.js light.mp4 # whiteboard
node scripts/render.js examples/ui-tutorial.js tutorial.mp4 # drawn over screenshots
node scripts/render.js examples/arabic.js arabic.mp4 # right-to-left writing
node scripts/render.js examples/languages.js languages.mp4 # one word in eight languages
Each render also prints the path of a contact sheet: the board at the end of every beat, in one image. That sheet is how Claude checks its own layout before it shows you anything.
SKILL.md is the full reference: the scene API, layout rules, the capture recipe for tutorials and the clip pipeline.
Optional extras
- A human voice. Export
ELEVENLABS_API_KEYand addeleven: '<voice id>'to a scene. The script is read in one take and cut back into beats, and takes are cached, so re-rendering the same words is free. - Kokoro, a free local human voice.
pip install kokoro soundfile, thenkokoro: trueon a scene orKHAN_TTS=kokorofor any scene. English, Spanish, French, Hindi, Italian, Japanese, Portuguese and Chinese. - Any language on the board. Arabic, Urdu and Hebrew are written right to left, Hindi, Thai, Chinese, Japanese, Korean, Russian and more left to right, each in a face that writes it properly.
lang: 'ar'on a scene picks the matching voice.node tests/run.jsrenders them all. - Real-audio clips need uv.
scripts/clip_audio.pytranscribes locally with faster-whisper. - The talking-head cutout uses macOS Vision. It builds itself with
swiftcthe first time, which needs the Xcode command line tools.
Credits
Made by Haider Farooq. MIT licensed: use it, change it, ship videos with it.
Not affiliated with or endorsed by Khan Academy. "Khan Academy style" describes the look: handwriting on a board, drawn as it is explained.
// HOW IT'S BUILT
// FILES
38 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
SKILL.md20 KBe97f57f77806upstream ↗
--- name: khan-explainer description: Use when the user wants a Khan Academy style explainer video, a blackboard or whiteboard lesson, a hand-drawn chalk-talk animation, a short narrated video that teaches a concept ("explain X in a video", "explainer video", "teach X in 30 seconds"), or a tutorial that draws hand-written arrows, circles and captions over product screenshots ("draw over the UI", "annotated walkthrough"), or clips cut from a YouTube video or podcast where the speaker's real audio plays under a blackboard drawn to it ("khanify this video", "clip this with the Khan visual"), especially when it must be free, local, and use no paid APIs or keys. macOS only. --- # Khan Explainer A pen draws while a voice explains. Three modes, one renderer: - **Blackboard lesson.** A diagram drawn on a black board, Khan Academy style. - **Draw-over-UI tutorial.** Arrows, circles and numbered captions drawn over product screenshots. - **Real-audio clip.** A real person's voice, cut from a video, with the board drawn to their words. See "Real-audio clips". One scene file in, one MP4 out, in seconds. Free and local: HTML canvas, Playwright, macOS `say`, ffmpeg. No keys. Every mode renders as chalk on a blackboard or marker on a whiteboard, landscape or vertical. Made by Haider Farooq ([github.com/haiderfarooq3](https://github.com/haiderfarooq3/khan-explainer)). Free for anyone to use and change (MIT). **Core principle: the voice drives the clock.** A scene is a list of beats. A beat is one spoken clause plus the drawing that happens while it is said. The renderer speaks each beat first, measures it, and fits that beat's drawing to it. Never hardcode seconds or guess when a word lands. ## Workflow 1. **Script the beats.** One idea per beat, split at commas and full stops. Check the length formula below. 2. **Plan the picture.** Lesson: lay out the whole board. Tutorial: capture the stills and their rectangles. Each has a section below. 3. **Write `scene.js`** in a scratch folder. Copy `examples/ai-agents.js` for a lesson or `examples/ui-tutorial.js` for a tutorial. 4. **Render:** `node ~/.claude/skills/khan-explainer/scripts/render.js scene.js out.mp4` 5. **Read the `sheet` image it prints.** It shows the board at the end of every beat. The same folder holds every beat full-size as `b000.jpg`, `b001.jpg` and so on. Open those to check that a ring really sits on a small button. Fix every `WARN` (text off the board, or one label on another), overlap and spill, then re-render. A render takes seconds, so iterate. 6. Deliver the MP4 and say which voice it used. Each output line is `beat N start +duration`. The sheet path is new on every render. First run on a machine: `cd scripts && npm install && npx playwright install chromium`. ## Length and pace | Pace | Settings | Seconds, roughly | |---|---|---| | Quick explainer | defaults: `rate: 170`, `gap: 0.15` | words ÷ 3 + beats × 0.15 + 1.3 | | Tutorial | `rate: 150, gap: 0.6` | words ÷ 2.9 + beats × 0.6 + 1.3 | A 10-second explainer is about 24 words in 5 beats. A 60-second tutorial is about 145 words in 15 beats. The formula lands within about 5%, and the render prints the real length. To hit a target, change the words, not `rate`. Use the tutorial pace whenever the viewer has to find something on a screen. The quick pace feels rushed there. ## Scene API ```js scene({ voice: 'Samantha', rate: 170, size: [1280, 720], // all optional. [720, 1280] = vertical lang: 'ar', // the language spoken: picks the voice (see "Other languages") gap: 0.15, dim: 0.2, // seconds between beats; screenshot darkening theme: 'light', // whiteboard and marker. Leave it out for the blackboard. beats: [ { say: 'Spoken clause.', draw: p => { /* p runs 0 to 1 while it is spoken */ } }, { dur: 1.5, draw: p => {} }, // silent beat, in seconds { clear: true, say: 'Next idea.', draw: p => {} }, // wipes the board first { bg: 'shots/home.png', say: 'Start here.', draw: p => {} }, // screenshot as the board { theme: 'dark', say: 'Lights off.', draw: p => {} } // flips the board from this beat on // With `audio: 'audio.wav'` on the scene, nothing is spoken by the computer: each beat takes // `at: 12.4` (seconds into that file) and `say` is only a note. See "Real-audio clips". ], }) ``` Every draw call is `(geometry, p, style)`. Points are `[x, y]` in board units. | Call | Draws | |---|---| | `write(str, x, y, p, {size, color, center, lang})` | Handwriting, letter by letter. `y` is the baseline. Arabic, Urdu and Hebrew run left from `x`. | | `stroke(points, p, {color, width})` | Any shape, drawn progressively. | | `arrow(from, to, p, {color, ctrl})` | Arrow. `ctrl` is a point that bends it. | | `check(x, y, p, {size, color})` | Tick mark. | | `line(a, b)` `curve(a, b, ctrl)` `oval(cx, cy, rx, ry)` `box(x, y, w, h)` | Return points for `stroke`. | | `ring(rect, pad)` `around(rect, pad)` | An oval or a frame around a `{x, y, w, h}` rectangle, for `stroke`. | | `view(captureWidth, cropTop)` | Maps screenshot positions to the board. `.r(rect)` for a rectangle, `.p(x, y)` for a point. | | `seg(p, from, to)` | A slice of the beat, to order strokes: `seg(p, 0, .4)` then `seg(p, .4, 1)`. | | `C.yellow` `blue` `orange` `pink` `green` `red` `purple` `white` | Chalk colours. On the whiteboard the same names are marker inks, and `white` is black. | Text width is about `0.45 × size` per character for a normal label and `0.63 × size` per capital. Work it out before placing a label beside anything. ## Other languages `write` takes any script and writes it the way that script is written by hand. The first letter of the string decides the direction; its script picks the face. | Script | Direction | Set in | Width per letter, roughly | |---|---|---|---| | Arabic, Persian | right to left | naskh, regular weight | `0.3–0.5 × size` (vowel marks add none). Give it about twice a Latin label's size. | | Urdu | right to left | nastaliq: letters slope down to the left and stack about `1.6 × size` tall | `0.5 × size`. Keep it near `0.7×` a Latin size and leave a tall line. | | Hebrew | right to left | regular weight, points (niqqud) kept | `0.65 × size` | | Hindi, Bengali, Tamil and other Indic | left to right, hung from a headline | regular weight | `0.7–0.9 × size` per syllable | | Thai, Lao, Khmer, Burmese | left to right, no spaces between words | looped, regular weight | `0.6 × size` | | Chinese, Japanese, Korean | left to right, one square per character | bold | `1.0 × size` per character | | Cyrillic, Greek | left to right | bold | `0.65 × size` | - **Right-to-left text.** `x` is the right end of the text, where the pen starts (the centre with `center: true`), and the word is uncovered right to left. - **Shaped, not sliced.** Every non-Latin string is shaped once as a whole and uncovered in writing order, so joined Arabic letters keep their forms, a vowel mark stays on its letter, and a Hindi vowel sign that sits before its consonant appears with it. - **Urdu.** It shares Arabic's letters, so `write` spots it only by a letter Arabic does not use (ٹ ڈ ڑ ں ہ ھ ے). Put `lang: 'ur'` on the scene or on the call to be sure of the nastaliq hand. - **Mixed labels.** A Latin label that quotes a foreign word keeps the handwriting and runs left to right; the quoted word is set in its own script's face. - **The voice.** `lang` on the scene picks the built-in voice: `ar` Majed, `he` Carmit, `hi` Lekha, `zh` Tingting, `ja` Kyoko, `ko` Yuna, `th` Kanya, `ru` Milena, `el` Melina, `tr` Yelda, `id` Damayanti, `es` Mónica, `fr` Thomas, `de` Anna, `it` Alice, `pt` Luciana, `bn` Piya, `ta` Vani, `te` Geeta, `kn` Soumya, `uk` Lesya, `vi` Linh, `pl` Zosia, `nl` Xander, `sv` Alva, `ms` Amira. A missing voice stops the render with where to download it. macOS has no voice for Urdu or Persian: use `eleven` (its multilingual model speaks them) or `audio`. An English scene can still show foreign words: then `say` spells the sound ("kitaab") and the board shows the word. - The off-board and overlap warnings measure the ink, not the letter count, so a long nastaliq swash or a tall stack of marks still warns. See `examples/arabic.js` (an Arabic lesson) and `examples/languages.js` (one word in eight languages). `node tests/run.js` renders every example and the same short scene in fifteen languages (`tests/languages/`), and fails on any warning. `node tests/fonts.js` prints which face each script gets on this machine: a Mac face, a Noto face, or none. ## Light and dark The board is a blackboard unless told otherwise. Three ways to change that: - `theme: 'light'` on the scene: a whiteboard, with the colour names mapped to marker inks. - `KHAN_THEME=light node scripts/render.js scene.js out-light.mp4`: re-skins a finished scene without editing it. - `theme` on a beat: flips the board from that beat on. The ink already on it changes colour with it. Read `C.blue` inside `draw`, never into a variable at the top of the file, or it keeps the first theme's colour. On a white board every hard edge shows, so look at the light sheet separately from the dark one. ## A human voice (optional) `say` is free and robotic. For a human voice, export `ELEVENLABS_API_KEY` and name a voice on the scene: ```js scene({ eleven: '<voice id>', beats: [...] }) scene({ eleven: { voice: '<voice id>', model: 'eleven_multilingual_v2', settings: { speed: 1.1 } }, beats: [...] }) ``` - The whole script is read in one take and cut back into beats at the character times ElevenLabs returns. It sounds like one person talking, and the pen still follows every clause. - `gap` defaults to 0 here, because the take has its own pauses. At `speed: 1.1` expect about 3.3 words a second. - Takes are cached in `.voice/` beside the scene. Re-rendering the same words is free, so lay the board out with `say` first, then switch the voice on and change only drawings. - Changing any `say` buys a new take of the whole script. **Kokoro: a free local human voice.** `pip install kokoro soundfile` once (for Japanese add `"misaki[ja]"` and run `python -m unidic download`; for Chinese add `"misaki[zh]"`), then put `kokoro: true` on the scene, or a voice name (`kokoro: 'am_michael'`), or `{ voice, speed }`. `KHAN_TTS=kokoro` tries it on any scene without editing it. It speaks English, Spanish, French, Hindi, Italian, Japanese, Portuguese and Chinese, and `lang` picks its voice. For Arabic, Urdu, Hebrew and the rest, `KHAN_TTS` leaves the built-in voice on; use `eleven` for a human voice there. The model downloads on first use (about 330 MB), then runs offline. Takes are cached in `.voice/kokoro/`. `KHAN_PYTHON` names the Python that has it installed. ## Blackboard lessons - **Lay out the whole board before writing code.** 1280×720 units, 60 margin, title top-left. List each shape's centre and size for every beat, including the last, so the finished board fills the width instead of crowding one side. - One colour per concept, reused whenever that concept returns. - Draw what is being said as it is said. Never reveal a finished diagram. - Diagrams and short labels only. No sentences on the board, no logos, no stock images. - Talk like a tutor: plain words, "so", "now", "let's say". No term the board has not introduced. - Exaggerate scale. If two things differ, draw the difference big enough to see at a glance. - The board accumulates. Add `clear: true` only when it is full, roughly every 5–6 beats. ## Draw-over-UI tutorials `bg` puts a screenshot on the board from that beat on and wipes earlier ink. Paths are relative to the scene file. Repeat the same `bg` on a later beat to wipe the annotations and mark up that screen again. `clear: true` takes the screenshot away as well, back to the plain board. `dim` darkens screenshots so the chalk reads, and a beat can override it, for example `dim: 0` on a showcase image. **Capture.** Pick the path that fits: | Situation | Capture with | Coordinates | |---|---|---| | Public page, or a script can sign in | Playwright, `viewport: {width: 1280, height: 720}, deviceScaleFactor: 1.5` | CSS pixels are board units. Use them as they are, or through `view(1280)`. | | Needs the user's own logged-in browser, or video previews a bundled browser cannot play | A full screenshot in that browser, cropped to 16:9 | `view(captureWidth, cropTop)` | For the second path, crop with ffmpeg. A 1440×900 window at 2× density, cut 90 CSS pixels from the top: ``` ffmpeg -i full.png -vf "crop=2880:1620:0:180,scale=1920:1080" shot.png ``` While capturing: - Save `getBoundingClientRect()` for every target. Never read coordinates off the image. - Measure again for every state, after it settles. Elements move and resize when focused or typed into, and menus open over the page. - Match the capture to the board: the app's dark theme for the blackboard, its light theme for the whiteboard. Put the setting back afterwards. Only one theme available: see `dim` under Build. - Hide private data in the page first (`visibility: hidden` on the nodes), then look at every still. A broad rule hides things you need: "anything near the top" also matches content scrolled above the viewport. - Capture progress states while they exist. They collapse when the job ends. - Never post in a shared or public space to stage a demo. Use existing results, or one cheap run in a private space the user has agreed to. **Build.** - Pass rectangles through `view()` into `ring` or `around`. Place labels in board units, in empty areas of the screen. - Number the steps in the labels: "1. Describe it", "2. Send". - Give anything a first-timer finds strange its own screen: progress lines, tool calls, a stop button. - Every beat adds something new to the picture. A beat that redraws the last ring in another colour is dead air. - Chalk needs a dark surface and marker a light one. `dim` washes the screenshot towards the board's colour: on a mismatched or crowded screen, raise it to about `0.55` so the ink reads. - End on the result, not the setup. ## Real-audio clips A YouTube video or podcast in, a folder of vertical shorts out: the speaker's own audio, our board. Still free and local. `scripts/clip_audio.py` does the transcribing and cutting. 1. **Get the audio.** The system `yt-dlp` goes stale and YouTube answers 403 or a bot check, so run the newest one: `uvx --from 'yt-dlp[default]@latest' yt-dlp --cookies-from-browser chrome -f "bestaudio[ext=m4a]/bestaudio" -o "src.%(ext)s" <url>` 2. **Transcribe.** `uvx --with faster-whisper python scripts/clip_audio.py transcribe src.m4a work` writes `work/transcript.txt`, one timed line per sentence. About 3 minutes for a 20-minute video. 3. **Pick the moments.** Read the whole transcript. A usable clip is 20 to 60 seconds, starts on a sentence that needs no earlier context, makes one point, and ends on its punchline. Skip sponsor reads, workshop plugs and outros. Write `clips.json` with each clip's first and last line times. 4. **Cut.** `... clip_audio.py cut src.m4a work clips.json` writes `work/clips/NN-slug/audio.wav` and `words.txt`. Every cut is transcribed again, so `words.txt` holds word times inside the clip. Fix any line marked `CHECK` before drawing: the cut caught a stray word or lost one. 5. **Draw.** One `scene.js` per clip folder: ```js scene({ size: [720, 1280], audio: 'audio.wav', // vertical; the recording is the clock beats: [ { at: 0, say: 'note of what he says', draw: p => {} }, // `at` = seconds, read from words.txt { at: 4.44, say: 'next phrase', draw: p => {} }, // a beat lasts until the next `at` ], }) ``` - `at` comes from `words.txt`, never from a guess. To land a word inside a beat, `seg` takes `(wordTime - at) / (nextAt - at)`. - Ink appears as the words are said or just after, never before. - Vertical board: 720 x 1280. Keep ink inside x 50..670 and y 150..1010, because phone UI covers the rest. Title 52 to 60, labels 40 to 50, nothing below 28. - Beat 1 writes a 2 to 5 word title naming the clip's point. Add something every 3 to 4 seconds. `clear: true` every 12 to 20 seconds. End on the punchline, written big. - Draw only what is said in that clip, with the numbers as spoken. Keep swearing, logos and real faces off the board. - The sheet tiles a vertical board six across. Open the last frame of each board full-size. **Both looks.** Render every clip twice, once plain and once with `KHAN_THEME=light` (see "Light and dark"). The scene does not change. **Talking head (TikTok green-screen look).** `scripts/cutout` (source `cutout.swift`, build with `swiftc -O cutout.swift -o cutout`) lifts the speaker off their background with macOS Vision: raw BGRA frames in, the same frames out with the matte as alpha. It hides itself on b-roll (no face to camera) and fades the bottom rows. `scripts/talking_head_example.sh <clip-folder> <source-video> [light]` is the working recipe: cut out once per clip into a ProRes 4444 `cutout.mov`, shrink the board to the top of the frame, overlay the speaker at the bottom with soft side edges. - Set `CROP` (w:h:x:y) to where the speaker sits in the source frame, above any captions the editor burned onto their chest, and check a frame from every clip. - Never edit a script while a batch is running it: bash reads the file as it goes and the in-flight runs break. For many clips, finish one as the worked example, write the rules above into a brief, and give each parallel agent three clip folders plus that brief and the example. ## Common mistakes | Mistake | Fix | |---|---| | Label wider than its oval or box | Work out the width from the rule above. Widen the shape or shorten the label. | | One long sentence in one beat | The pen crawls. Split it into clauses. | | Splitting a beat mid-clause | Each beat is a separate take, so it sounds choppy. Split at punctuation. | | Emoji, ticks or arrow glyphs in `write` | The font lacks them. Draw them with `stroke`, as `check` does. Keyboard symbols such as `$ % + !` are fine. | | An arrow pointing at something not drawn yet | It points at empty space until a later beat. Aim arrows only at what is already on the board. | | An arrow drawn through a label | Start it from the side of the label that faces the target. | | A key word drawn early in a long beat | `p` spans the whole beat. Use `seg` to place the stroke where the word falls, or split the beat. | | A mispronounced word or a number | Respell it in `say` only ("one hundred ten"). Keep the written label correct ("$110"). | | Old annotations still on screen | Ink carries over until a beat has `bg` or `clear`. Repeat the `bg` to start clean on the same screenshot; `clear` goes back to the plain board. | | Calling your own variable `box`, `line`, `ring` or `check` | It hides the helper of that name inside your scene. Name rectangles after the thing: `searchBox`, `sendBtn`. | | Converting screenshot coordinates by hand | Use `view()`. Hand arithmetic is where rings miss buttons. | | Arabic or Hebrew placed by its left edge | For right-to-left text `x` is the right end. Use `center: true` to place it by its middle. | | Urdu written in naskh | Add `lang: 'ur'` to the scene. Without an Urdu-only letter the text looks Arabic. | | A sentence in another language read by the English voice | Set `lang` on the scene so the matching voice reads it. | | Skipping the sheet | Coordinates are written blind. The sheet is the only check. | | A real-audio beat timed by ear or by sentence length | Read `at` from `words.txt`. A guess drifts and the pen runs ahead of the voice. | ## Limits Built for macOS. On Linux the free voice falls back to espeak-ng (`apt install espeak-ng`), which speaks about a hundred languages but sounds rougher still; install the Noto fonts for the scripts you write. The free voice is robotic: use `eleven` or real audio when the voice matters. `tts()` in `scripts/render.js` is the one place to swap in another engine.skills/khan-explainer/SKILL.md20 KB867737a3a898upstream ↗
--- name: khan-explainer description: Use when the user wants a Khan Academy style explainer video, a blackboard or whiteboard lesson, a hand-drawn chalk-talk animation, a short narrated video that teaches a concept ("explain X in a video", "explainer video", "teach X in 30 seconds"), or a tutorial that draws hand-written arrows, circles and captions over product screenshots ("draw over the UI", "annotated walkthrough"), or clips cut from a YouTube video or podcast where the speaker's real audio plays under a blackboard drawn to it ("khanify this video", "clip this with the Khan visual"), especially when it must be free, local, and use no paid APIs or keys. macOS only. --- > Copy of the root SKILL.md for skills.sh discovery. The root file is the source of truth. # Khan Explainer A pen draws while a voice explains. Three modes, one renderer: - **Blackboard lesson.** A diagram drawn on a black board, Khan Academy style. - **Draw-over-UI tutorial.** Arrows, circles and numbered captions drawn over product screenshots. - **Real-audio clip.** A real person's voice, cut from a video, with the board drawn to their words. See "Real-audio clips". One scene file in, one MP4 out, in seconds. Free and local: HTML canvas, Playwright, macOS `say`, ffmpeg. No keys. Every mode renders as chalk on a blackboard or marker on a whiteboard, landscape or vertical. Made by Haider Farooq ([github.com/haiderfarooq3](https://github.com/haiderfarooq3/khan-explainer)). Free for anyone to use and change (MIT). **Core principle: the voice drives the clock.** A scene is a list of beats. A beat is one spoken clause plus the drawing that happens while it is said. The renderer speaks each beat first, measures it, and fits that beat's drawing to it. Never hardcode seconds or guess when a word lands. ## Workflow 1. **Script the beats.** One idea per beat, split at commas and full stops. Check the length formula below. 2. **Plan the picture.** Lesson: lay out the whole board. Tutorial: capture the stills and their rectangles. Each has a section below. 3. **Write `scene.js`** in a scratch folder. Copy `examples/ai-agents.js` for a lesson or `examples/ui-tutorial.js` for a tutorial. 4. **Render:** `node ~/.claude/skills/khan-explainer/scripts/render.js scene.js out.mp4` 5. **Read the `sheet` image it prints.** It shows the board at the end of every beat. The same folder holds every beat full-size as `b000.jpg`, `b001.jpg` and so on. Open those to check that a ring really sits on a small button. Fix every `WARN` (text off the board, or one label on another), overlap and spill, then re-render. A render takes seconds, so iterate. 6. Deliver the MP4 and say which voice it used. Each output line is `beat N start +duration`. The sheet path is new on every render. First run on a machine: `cd scripts && npm install && npx playwright install chromium`. ## Length and pace | Pace | Settings | Seconds, roughly | |---|---|---| | Quick explainer | defaults: `rate: 170`, `gap: 0.15` | words ÷ 3 + beats × 0.15 + 1.3 | | Tutorial | `rate: 150, gap: 0.6` | words ÷ 2.9 + beats × 0.6 + 1.3 | A 10-second explainer is about 24 words in 5 beats. A 60-second tutorial is about 145 words in 15 beats. The formula lands within about 5%, and the render prints the real length. To hit a target, change the words, not `rate`. Use the tutorial pace whenever the viewer has to find something on a screen. The quick pace feels rushed there. ## Scene API ```js scene({ voice: 'Samantha', rate: 170, size: [1280, 720], // all optional. [720, 1280] = vertical lang: 'ar', // the language spoken: picks the voice (see "Other languages") gap: 0.15, dim: 0.2, // seconds between beats; screenshot darkening theme: 'light', // whiteboard and marker. Leave it out for the blackboard. beats: [ { say: 'Spoken clause.', draw: p => { /* p runs 0 to 1 while it is spoken */ } }, { dur: 1.5, draw: p => {} }, // silent beat, in seconds { clear: true, say: 'Next idea.', draw: p => {} }, // wipes the board first { bg: 'shots/home.png', say: 'Start here.', draw: p => {} }, // screenshot as the board { theme: 'dark', say: 'Lights off.', draw: p => {} } // flips the board from this beat on // With `audio: 'audio.wav'` on the scene, nothing is spoken by the computer: each beat takes // `at: 12.4` (seconds into that file) and `say` is only a note. See "Real-audio clips". ], }) ``` Every draw call is `(geometry, p, style)`. Points are `[x, y]` in board units. | Call | Draws | |---|---| | `write(str, x, y, p, {size, color, center, lang})` | Handwriting, letter by letter. `y` is the baseline. Arabic, Urdu and Hebrew run left from `x`. | | `stroke(points, p, {color, width})` | Any shape, drawn progressively. | | `arrow(from, to, p, {color, ctrl})` | Arrow. `ctrl` is a point that bends it. | | `check(x, y, p, {size, color})` | Tick mark. | | `line(a, b)` `curve(a, b, ctrl)` `oval(cx, cy, rx, ry)` `box(x, y, w, h)` | Return points for `stroke`. | | `ring(rect, pad)` `around(rect, pad)` | An oval or a frame around a `{x, y, w, h}` rectangle, for `stroke`. | | `view(captureWidth, cropTop)` | Maps screenshot positions to the board. `.r(rect)` for a rectangle, `.p(x, y)` for a point. | | `seg(p, from, to)` | A slice of the beat, to order strokes: `seg(p, 0, .4)` then `seg(p, .4, 1)`. | | `C.yellow` `blue` `orange` `pink` `green` `red` `purple` `white` | Chalk colours. On the whiteboard the same names are marker inks, and `white` is black. | Text width is about `0.45 × size` per character for a normal label and `0.63 × size` per capital. Work it out before placing a label beside anything. ## Other languages `write` takes any script and writes it the way that script is written by hand. The first letter of the string decides the direction; its script picks the face. | Script | Direction | Set in | Width per letter, roughly | |---|---|---|---| | Arabic, Persian | right to left | naskh, regular weight | `0.3–0.5 × size` (vowel marks add none). Give it about twice a Latin label's size. | | Urdu | right to left | nastaliq: letters slope down to the left and stack about `1.6 × size` tall | `0.5 × size`. Keep it near `0.7×` a Latin size and leave a tall line. | | Hebrew | right to left | regular weight, points (niqqud) kept | `0.65 × size` | | Hindi, Bengali, Tamil and other Indic | left to right, hung from a headline | regular weight | `0.7–0.9 × size` per syllable | | Thai, Lao, Khmer, Burmese | left to right, no spaces between words | looped, regular weight | `0.6 × size` | | Chinese, Japanese, Korean | left to right, one square per character | bold | `1.0 × size` per character | | Cyrillic, Greek | left to right | bold | `0.65 × size` | - **Right-to-left text.** `x` is the right end of the text, where the pen starts (the centre with `center: true`), and the word is uncovered right to left. - **Shaped, not sliced.** Every non-Latin string is shaped once as a whole and uncovered in writing order, so joined Arabic letters keep their forms, a vowel mark stays on its letter, and a Hindi vowel sign that sits before its consonant appears with it. - **Urdu.** It shares Arabic's letters, so `write` spots it only by a letter Arabic does not use (ٹ ڈ ڑ ں ہ ھ ے). Put `lang: 'ur'` on the scene or on the call to be sure of the nastaliq hand. - **Mixed labels.** A Latin label that quotes a foreign word keeps the handwriting and runs left to right; the quoted word is set in its own script's face. - **The voice.** `lang` on the scene picks the built-in voice: `ar` Majed, `he` Carmit, `hi` Lekha, `zh` Tingting, `ja` Kyoko, `ko` Yuna, `th` Kanya, `ru` Milena, `el` Melina, `tr` Yelda, `id` Damayanti, `es` Mónica, `fr` Thomas, `de` Anna, `it` Alice, `pt` Luciana, `bn` Piya, `ta` Vani, `te` Geeta, `kn` Soumya, `uk` Lesya, `vi` Linh, `pl` Zosia, `nl` Xander, `sv` Alva, `ms` Amira. A missing voice stops the render with where to download it. macOS has no voice for Urdu or Persian: use `eleven` (its multilingual model speaks them) or `audio`. An English scene can still show foreign words: then `say` spells the sound ("kitaab") and the board shows the word. - The off-board and overlap warnings measure the ink, not the letter count, so a long nastaliq swash or a tall stack of marks still warns. See `examples/arabic.js` (an Arabic lesson) and `examples/languages.js` (one word in eight languages). `node tests/run.js` renders every example and the same short scene in fifteen languages (`tests/languages/`), and fails on any warning. `node tests/fonts.js` prints which face each script gets on this machine: a Mac face, a Noto face, or none. ## Light and dark The board is a blackboard unless told otherwise. Three ways to change that: - `theme: 'light'` on the scene: a whiteboard, with the colour names mapped to marker inks. - `KHAN_THEME=light node scripts/render.js scene.js out-light.mp4`: re-skins a finished scene without editing it. - `theme` on a beat: flips the board from that beat on. The ink already on it changes colour with it. Read `C.blue` inside `draw`, never into a variable at the top of the file, or it keeps the first theme's colour. On a white board every hard edge shows, so look at the light sheet separately from the dark one. ## A human voice (optional) `say` is free and robotic. For a human voice, export `ELEVENLABS_API_KEY` and name a voice on the scene: ```js scene({ eleven: '<voice id>', beats: [...] }) scene({ eleven: { voice: '<voice id>', model: 'eleven_multilingual_v2', settings: { speed: 1.1 } }, beats: [...] }) ``` - The whole script is read in one take and cut back into beats at the character times ElevenLabs returns. It sounds like one person talking, and the pen still follows every clause. - `gap` defaults to 0 here, because the take has its own pauses. At `speed: 1.1` expect about 3.3 words a second. - Takes are cached in `.voice/` beside the scene. Re-rendering the same words is free, so lay the board out with `say` first, then switch the voice on and change only drawings. - Changing any `say` buys a new take of the whole script. **Kokoro: a free local human voice.** `pip install kokoro soundfile` once (for Japanese add `"misaki[ja]"` and run `python -m unidic download`; for Chinese add `"misaki[zh]"`), then put `kokoro: true` on the scene, or a voice name (`kokoro: 'am_michael'`), or `{ voice, speed }`. `KHAN_TTS=kokoro` tries it on any scene without editing it. It speaks English, Spanish, French, Hindi, Italian, Japanese, Portuguese and Chinese, and `lang` picks its voice. For Arabic, Urdu, Hebrew and the rest, `KHAN_TTS` leaves the built-in voice on; use `eleven` for a human voice there. The model downloads on first use (about 330 MB), then runs offline. Takes are cached in `.voice/kokoro/`. `KHAN_PYTHON` names the Python that has it installed. ## Blackboard lessons - **Lay out the whole board before writing code.** 1280×720 units, 60 margin, title top-left. List each shape's centre and size for every beat, including the last, so the finished board fills the width instead of crowding one side. - One colour per concept, reused whenever that concept returns. - Draw what is being said as it is said. Never reveal a finished diagram. - Diagrams and short labels only. No sentences on the board, no logos, no stock images. - Talk like a tutor: plain words, "so", "now", "let's say". No term the board has not introduced. - Exaggerate scale. If two things differ, draw the difference big enough to see at a glance. - The board accumulates. Add `clear: true` only when it is full, roughly every 5–6 beats. ## Draw-over-UI tutorials `bg` puts a screenshot on the board from that beat on and wipes earlier ink. Paths are relative to the scene file. Repeat the same `bg` on a later beat to wipe the annotations and mark up that screen again. `clear: true` takes the screenshot away as well, back to the plain board. `dim` darkens screenshots so the chalk reads, and a beat can override it, for example `dim: 0` on a showcase image. **Capture.** Pick the path that fits: | Situation | Capture with | Coordinates | |---|---|---| | Public page, or a script can sign in | Playwright, `viewport: {width: 1280, height: 720}, deviceScaleFactor: 1.5` | CSS pixels are board units. Use them as they are, or through `view(1280)`. | | Needs the user's own logged-in browser, or video previews a bundled browser cannot play | A full screenshot in that browser, cropped to 16:9 | `view(captureWidth, cropTop)` | For the second path, crop with ffmpeg. A 1440×900 window at 2× density, cut 90 CSS pixels from the top: ``` ffmpeg -i full.png -vf "crop=2880:1620:0:180,scale=1920:1080" shot.png ``` While capturing: - Save `getBoundingClientRect()` for every target. Never read coordinates off the image. - Measure again for every state, after it settles. Elements move and resize when focused or typed into, and menus open over the page. - Match the capture to the board: the app's dark theme for the blackboard, its light theme for the whiteboard. Put the setting back afterwards. Only one theme available: see `dim` under Build. - Hide private data in the page first (`visibility: hidden` on the nodes), then look at every still. A broad rule hides things you need: "anything near the top" also matches content scrolled above the viewport. - Capture progress states while they exist. They collapse when the job ends. - Never post in a shared or public space to stage a demo. Use existing results, or one cheap run in a private space the user has agreed to. **Build.** - Pass rectangles through `view()` into `ring` or `around`. Place labels in board units, in empty areas of the screen. - Number the steps in the labels: "1. Describe it", "2. Send". - Give anything a first-timer finds strange its own screen: progress lines, tool calls, a stop button. - Every beat adds something new to the picture. A beat that redraws the last ring in another colour is dead air. - Chalk needs a dark surface and marker a light one. `dim` washes the screenshot towards the board's colour: on a mismatched or crowded screen, raise it to about `0.55` so the ink reads. - End on the result, not the setup. ## Real-audio clips A YouTube video or podcast in, a folder of vertical shorts out: the speaker's own audio, our board. Still free and local. `scripts/clip_audio.py` does the transcribing and cutting. 1. **Get the audio.** The system `yt-dlp` goes stale and YouTube answers 403 or a bot check, so run the newest one: `uvx --from 'yt-dlp[default]@latest' yt-dlp --cookies-from-browser chrome -f "bestaudio[ext=m4a]/bestaudio" -o "src.%(ext)s" <url>` 2. **Transcribe.** `uvx --with faster-whisper python scripts/clip_audio.py transcribe src.m4a work` writes `work/transcript.txt`, one timed line per sentence. About 3 minutes for a 20-minute video. 3. **Pick the moments.** Read the whole transcript. A usable clip is 20 to 60 seconds, starts on a sentence that needs no earlier context, makes one point, and ends on its punchline. Skip sponsor reads, workshop plugs and outros. Write `clips.json` with each clip's first and last line times. 4. **Cut.** `... clip_audio.py cut src.m4a work clips.json` writes `work/clips/NN-slug/audio.wav` and `words.txt`. Every cut is transcribed again, so `words.txt` holds word times inside the clip. Fix any line marked `CHECK` before drawing: the cut caught a stray word or lost one. 5. **Draw.** One `scene.js` per clip folder: ```js scene({ size: [720, 1280], audio: 'audio.wav', // vertical; the recording is the clock beats: [ { at: 0, say: 'note of what he says', draw: p => {} }, // `at` = seconds, read from words.txt { at: 4.44, say: 'next phrase', draw: p => {} }, // a beat lasts until the next `at` ], }) ``` - `at` comes from `words.txt`, never from a guess. To land a word inside a beat, `seg` takes `(wordTime - at) / (nextAt - at)`. - Ink appears as the words are said or just after, never before. - Vertical board: 720 x 1280. Keep ink inside x 50..670 and y 150..1010, because phone UI covers the rest. Title 52 to 60, labels 40 to 50, nothing below 28. - Beat 1 writes a 2 to 5 word title naming the clip's point. Add something every 3 to 4 seconds. `clear: true` every 12 to 20 seconds. End on the punchline, written big. - Draw only what is said in that clip, with the numbers as spoken. Keep swearing, logos and real faces off the board. - The sheet tiles a vertical board six across. Open the last frame of each board full-size. **Both looks.** Render every clip twice, once plain and once with `KHAN_THEME=light` (see "Light and dark"). The scene does not change. **Talking head (TikTok green-screen look).** `scripts/cutout` (source `cutout.swift`, build with `swiftc -O cutout.swift -o cutout`) lifts the speaker off their background with macOS Vision: raw BGRA frames in, the same frames out with the matte as alpha. It hides itself on b-roll (no face to camera) and fades the bottom rows. `scripts/talking_head_example.sh <clip-folder> <source-video> [light]` is the working recipe: cut out once per clip into a ProRes 4444 `cutout.mov`, shrink the board to the top of the frame, overlay the speaker at the bottom with soft side edges. - Set `CROP` (w:h:x:y) to where the speaker sits in the source frame, above any captions the editor burned onto their chest, and check a frame from every clip. - Never edit a script while a batch is running it: bash reads the file as it goes and the in-flight runs break. For many clips, finish one as the worked example, write the rules above into a brief, and give each parallel agent three clip folders plus that brief and the example. ## Common mistakes | Mistake | Fix | |---|---| | Label wider than its oval or box | Work out the width from the rule above. Widen the shape or shorten the label. | | One long sentence in one beat | The pen crawls. Split it into clauses. | | Splitting a beat mid-clause | Each beat is a separate take, so it sounds choppy. Split at punctuation. | | Emoji, ticks or arrow glyphs in `write` | The font lacks them. Draw them with `stroke`, as `check` does. Keyboard symbols such as `$ % + !` are fine. | | An arrow pointing at something not drawn yet | It points at empty space until a later beat. Aim arrows only at what is already on the board. | | An arrow drawn through a label | Start it from the side of the label that faces the target. | | A key word drawn early in a long beat | `p` spans the whole beat. Use `seg` to place the stroke where the word falls, or split the beat. | | A mispronounced word or a number | Respell it in `say` only ("one hundred ten"). Keep the written label correct ("$110"). | | Old annotations still on screen | Ink carries over until a beat has `bg` or `clear`. Repeat the `bg` to start clean on the same screenshot; `clear` goes back to the plain board. | | Calling your own variable `box`, `line`, `ring` or `check` | It hides the helper of that name inside your scene. Name rectangles after the thing: `searchBox`, `sendBtn`. | | Converting screenshot coordinates by hand | Use `view()`. Hand arithmetic is where rings miss buttons. | | Arabic or Hebrew placed by its left edge | For right-to-left text `x` is the right end. Use `center: true` to place it by its middle. | | Urdu written in naskh | Add `lang: 'ur'` to the scene. Without an Urdu-only letter the text looks Arabic. | | A sentence in another language read by the English voice | Set `lang` on the scene so the matching voice reads it. | | Skipping the sheet | Coordinates are written blind. The sheet is the only check. | | A real-audio beat timed by ear or by sentence length | Read `at` from `words.txt`. A guess drifts and the pen runs ahead of the voice. | ## Limits Built for macOS. On Linux the free voice falls back to espeak-ng (`apt install espeak-ng`), which speaks about a hundred languages but sounds rougher still; install the Noto fonts for the scripts you write. The free voice is robotic: use `eleven` or real audio when the voice matters. `tts()` in `scripts/render.js` is the one place to swap in another engine.README.md4.5 KB415d5681c659upstream ↗
# khan-explainer A Claude Code skill that makes Khan Academy style explainer videos: a pen draws while a voice explains. You describe the video, Claude writes a scene file, and one command renders the MP4. Write-up: [Claude Code skills for content: how I make Khan Academy style videos for free](https://haiderfarooq.dev/blog/claude-code-skills-for-content)  It runs on your Mac with an HTML canvas, Playwright, ffmpeg and the built-in `say` voice. No API keys, no accounts, no editor. ## What it makes | Mode | What you get | |---|---| | Blackboard lesson | A diagram drawn stroke by stroke while the voice explains it. | | Draw-over-UI tutorial | Arrows, circles and numbered steps drawn over your product screenshots. | | Real-audio clip | A YouTube video or podcast in, vertical shorts out. The speaker's own voice plays while the board is drawn to their words. It can also cut the speaker out and stand them in front of the board. | Every mode renders as chalk on a blackboard or marker on a whiteboard, landscape or vertical. One flag switches between them, and a single beat can flip the board mid-video. ## Why the pen stays in sync The voice drives the clock. A scene is a list of beats, and a beat is one spoken clause plus the drawing that happens while it is said. The renderer speaks each beat first, measures it, and fits that beat's drawing to its length. Nobody types a timestamp, so the pen cannot run ahead of the words. ```js scene({ beats: [ { say: 'What is an AI agent?', draw: p => { write('What is an AI agent?', 60, 85, p, { size: 56, color: C.yellow }); } }, { say: "It's software that uses a language model to think,", draw: p => { stroke(oval(300, 330, 155, 82), seg(p, 0, .4), { color: C.blue }); write('1. THINK', 300, 328, seg(p, .4, 1), { size: 40, color: C.blue, center: true }); } }, ], }) ``` ## Install You need macOS, Node 20 or newer, and ffmpeg (`brew install ffmpeg`). ```sh git clone https://github.com/haiderfarooq3/khan-explainer ~/.claude/skills/khan-explainer cd ~/.claude/skills/khan-explainer/scripts && npm install && npx playwright install chromium ``` ## Use Ask Claude Code for the video you want: > Make a 30-second Khan-style explainer on how DNS works. > Draw over these screenshots and show a new user how to send their first invoice. > Khanify this YouTube video: find the best moments and clip them, light and dark. Or render one of the examples yourself: ```sh cd ~/.claude/skills/khan-explainer node scripts/render.js examples/ai-agents.js agents.mp4 # blackboard KHAN_THEME=light node scripts/render.js examples/ai-agents.js light.mp4 # whiteboard node scripts/render.js examples/ui-tutorial.js tutorial.mp4 # drawn over screenshots node scripts/render.js examples/arabic.js arabic.mp4 # right-to-left writing node scripts/render.js examples/languages.js languages.mp4 # one word in eight languages ``` Each render also prints the path of a contact sheet: the board at the end of every beat, in one image. That sheet is how Claude checks its own layout before it shows you anything. [SKILL.md](SKILL.md) is the full reference: the scene API, layout rules, the capture recipe for tutorials and the clip pipeline. ## Optional extras - **A human voice.** Export `ELEVENLABS_API_KEY` and add `eleven: '<voice id>'` to a scene. The script is read in one take and cut back into beats, and takes are cached, so re-rendering the same words is free. - **Kokoro, a free local human voice.** `pip install kokoro soundfile`, then `kokoro: true` on a scene or `KHAN_TTS=kokoro` for any scene. English, Spanish, French, Hindi, Italian, Japanese, Portuguese and Chinese. - **Any language on the board.** Arabic, Urdu and Hebrew are written right to left, Hindi, Thai, Chinese, Japanese, Korean, Russian and more left to right, each in a face that writes it properly. `lang: 'ar'` on a scene picks the matching voice. `node tests/run.js` renders them all. - **Real-audio clips** need [uv](https://docs.astral.sh/uv/). `scripts/clip_audio.py` transcribes locally with faster-whisper. - **The talking-head cutout** uses macOS Vision. It builds itself with `swiftc` the first time, which needs the Xcode command line tools. ## Credits Made by [Haider Farooq](https://github.com/haiderfarooq3). MIT licensed: use it, change it, ship videos with it. Not affiliated with or endorsed by Khan Academy. "Khan Academy style" describes the look: handwriting on a board, drawn as it is explained.scripts/board.html12 KB642526fe4a6dupstream ↗
<!doctype html> <html><body style="margin:0;background:#111"><canvas id="c"></canvas> <script> // Blackboard runtime. A scene file calls scene({...}); render.js then drives frame(t). // Every coordinate is in logical board units (1280x720 by default), rendered at SCALE. const SCALE = 1.5, cv = document.getElementById('c'), g = cv.getContext('2d'); const FONT = '"Bradley Hand","Chalkboard SE","Marker Felt",cursive'; // Each script in a face that writes it properly: a Mac face first, then a Noto face for other systems. Only scripts // made of plain strokes are set bold; a faked bold smears vowel marks and stacked consonants. Latin text has no entry. // The first that matches wins, so Urdu-only letters come before Arabic and kana before Han. const SCRIPTS = [ { re: /\p{Script=Hebrew}/u, face: '"Arial Hebrew","Noto Sans Hebrew"' }, { urdu: true, re: /[ٹڈڑںھہے]/u, face: '"Noto Nastaliq Urdu"' }, // letters only Urdu uses: written in nastaliq { arabic: true, re: /\p{Script=Arabic}/u, face: '"Traditional Arabic","Noto Naskh Arabic","Geeza Pro"' }, { re: /\p{Script=Syriac}|\p{Script=Thaana}|\p{Script=Nko}/u, face: '"Noto Sans Syriac","Noto Sans Thaana","Noto Sans NKo"' }, { re: /\p{Script=Devanagari}/u, face: '"Kohinoor Devanagari","Devanagari Sangam MN","Noto Sans Devanagari"' }, { re: /\p{Script=Bengali}/u, face: '"Kohinoor Bangla","Bangla Sangam MN","Noto Sans Bengali"' }, { re: /\p{Script=Gurmukhi}/u, face: '"Gurmukhi Sangam MN","Noto Sans Gurmukhi"' }, { re: /\p{Script=Gujarati}/u, face: '"Kohinoor Gujarati","Gujarati Sangam MN","Noto Sans Gujarati"' }, { re: /\p{Script=Tamil}/u, face: '"Tamil Sangam MN","Tamil MN","InaiMathi","Noto Sans Tamil"' }, { re: /\p{Script=Telugu}/u, face: '"Kohinoor Telugu","Telugu Sangam MN","Noto Sans Telugu"' }, { re: /\p{Script=Kannada}|\p{Script=Malayalam}|\p{Script=Sinhala}|\p{Script=Oriya}/u, face: '"Kannada Sangam MN","Malayalam Sangam MN","Sinhala Sangam MN","Oriya Sangam MN","Noto Sans Kannada","Noto Sans Malayalam","Noto Sans Sinhala","Noto Sans Oriya"' }, { re: /\p{Script=Thai}|\p{Script=Lao}|\p{Script=Khmer}|\p{Script=Myanmar}|\p{Script=Tibetan}/u, face: '"Thonburi","Lao Sangam MN","Khmer Sangam MN","Myanmar Sangam MN","Kailasa","Noto Sans Thai Looped","Noto Looped Thai","Noto Sans Thai","Noto Sans Lao","Noto Sans Khmer","Noto Sans Myanmar","Noto Serif Tibetan"' }, { re: /\p{Script=Hiragana}|\p{Script=Katakana}/u, bold: true, face: '"Klee","Hiragino Maru Gothic ProN","Hiragino Sans","Hiragino Kaku Gothic ProN","Noto Sans CJK JP"' }, // kana anywhere makes the Han in it Japanese { re: /\p{Script=Hangul}/u, bold: true, face: '"Nanum Pen Script","Apple SD Gothic Neo","Noto Sans CJK KR"' }, { re: /\p{Script=Han}/u, bold: true, face: '"Hannotate SC","Kaiti SC","PingFang SC","Noto Sans CJK SC"' }, { re: /\p{Script=Cyrillic}|\p{Script=Greek}|\p{Script=Armenian}|\p{Script=Georgian}/u, bold: true, face: '"Comic Sans MS","Noto Sans"' }, ]; const LETTER = /\p{L}/u, RTL = /\p{Script=Hebrew}|\p{Script=Arabic}|\p{Script=Syriac}|\p{Script=Thaana}|\p{Script=Nko}/u; const URDU = SCRIPTS.find(k => k.urdu).face; const C = { yellow: '#ffe066', blue: '#4fc3f7', orange: '#ffb74d', pink: '#f48fb1', green: '#81c784', red: '#ef5350', purple: '#b39ddb', white: '#e8e8e8' }; // Light mode: marker colours on a white board. The names stay the same, so a scene needs no change. const LIGHT = { yellow: '#cf8600', blue: '#1b74d3', orange: '#e6620a', pink: '#d5307a', green: '#1c9a4a', red: '#dc2f2f', purple: '#6d45c6', white: '#1c1c1c' }; const DARK = { ...C }; let BASE = 'dark', BG, PEN, GLOW; // GLOW: the halo that lifts ink off a screenshot, dark behind chalk and white behind marker const useTheme = t => { const l = t === 'light'; Object.assign(C, l ? LIGHT : DARK); BG = l ? '#fbfbf8' : '#111'; PEN = l ? '#222' : '#fff'; GLOW = l ? '255,255,255' : '0,0,0'; }; window.setTheme = t => { BASE = t; }; const clamp = v => Math.max(0, Math.min(1, v)); const seg = (p, a, b) => clamp((p - a) / (b - a)); // a slice of a beat's 0..1 progress let S = null, T = [], W = 1280, H = 720, pen = null; const IMGS = {}, FADE = 0.3; // screenshot backgrounds, and their cross-fade in seconds const warns = new Set(); let labels = []; // text boxes drawn this frame, to catch one label landing on another // ---- shapes: each returns [x, y] points for stroke(). Wobble is sin-based, never // Math.random, because every frame has to redraw the identical line. function curve(a, b, ctrl, n = 40) { const m = ctrl || [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2], pts = []; const amp = Math.min(2, Math.hypot(b[0] - a[0], b[1] - a[1]) / 80); // short strokes get less wobble for (let i = 0; i <= n; i++) { const u = i / n, v = 1 - u, w = amp * Math.sin(u * 9); pts.push([v * v * a[0] + 2 * v * u * m[0] + u * u * b[0] + w, v * v * a[1] + 2 * v * u * m[1] + u * u * b[1] + w]); } return pts; } const line = (a, b) => curve(a, b); function oval(cx, cy, rx, ry) { const pts = []; for (let i = 0; i <= 80; i++) { const a = -Math.PI / 2 + (i / 80) * Math.PI * 2.08, k = 1 + 0.03 * Math.sin(a * 3 + cx) + 0.025 * (i / 80); pts.push([cx + Math.cos(a) * rx * k, cy + Math.sin(a) * ry * k]); } return pts; } const ring = (r, pad = 8) => oval(r.x + r.w / 2, r.y + r.h / 2, r.w / 2 + pad, r.h / 2 + pad); // circle a UI element from its {x, y, w, h} const box = (x, y, w, h) => [].concat(curve([x, y], [x + w, y + 2], null, 14), curve([x + w, y + 2], [x + w - 2, y + h], null, 10), curve([x + w - 2, y + h], [x + 1, y + h - 2], null, 14), curve([x + 1, y + h - 2], [x - 2, y - 5], null, 10)); const around = (r, pad = 8) => box(r.x - pad, r.y - pad, r.w + pad * 2, r.h + pad * 2); // a hand-drawn frame around a UI element // view(captureWidth, cropTop) puts CSS-pixel numbers straight from getBoundingClientRect() onto the board, // so nobody converts screenshot coordinates by hand. cropTop = CSS px cut off the top of the still. const view = (cw, top = 0) => ({ p: (x, y) => [x * W / cw, (y - top) * W / cw], r: r => ({ x: r.x * W / cw, y: (r.y - top) * W / cw, w: r.w * W / cw, h: r.h * W / cw }) }); // ---- drawing: (geometry..., p, style). p is 0..1; nothing is drawn at 0. function stroke(pts, p = 1, o = {}) { if (p <= 0) return; const n = Math.max(2, Math.ceil(pts.length * p)); g.strokeStyle = o.color || C.white; g.lineWidth = o.width || 5; g.lineCap = g.lineJoin = 'round'; g.beginPath(); g.moveTo(...pts[0]); for (let i = 1; i < n; i++) g.lineTo(...pts[i]); g.stroke(); if (p < 1) pen = pts[n - 1]; } function write(str, x, y, p = 1, o = {}) { if (p <= 0) return; const size = o.size || 36, sc = SCRIPTS.find(k => k.re.test(str)), shaped = !!sc; const rtl = shaped && RTL.test((str.match(LETTER) || [''])[0]); // the first letter sets the direction // Urdu shares Arabic's letters but is written in nastaliq. `lang: 'ur'` on the call or the scene says so when no Urdu-only letter does. const face = sc?.arabic && (o.lang || S?.lang) === 'ur' ? URDU : sc?.face; // A Latin label that quotes a foreign word keeps its own hand, and the foreign word falls back to its script's face. const latin = !rtl && /\p{Script=Latin}/u.test((str.match(LETTER) || [''])[0]); g.font = !shaped ? `bold ${size}px ${FONT}` : latin ? `bold ${size}px ${FONT},${face}` : `${sc.bold ? 'bold ' : ''}${size}px ${face},${FONT}`; g.fillStyle = o.color || C.white; g.textAlign = 'left'; if (shaped) g.direction = rtl ? 'rtl' : 'ltr'; const m = g.measureText(str), full = m.width, lx = o.center ? x - full / 2 : rtl ? x - full : x; // x is where the pen starts: the right end of right-to-left text // Ink, not advance width: a nastaliq word or a Thai tone mark can reach past the box the text advances by. // Nastaliq also stacks its letters far above the line. const ink0 = shaped ? lx - m.actualBoundingBoxLeft : lx, ink1 = shaped ? lx + m.actualBoundingBoxRight : lx + full; const top = shaped ? y - Math.max(size * 0.8, m.actualBoundingBoxAscent) : y - size * 0.8, bot = shaped ? y + m.actualBoundingBoxDescent : y + size * 0.2; if (ink0 < 0 || ink1 > W || (shaped ? top : y - size) < 0 || (shaped ? bot : y) > H) warns.add(`text runs off the board: "${str}"`); labels.push({ str, x: ink0, y: top, w: ink1 - ink0, h: bot - top }); if (!shaped) { const sub = str.slice(0, Math.ceil(str.length * p)); g.fillText(sub, lx, y); if (p < 1) pen = [lx + g.measureText(sub).width, y - size * 0.3]; return; } // Joined letters take their shape from their neighbours, a vowel mark belongs to the letter it sits on, and an // Indic vowel sign can be drawn before the consonant it follows. A sliced string would reshape as it grows, // so shape the whole string once and uncover it in writing order. const shown = full * p, edge = rtl ? lx + full - shown : lx + shown; const up = m.actualBoundingBoxAscent + 4, down = m.actualBoundingBoxDescent + 4; // marks stack well above and below the letters g.save(); g.beginPath(); g.rect(rtl ? edge : lx - size, y - up, shown + size, up + down); g.clip(); g.fillText(str, lx, y); g.restore(); g.direction = 'ltr'; if (p < 1) pen = [edge, y - size * 0.3]; } function arrow(a, b, p = 1, o = {}) { const pts = curve(a, b, o.ctrl); stroke(pts, p, o); if (p < 1) return; const e = pts[40], q = pts[36], ang = Math.atan2(e[1] - q[1], e[0] - q[0]); for (const d of [2.6, -2.6]) stroke([e, [e[0] + Math.cos(ang + d) * 22, e[1] + Math.sin(ang + d) * 22]], 1, o); } function check(x, y, p = 1, o = {}) { // glyphs like a tick are missing from the handwriting font, so draw them const s = o.size || 40, mid = [x + s * 0.3, y + s]; stroke(curve([x, y + s * 0.55], mid, null, 8).concat(curve(mid, [x + s, y], null, 14)), p, { color: C.green, width: 6, ...o }); } // ---- runtime window.scene = s => { S = s; if (s.theme) setTheme(s.theme); [W, H] = s.size || [W, H]; cv.width = W * SCALE; cv.height = H * SCALE; }; window.loadImages = async map => { for (const [k, url] of Object.entries(map)) { const im = new Image(); im.src = url; await im.decode(); IMGS[k] = im; } }; function paint(name, alpha) { // fit the screenshot inside the board, letterboxed if the shape differs const im = IMGS[name], k = Math.min(W / im.width, H / im.height); g.globalAlpha = alpha; g.drawImage(im, (W - im.width * k) / 2, (H - im.height * k) / 2, im.width * k, im.height * k); g.globalAlpha = 1; } window.sceneMeta = () => S && { voice: S.voice, lang: S.lang, kokoro: S.kokoro, rate: S.rate || 170, gap: S.gap, audio: S.audio, eleven: S.eleven, size: [W, H], bgs: [...new Set(S.beats.map(b => b.bg).filter(Boolean))], beats: S.beats.map(b => ({ say: b.say || '', dur: b.dur, at: b.at })) }; window.setTimings = t => { T = t; }; window.warnings = () => [...warns]; window.frame = t => { pen = null; labels = []; let from = 0, theme = BASE; // a beat with clear or bg wipes the ink, so start from the latest one already reached const bgs = []; S.beats.forEach((b, i) => { if (t < T[i].start) return; if (b.clear || b.bg) from = i; if (b.clear) bgs.length = 0; if (b.bg) bgs.push(i); if (b.theme) theme = b.theme; }); // clear takes the screenshot away too useTheme(theme); // a beat's `theme` flips the board from that beat on, and the ink already on it changes with it g.setTransform(SCALE, 0, 0, SCALE, 0, 0); g.shadowBlur = 0; g.fillStyle = BG; g.fillRect(0, 0, W, H); if (bgs.length) { const cur = bgs[bgs.length - 1], prev = bgs[bgs.length - 2], a = clamp((t - T[cur].start) / FADE); if (a < 1 && prev !== undefined) paint(S.beats[prev].bg, 1); paint(S.beats[cur].bg, a); g.fillStyle = `rgba(${GLOW},${S.beats[cur].dim ?? S.dim ?? 0.2})`; g.fillRect(0, 0, W, H); g.shadowColor = `rgba(${GLOW},.9)`; g.shadowBlur = 10; // ink needs an edge to read over a busy screenshot } for (let i = from; i < S.beats.length; i++) { const p = clamp((t - T[i].start) / T[i].dur); if (p > 0 && S.beats[i].draw) S.beats[i].draw(p); } for (let i = 0; i < labels.length; i++) for (let j = i + 1; j < labels.length; j++) { const a = labels[i], b = labels[j]; if (a.str === b.str) continue; const ox = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x), oy = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y); if (ox > 0 && oy > 0 && ox * oy > 0.15 * Math.min(a.w * a.h, b.w * b.h)) warns.add(`labels overlap: "${a.str}" and "${b.str}"`); } if (pen) { g.fillStyle = PEN; g.shadowColor = PEN; g.shadowBlur = 12; g.beginPath(); g.arc(pen[0], pen[1], 5, 0, 7); g.fill(); g.shadowBlur = 0; } return cv.toDataURL('image/jpeg', 0.95); }; </script></body></html>scripts/clip_audio.py4.8 KBaa01dac51757upstream ↗
#!/usr/bin/env python3 """Real-audio clips for the blackboard: transcribe a recording, then cut moments out of it. uvx --with faster-whisper python clip_audio.py transcribe <audio> <workdir> -> <workdir>/transcript.json (words with times) and transcript.txt (one timed line per sentence) uvx --with faster-whisper python clip_audio.py cut <audio> <workdir> <clips.json> -> <workdir>/clips/NN-slug/audio.wav + words.txt (word times inside that clip) clips.json: [{"slug": "the-12k-offer", "from": 85.96, "to": 131.10}, ...] `from` and `to` are the start times of the first and last transcript.txt lines to keep. Optional "stop": "results," ends the clip after that word in the last line. Local and free: faster-whisper on the CPU. Each cut is re-transcribed, so the times in words.txt belong to the clip itself and a cut that caught a stray word shows up as CHECK. """ import json, os, re, subprocess, sys import numpy as np from faster_whisper import WhisperModel SR = 16000 norm = lambda s: re.sub(r"[^a-z0-9]", "", s.lower()) def load(path): # raw mono floats from ffmpeg: sidesteps faster-whisper's own decoder raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-ac", "1", "-ar", str(SR), "-f", "f32le", "-"], check=True, capture_output=True).stdout return np.frombuffer(raw, dtype=np.float32) def model(): return WhisperModel(os.environ.get("WHISPER_MODEL", "small.en"), device="cpu", compute_type="int8") def transcribe(audio_path, work): os.makedirs(work, exist_ok=True) segs, _ = model().transcribe(load(audio_path), word_timestamps=True, vad_filter=True) out = [{"start": s.start, "end": s.end, "text": s.text.strip(), "words": [{"w": w.word.strip(), "s": round(w.start, 2), "e": round(w.end, 2)} for w in s.words]} for s in segs] json.dump(out, open(f"{work}/transcript.json", "w")) with open(f"{work}/transcript.txt", "w") as f: for s in out: f.write(f"[{int(s['start']) // 60:02d}:{s['start'] % 60:05.2f} = {s['start']:.2f}] {s['text']}\n") print(f"{len(out)} lines -> {work}/transcript.txt") def cut(audio_path, work, clips_path): audio, segs = load(audio_path), json.load(open(f"{work}/transcript.json")) every = [w for s in segs for w in s["words"]] m = model() def quietest(t, lo, hi): # the quietest 25 ms in [t+lo, t+hi]: the seam between two words best, at = 1e9, t for c in np.arange(max(0, t + lo), t + hi, 0.005): w = audio[int(c * SR):int(c * SR) + int(0.025 * SR)] if len(w) == 0: break e = float(np.sqrt(np.mean(w * w))) if e < best: best, at = e, c + 0.0125 return at for n, c in enumerate(json.load(open(clips_path)), 1): i = min(range(len(segs)), key=lambda k: abs(segs[k]["start"] - c["from"])) j = min(range(len(segs)), key=lambda k: abs(segs[k]["start"] - c["to"])) words = [w for s in segs[i:j + 1] for w in s["words"]] if c.get("stop"): words = words[:len(words) - [norm(w["w"]) for w in reversed(words)].index(norm(c["stop"]))] # Never look for the seam past the neighbouring word: that is how a stray word gets into a cut. k0, k1 = every.index(words[0]), every.index(words[-1]) before = every[k0 - 1]["e"] if k0 else 0 after = every[k1 + 1]["s"] if k1 + 1 < len(every) else 1e9 t0 = quietest(words[0]["s"], max(-0.30, before + 0.03 - words[0]["s"]), 0.04) t1 = quietest(words[-1]["e"], 0.02, max(0.08, min(0.45, after - 0.03 - words[-1]["e"]))) d, dur = f"{work}/clips/{n:02d}-{c['slug']}", t1 - t0 os.makedirs(d, exist_ok=True) subprocess.run(["ffmpeg", "-y", "-v", "error", "-ss", f"{t0:.3f}", "-t", f"{dur:.3f}", "-i", audio_path, "-af", f"afade=t=in:d=0.02,afade=t=out:st={dur - 0.06:.3f}:d=0.06", "-ar", "48000", "-ac", "2", f"{d}/audio.wav"], check=True) got = list(m.transcribe(audio[int(t0 * SR):int(t1 * SR)], word_timestamps=True)[0]) with open(f"{d}/words.txt", "w") as f: f.write(f"# {c['slug']} {dur:.2f}s (source {int(t0) // 60}:{t0 % 60:05.2f} to {int(t1) // 60}:{t1 % 60:05.2f})\n# [seconds into audio.wav] word\n") for s in got: f.write(" ".join(f"[{w.start:.2f}] {w.word.strip()}" for w in s.words) + "\n") heard = [w.word.strip() for s in got for w in s.words] ok = norm(heard[0]) == norm(words[0]["w"]) and norm(heard[-1]) == norm(words[-1]["w"]) print(f"{'ok ' if ok else 'CHECK'} {n:02d}-{c['slug']} {dur:.1f}s starts «{' '.join(heard[:4])}» ends «{' '.join(heard[-4:])}»") if __name__ == "__main__": mode, args = (sys.argv[1] if len(sys.argv) > 1 else ""), sys.argv[2:] if mode == "transcribe" and len(args) == 2: transcribe(*args) elif mode == "cut" and len(args) == 3: cut(*args) else: sys.exit(__doc__)scripts/cutout.swift4.1 KB941d170119bdupstream ↗
// Person cutout for a talking head: raw BGRA frames in on stdin, the same frames out on stdout // with the person's matte written into the alpha channel. Free and local: macOS Vision. // A frame with no face looking at the camera (b-roll, a screen recording) comes out fully // transparent, and the bottom rows fade out so the cut-off torso has no hard edge. // swiftc -O cutout.swift -o cutout // ffmpeg -i in.mp4 -vf scale=W:H -f rawvideo -pix_fmt bgra - | ./cutout W H | ffmpeg -f rawvideo -pix_fmt bgra -s WxH -r 30 -i - ... import CoreImage import CoreVideo import Foundation import Vision let args = CommandLine.arguments guard args.count == 3, let w = Int(args[1]), let h = Int(args[2]) else { FileHandle.standardError.write("usage: cutout <width> <height>\n".data(using: .utf8)!) exit(1) } let frameBytes = w * h * 4 // One request for the whole stream: it is stateful, so the matte stays steady from frame to frame. let request = VNGeneratePersonSegmentationRequest() request.qualityLevel = .accurate request.outputPixelFormat = kCVPixelFormatType_OneComponent8 let context = CIContext(options: [.workingColorSpace: NSNull()]) var matte = [UInt8](repeating: 0, count: w * h) var pixelBuffer: CVPixelBuffer? CVPixelBufferCreate(nil, w, h, kCVPixelFormatType_32BGRA, [kCVPixelBufferIOSurfacePropertiesKey: [:]] as CFDictionary, &pixelBuffer) let buffer = pixelBuffer! let input = FileHandle.standardInput, output = FileHandle.standardOutput func readFrame() -> Data? { var data = Data(capacity: frameBytes) while data.count < frameBytes { let chunk = input.readData(ofLength: frameBytes - data.count) if chunk.isEmpty { return nil } data.append(chunk) } return data } // Tighten the matte: the soft outer edge carries the old background (bright sky reads as a halo on a dark board). let levels: [UInt8] = (0..<256).map { v in let t = min(1, max(0, (Double(v) / 255 - 0.35) / 0.5)) return UInt8((t * t * (3 - 2 * t) * 255).rounded()) } let fadeRows = h / 9, bridge = 10 // bottom fade height; a face lost for fewer than `bridge` frames either side is a blink, not b-roll let faces = VNDetectFaceRectanglesRequest() var waiting: [Data] = [], flags: [Bool] = [], written = 0 func flush(upTo end: Int, atEnd: Bool) { while written < end { let i = written let past = flags[max(0, i - bridge)..<i].contains(true) let last = min(flags.count - 1, i + bridge) let future = i < last ? flags[(i + 1)...last].contains(true) : atEnd var frame = waiting.removeFirst() if !(flags[i] || (past && future)) { frame.withUnsafeMutableBytes { raw in let px = raw.bindMemory(to: UInt8.self) for k in 0..<(w * h) { px[k * 4 + 3] = 0 } } } output.write(frame) written += 1 } } while var frame = readFrame() { CVPixelBufferLockBaseAddress(buffer, []) let base = CVPixelBufferGetBaseAddress(buffer)!, stride = CVPixelBufferGetBytesPerRow(buffer) frame.withUnsafeBytes { src in for y in 0..<h { memcpy(base + y * stride, src.baseAddress! + y * w * 4, w * 4) } } CVPixelBufferUnlockBaseAddress(buffer, []) try VNImageRequestHandler(cvPixelBuffer: buffer).perform([request, faces]) if let mask = request.results?.first?.pixelBuffer { let image = CIImage(cvPixelBuffer: mask) let fitted = image.transformed(by: CGAffineTransform(scaleX: CGFloat(w) / image.extent.width, y: CGFloat(h) / image.extent.height)) context.render(fitted, toBitmap: &matte, rowBytes: w, bounds: CGRect(x: 0, y: 0, width: w, height: h), format: .R8, colorSpace: nil) } else { matte.withUnsafeMutableBufferPointer { $0.update(repeating: 0) } } frame.withUnsafeMutableBytes { raw in let px = raw.bindMemory(to: UInt8.self) for y in 0..<h { let fade = y < h - fadeRows ? 256 : (h - 1 - y) * 256 / fadeRows for x in 0..<w { px[(y * w + x) * 4 + 3] = UInt8(Int(levels[Int(matte[y * w + x])]) * fade / 256) } } } // A real talking-head frame has a large face in it; anything else is a cutaway. flags.append((faces.results ?? []).contains { $0.boundingBox.height >= 0.2 }) waiting.append(frame) flush(upTo: flags.count - bridge, atEnd: false) } flush(upTo: flags.count, atEnd: true)scripts/kokoro_tts.py950 B4e0eed2173d8upstream ↗
#!/usr/bin/env python3 # Kokoro: a free, local, human-sounding voice (https://huggingface.co/hexgrad/Kokoro-82M). # render.js pipes in {"voice": "af_heart", "speed": 1.0, "lines": [{"text": ..., "out": "0.wav"}]}; # one process speaks every line, so the model loads once. Setup: pip install kokoro soundfile # (Japanese: "misaki[ja]" then python -m unidic download; Chinese: "misaki[zh]"). import json, sys import numpy as np, soundfile as sf from kokoro import KPipeline job = json.load(sys.stdin) pipe = KPipeline(lang_code=job['voice'][0], repo_id='hexgrad/Kokoro-82M') # the voice's first letter is its language for line in job['lines']: parts = [r.audio for r in pipe(line['text'], voice=job['voice'], speed=job.get('speed', 1.0)) if r.audio is not None] if not parts: sys.exit(f'kokoro produced no audio for: {line["text"]}') sf.write(line['out'], np.concatenate([p.numpy() if hasattr(p, 'numpy') else p for p in parts]), 24000)scripts/package-lock.json1.6 KB0d1fbec33868upstream ↗
{ "name": "khan-explainer", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "khan-explainer", "dependencies": { "playwright": "1.62.1" } }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "hasInstallScript": true, "license": "MIT", "optional": true, "os": [ "darwin" ], "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, "node_modules/playwright": { "version": "1.62.1", "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz", "integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==", "license": "Apache-2.0", "dependencies": { "playwright-core": "1.62.1" }, "bin": { "playwright": "cli.js" }, "engines": { "node": ">=20" }, "optionalDependencies": { "fsevents": "2.3.2" } }, "node_modules/playwright-core": { "version": "1.62.1", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz", "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==", "license": "Apache-2.0", "bin": { "playwright-core": "cli.js" }, "engines": { "node": ">=20" } } } }scripts/package.json188 B989c747cb850upstream ↗
{ "name": "khan-explainer", "private": true, "description": "Blackboard explainer renderer: canvas + Playwright + macOS say + ffmpeg", "dependencies": { "playwright": "1.62.1" } }scripts/render.js13 KB6e6c31dfd7afupstream ↗
#!/usr/bin/env node // Render a blackboard explainer: node render.js <scene.js> <out.mp4> // The voice drives the clock: each beat is spoken first and its measured length // times that beat's drawing, so voice and pen stay in sync without guessing. const { execFileSync, spawn, spawnSync } = require('child_process'); const { once } = require('events'); const fs = require('fs'), os = require('os'), path = require('path'), crypto = require('crypto'); const FPS = 30, LEAD = 0.3, GAP = 0.15, TAIL = 1.0; // seconds: before the first word, between beats, hold at the end const [sceneFile, out] = process.argv.slice(2); const die = m => { console.error(m); process.exit(1); }; if (!sceneFile || !out) die('usage: node render.js <scene.js> <out.mp4>'); const MAC = process.platform === 'darwin'; // elsewhere espeak-ng stands in for `say`: rougher, but it speaks about a hundred languages let chromium; try { ({ chromium } = require('playwright')); } catch { die(`playwright missing. Run: cd ${__dirname} && npm install && npx playwright install chromium`); } const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'khan-')); const probe = f => parseFloat(execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', f])); const jpeg = dataUrl => Buffer.from(dataUrl.split(',')[1], 'base64'); // ponytail: one `say` take per beat, so intonation resets at every beat and the voice is robotic. // Upgrade: a single full take + forced alignment (whisper.cpp) for word timings, or return a // Chatterbox/Piper file from here for a human voice. Anything that writes an audio file works. // A scene's `lang` picks the free voice that speaks it; `voice` names one outright. const SAY = { en: 'Samantha', ar: 'Majed', he: 'Carmit', hi: 'Lekha', zh: 'Tingting', ja: 'Kyoko', ko: 'Yuna', th: 'Kanya', ru: 'Milena', el: 'Melina', tr: 'Yelda', id: 'Damayanti', es: 'Mónica', fr: 'Thomas', de: 'Anna', it: 'Alice', pt: 'Luciana', bn: 'Piya', ta: 'Vani', te: 'Geeta', kn: 'Soumya', uk: 'Lesya', vi: 'Linh', pl: 'Zosia', nl: 'Xander', sv: 'Alva', ms: 'Amira' }; const ESPEAK = { en: 'en-us', zh: 'cmn' }; // every other code is espeak-ng's own: ur, fa, bn, ta, ... function voiceFor(meta) { const lang = meta.lang || 'en'; if (!MAC) { try { execFileSync('espeak-ng', ['--version'], { stdio: 'ignore' }); } catch { die('the free voice needs macOS `say`, or espeak-ng on other systems (apt install espeak-ng)'); } return meta.voice || ESPEAK[lang] || lang; } const voice = meta.voice || SAY[lang]; if (!voice) die(`macOS has no built-in voice for lang '${lang}'. Name one with \`voice\`, or use \`eleven\` or \`audio\`.`); if (!execFileSync('say', ['-v', '?'], { encoding: 'utf8' }).split('\n').some(l => l.startsWith(voice + ' '))) die(`the voice ${voice} is not installed. Add it in System Settings > Accessibility > Spoken Content > System voice > Manage Voices.`); return voice; } function tts(text, i, voice, rate) { const txt = path.join(tmp, `${i}.txt`), audio = path.join(tmp, MAC ? `${i}.aiff` : `${i}.wav`); fs.writeFileSync(txt, text); if (MAC) execFileSync('say', ['-v', voice, '-r', String(rate), '-o', audio, '-f', txt]); else execFileSync('espeak-ng', ['-v', voice, '-s', String(rate), '-w', audio, '-f', txt]); return audio; } // Optional human voice: put ELEVENLABS_API_KEY in the environment and `eleven: '<voice id>'` on the scene. // The whole script is read in ONE take, so it flows like one person talking, then cut back into beats // at the character times the API returns. Takes are cached beside the scene, so re-rendering the same // words costs nothing: fix the drawing as often as you like. async function elevenTakes(beats, opt, dir) { const o = typeof opt === 'string' ? { voice: opt } : opt; if (!o.voice) die('`eleven` needs a voice id: eleven: \'<voice id>\' or eleven: { voice: \'<voice id>\' }'); const said = beats.map((b, i) => ({ i, text: b.say })).filter(b => b.text), text = said.map(b => b.text).join(' '); const body = JSON.stringify({ text, model_id: o.model || 'eleven_multilingual_v2', voice_settings: o.settings }); const cache = path.join(dir, '.voice', crypto.createHash('sha1').update(o.voice + body).digest('hex').slice(0, 12) + '.json'); if (!fs.existsSync(cache)) { const key = process.env.ELEVENLABS_API_KEY; if (!key) die('the scene sets `eleven`, so ELEVENLABS_API_KEY must be set. Remove `eleven` to use the free Mac voice.'); const r = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${o.voice}/with-timestamps`, { method: 'POST', headers: { 'xi-api-key': key, 'content-type': 'application/json' }, body }); if (!r.ok) die(`ElevenLabs ${r.status}: ${await r.text()}`); fs.mkdirSync(path.dirname(cache), { recursive: true }); fs.writeFileSync(cache, await r.text()); } const take = JSON.parse(fs.readFileSync(cache)), { character_start_times_seconds: starts, character_end_times_seconds: ends } = take.alignment; if (starts.length !== text.length) die(`ElevenLabs timed ${starts.length} characters for a ${text.length}-character script. Keep \`say\` to plain text.`); const mp3 = path.join(tmp, 'take.mp3'), wav = path.join(tmp, 'take.wav'); fs.writeFileSync(mp3, Buffer.from(take.audio_base64, 'base64')); execFileSync('ffmpeg', ['-y', '-loglevel', 'error', '-i', mp3, '-ar', '48000', wav]); // Cut halfway through the pause between one beat's last character and the next beat's first, on a // whole millisecond, so the pieces land back together sample-exact. const cuts = [0]; let pos = 0; said.slice(0, -1).forEach(b => { pos += b.text.length + 1; cuts.push(Math.round((ends[pos - 2] + starts[pos]) * 500) / 1000); }); cuts.push(probe(wav)); return Object.fromEntries(said.map((b, k) => { const f = path.join(tmp, `${b.i}.wav`); execFileSync('ffmpeg', ['-y', '-loglevel', 'error', '-i', wav, '-af', `atrim=start=${cuts[k]}:end=${cuts[k + 1]}`, f]); return [b.i, f]; })); } // Optional local human voice: `kokoro: true` (or a voice name, or { voice, speed }) on the scene, or // KHAN_TTS=kokoro to try it on any scene. Free and offline after the first model download; it speaks // English, Spanish, French, Hindi, Italian, Japanese, Portuguese and Chinese. Takes are cached beside the scene. const KOKORO = { en: 'af_heart', 'en-gb': 'bf_emma', es: 'ef_dora', fr: 'ff_siwis', hi: 'hf_alpha', it: 'if_sara', ja: 'jf_alpha', pt: 'pf_dora', zh: 'zf_xiaobei' }; function kokoroTakes(meta, dir) { const o = typeof meta.kokoro === 'string' ? { voice: meta.kokoro } : meta.kokoro === true || !meta.kokoro ? {} : meta.kokoro; const voice = o.voice || KOKORO[meta.lang || 'en']; if (!voice) { if (meta.kokoro) die(`Kokoro does not speak lang '${meta.lang}'. It speaks ${Object.keys(KOKORO).join(', ')}.`); return null; // only KHAN_TTS asked for it: this language keeps the built-in voice } const said = meta.beats.map((b, i) => ({ i, text: b.say })).filter(b => b.text), speed = o.speed || 1; const cache = path.join(dir, '.voice', 'kokoro'); const lines = said.map(b => ({ i: b.i, text: b.text, out: path.join(cache, crypto.createHash('sha1').update(`${voice} ${speed} ${b.text}`).digest('hex').slice(0, 12) + '.wav') })); const todo = lines.filter(l => !fs.existsSync(l.out)); if (todo.length) { fs.mkdirSync(cache, { recursive: true }); const py = process.env.KHAN_PYTHON || 'python3'; const r = spawnSync(py, [path.join(__dirname, 'kokoro_tts.py')], { input: JSON.stringify({ voice, speed, lines: todo }), stdio: ['pipe', 'inherit', 'inherit'] }); if (r.status !== 0) die(`Kokoro failed. Install it with: ${py} -m pip install kokoro soundfile (set KHAN_PYTHON to use another Python)`); } return Object.fromEntries(lines.map(l => [l.i, l.out])); } (async () => { const browser = await chromium.launch(), page = await browser.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message)); await page.goto('file://' + path.join(__dirname, 'board.html')); // The scene gets its own scope: a scene variable named like a helper (box, line, ring) must not be a redeclaration error. await page.addScriptTag({ content: `(() => {\n${fs.readFileSync(path.resolve(sceneFile), 'utf8')}\n})();` }); const meta = await page.evaluate(() => window.sceneMeta()); if (errs.length || !meta) die(`scene failed to load: ${errs.join('; ') || 'scene({...}) was never called'}`); if (process.env.KHAN_THEME) await page.evaluate(t => window.setTheme(t), process.env.KHAN_THEME); // KHAN_THEME=light re-skins any scene // Screenshot backgrounds go in as data URLs: a file:// image would taint the canvas and block toDataURL. const dir = path.dirname(path.resolve(sceneFile)); const mime = f => 'image/' + ({ jpg: 'jpeg' }[path.extname(f).slice(1).toLowerCase()] || path.extname(f).slice(1).toLowerCase()); await page.evaluate(m => window.loadImages(m), Object.fromEntries(meta.bgs.map(f => [f, `data:${mime(f)};base64,` + fs.readFileSync(path.resolve(dir, f)).toString('base64')]))); const takes = meta.eleven && !meta.audio ? await elevenTakes(meta.beats, meta.eleven, dir) : null; const kok = !meta.audio && !takes && (meta.kokoro || process.env.KHAN_TTS === 'kokoro') ? kokoroTakes(meta, dir) : null; const voice = meta.audio || takes || kok ? null : voiceFor(meta); if (!meta.audio) console.log(`voice ${takes ? 'ElevenLabs' : kok ? 'Kokoro' : voice}`); const gap = meta.gap ?? (takes ? 0 : GAP); // scene-level `gap` slows the pace: more air between beats. One take already has its own pauses. let at = LEAD; const clips = []; let timings, total; if (meta.audio) { // Recorded voice: the audio file is the clock. Each beat starts at its `at` (seconds into the // file, from a word-level transcript) and draws until the next beat starts, or for its `dur`. const f = path.resolve(dir, meta.audio); total = probe(f) + TAIL / 2; // a short hold on the finished board after the last word clips.push({ f, at: 0 }); timings = meta.beats.map((b, i) => { if (typeof b.at !== 'number') die(`beat ${i + 1} needs \`at\` (seconds into ${meta.audio})`); const next = meta.beats[i + 1]?.at ?? total; if (next <= b.at) die(`beat ${i + 1} starts at ${b.at}s, not before the next beat (${next}s)`); return { start: b.at, dur: Math.min(b.dur || Infinity, next - b.at - 0.02) }; // finish a hair early, so the QA frame of a beat is not the next beat's wiped board }); } else { timings = meta.beats.map((b, i) => { let dur = b.dur || 1; if (b.say) { const f = takes ? takes[i] : kok ? kok[i] : tts(b.say, i, voice, meta.rate); dur = probe(f); clips.push({ f, at }); } const t = { start: at, dur: gap < 0.03 ? dur - 0.02 : dur }; // back to back, finish a hair early: the QA frame must not be the next beat's board at += dur + gap; return t; }); total = at - gap + TAIL; } await page.evaluate(t => window.setTimings(t), timings); await page.evaluate(() => document.fonts.ready); const args = ['-y', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(FPS), '-c:v', 'mjpeg', '-i', '-']; clips.forEach(c => args.push('-i', c.f)); if (clips.length) { const delayed = clips.map((c, i) => `[${i + 1}:a]aresample=48000,adelay=${Math.round(c.at * 1000)}:all=1[a${i}]`).join(';'); const mix = clips.map((_, i) => `[a${i}]`).join('') + `amix=inputs=${clips.length}:normalize=0,apad[a]`; args.push('-filter_complex', `${delayed};${mix}`, '-map', '0:v', '-map', '[a]', '-c:a', 'aac', '-b:a', '160k', '-ac', '2'); } args.push('-t', total.toFixed(3), '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '18', '-movflags', '+faststart', out); const ff = spawn('ffmpeg', args, { stdio: ['pipe', 'inherit', 'inherit'] }); for (let i = 0; i < Math.ceil(total * FPS); i++) { const buf = jpeg(await page.evaluate(t => window.frame(t), i / FPS)); if (!ff.stdin.write(buf)) await once(ff.stdin, 'drain'); } ff.stdin.end(); await once(ff, 'close'); // QA sheet: the board as it stands at the end of every beat, tiled into one image. for (let i = 0; i < timings.length; i++) fs.writeFileSync(path.join(tmp, `b${String(i).padStart(3, '0')}.jpg`), jpeg(await page.evaluate(t => window.frame(t), timings[i].start + timings[i].dur + 0.01))); // +0.01: land past the beat's last stroke const sheet = path.join(tmp, 'sheet.jpg'); const cols = meta.size[0] < meta.size[1] ? 6 : 3; // a vertical board tiles six across so the sheet stays readable execFileSync('ffmpeg', ['-y', '-loglevel', 'error', '-framerate', '1', '-i', path.join(tmp, 'b%03d.jpg'), '-vf', `scale=${cols === 3 ? 640 : 300}:-1,tile=${cols}x${Math.ceil(timings.length / cols)}`, '-frames:v', '1', sheet]); const warns = await page.evaluate(() => window.warnings()); await browser.close(); timings.forEach((t, i) => console.log(`beat ${i + 1} ${t.start.toFixed(2)}s +${t.dur.toFixed(2)}s ${meta.beats[i].say || (meta.audio ? '' : '(silent)')}`)); warns.forEach(w => console.log('WARN ' + w)); console.log('sheet ' + sheet); const got = probe(out); if (Math.abs(got - total) > 0.1) die(`FAIL ${out} is ${got}s, expected ${total.toFixed(2)}s`); console.log(`ok ${out} ${got.toFixed(2)}s`); })().catch(e => die(e.stack || String(e)));scripts/talking_head_example.sh2.8 KBddb4dad65a21upstream ↗
#!/bin/bash # Talking-head version of one clip: the board moves up and shrinks, and the speaker, cut out of the # source video, stands in front of it at the bottom. # usage: talking_head_example.sh <clip-folder> <source-video> [light] # <clip-folder> is one of clip_audio.py's folders, with its scene already rendered there as out.mp4 # (and out-light.mp4 for the light version). The cutout is the slow part, so it is made once per clip # (cutout.mov) and reused for every look. # CROP (w:h:x:y) is where the speaker sits in the source frame. The default fits one 1920x1080 video: # look at a frame of yours and set your own, above any captions burned onto the speaker. set -e -o pipefail [ -d "$1" ] && [ -f "$2" ] || { echo "usage: $0 <clip-folder> <source-video> [light]"; exit 1; } K="$(cd "$(dirname "$0")" && pwd)"; c="$1"; CUT="$K/cutout"; CROP="${CROP:-1000:780:460:50}" W=$(echo "$CROP" | cut -d: -f1); H=$(echo "$CROP" | cut -d: -f2) [ -x "$CUT" ] || swiftc -O "$K/cutout.swift" -o "$CUT" if [ ! -s "$c/cutout.mov" ]; then src=$(head -1 "$c/words.txt" | sed -E 's/.*\(source ([0-9]+):([0-9.]+) to.*/\1 \2/') t0=$(echo $src | awk '{printf "%.2f", $1*60+$2}') dur=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$c/audio.wav") ffmpeg -v error -ss "$t0" -t "$dur" -i "$2" -vf "fps=30,crop=$CROP" -f rawvideo -pix_fmt bgra - \ | "$CUT" "$W" "$H" \ | ffmpeg -y -v error -f rawvideo -pix_fmt bgra -s "${W}x${H}" -r 30 -i - -vf "scale=780:-2:flags=lanczos" \ -c:v prores_ks -profile:v 4444 -pix_fmt yuva444p10le -an "$c/cutout.tmp.mov" mv "$c/cutout.tmp.mov" "$c/cutout.mov" fi if [ "$3" = light ]; then board="$c/out-light.mp4"; bg=0xFBFBF8; out="$c/head-light.mp4"; else board="$c/out.mp4"; bg=0x111111; out="$c/head.mp4"; fi # Soft left and right edges: shoulders and hands that run past the crop fade out instead of ending in a straight line. dim=$(ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0:s=x "$c/cutout.mov") ffmpeg -y -v error -i "$c/cutout.mov" -i "$board" -f lavfi -i "color=white:s=$dim:d=1,format=gray,geq=lum='255*min(1,min(X,W-1-X)/90)'" -filter_complex " color=c=$bg:s=1080x1920:r=30[bg]; [1:v]crop=1080:1410:0:150,scale=842:1100:flags=lanczos[b]; [bg][b]overlay=(W-w)/2:110:shortest=1[v1]; [2:v]trim=end_frame=1,loop=loop=-1:size=1,setpts=N/30/TB[m]; [0:v]format=yuva420p,split[hc][ha]; [ha]alphaextract[a0]; [a0][m]blend=all_mode=multiply:shortest=1[a1]; [hc][a1]alphamerge,tpad=stop_mode=clone:stop_duration=2[h]; [v1][h]overlay=(W-w)/2:1100:shortest=1[v]" \ -map "[v]" -map 1:a -c:a copy -c:v libx264 -crf 18 -pix_fmt yuv420p -movflags +faststart "$out.tmp.mp4" mv "$out.tmp.mp4" "$out" echo "$(basename "$c") ${3:-dark} $(ffprobe -v error -show_entries format=duration -of csv=p=0 "$out")s".github/workflows/render.yml2.4 KBb4ea78396debupstream ↗
name: render on: push: branches: [main] pull_request: workflow_dispatch: jobs: render: strategy: fail-fast: false matrix: os: [macos-latest, ubuntu-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 - name: Tools (macOS) if: runner.os == 'macOS' run: | brew install ffmpeg say -v '?' - name: Tools (Linux) if: runner.os == 'Linux' run: sudo apt-get update -qq && sudo apt-get install -y -qq ffmpeg espeak-ng fonts-noto-core fonts-noto-cjk fonts-noto-extra - name: Playwright working-directory: scripts run: npm ci && npx playwright install --with-deps chromium - name: Faces each script gets run: node tests/fonts.js - name: Render examples and languages run: node tests/run.js out - uses: actions/upload-artifact@v4 if: always() with: name: render-${{ matrix.os }} path: out/ kokoro: strategy: fail-fast: false matrix: os: [macos-latest, ubuntu-latest] runs-on: ${{ matrix.os }} env: KHAN_TTS: kokoro steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 - uses: actions/setup-python@v5 with: python-version: '3.12' - name: Tools (macOS) if: runner.os == 'macOS' run: brew install ffmpeg espeak-ng - name: Tools (Linux) if: runner.os == 'Linux' run: sudo apt-get update -qq && sudo apt-get install -y -qq ffmpeg espeak-ng fonts-noto-core fonts-noto-cjk fonts-noto-extra - name: Kokoro run: | pip install torch --index-url https://download.pytorch.org/whl/cpu pip install kokoro soundfile "misaki[ja]" "misaki[zh]" pip install unidic && python -m unidic download echo "KHAN_PYTHON=$(which python)" >> "$GITHUB_ENV" - name: Playwright working-directory: scripts run: npm ci && npx playwright install --with-deps chromium - name: Render with Kokoro where it speaks the language run: node tests/run.js out - uses: actions/upload-artifact@v4 if: always() with: name: kokoro-${{ matrix.os }} path: out/.gitignore58 B6201674c7269upstream ↗
node_modules/ scripts/cutout .voice/ .DS_Store *.mp4 out/docs/board.jpg85 KB011713c687beupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
examples/ai-agents.js1.9 KB768943c4fcb5upstream ↗
// A 12-second lesson: the agent loop. Copy this file as the starting point for a new scene. // Each beat = one spoken clause + what the pen draws while it is being said. scene({ beats: [ { say: 'What is an AI agent?', draw: p => { write('What is an AI agent?', 60, 85, seg(p, 0, .8), { size: 56, color: C.yellow }); stroke(curve([58, 104], [590, 102], [320, 112]), seg(p, .8, 1), { color: C.yellow, width: 4 }); } }, { say: "It's software that uses a language model to think,", draw: p => { stroke(oval(300, 330, 155, 82), seg(p, 0, .4), { color: C.blue }); write('1. THINK', 300, 328, seg(p, .4, .7), { size: 40, color: C.blue, center: true }); write('language model', 300, 364, seg(p, .7, 1), { size: 26, center: true }); } }, { say: 'picks a tool, and acts.', draw: p => { arrow([455, 290], [825, 290], seg(p, 0, .3), { ctrl: [640, 215] }); stroke(oval(980, 330, 155, 82), seg(p, .25, .55), { color: C.orange }); write('2. ACT', 980, 328, seg(p, .55, .75), { size: 40, color: C.orange, center: true }); write('uses a tool', 980, 364, seg(p, .75, 1), { size: 26, center: true }); } }, { say: 'Then it looks at the result,', draw: p => { arrow([965, 420], [818, 592], seg(p, 0, .3), { ctrl: [945, 545] }); stroke(oval(640, 600, 175, 76), seg(p, .25, .55), { color: C.pink }); write('3. OBSERVE', 640, 598, seg(p, .55, .75), { size: 40, color: C.pink, center: true }); write('checks the result', 640, 634, seg(p, .75, 1), { size: 26, center: true }); } }, { say: 'and repeats until the goal is done.', draw: p => { arrow([462, 592], [318, 420], seg(p, 0, .3), { ctrl: [338, 545] }); write('repeat until', 640, 405, seg(p, .3, .6), { size: 34, color: C.yellow, center: true }); write('goal done', 620, 455, seg(p, .6, .9), { size: 42, color: C.green, center: true }); check(738, 418, seg(p, .9, 1)); } }, ], });examples/arabic.js1.2 KBf38a26cf8db6upstream ↗
// A 12-second lesson with right-to-left writing. For Arabic or Hebrew, `x` is the right end of the // text, where the pen starts, and the word is uncovered right to left. The voice still speaks English, // so `say` spells the sound ("kitaab") while the board shows the real word. scene({ beats: [ { say: 'Arabic is written from right to left.', draw: p => { write('Right to left', 60, 85, seg(p, 0, .5), { size: 56, color: C.yellow }); arrow([1210, 150], [800, 150], seg(p, .5, 1), { color: C.yellow }); } }, { say: 'This word is kitaab: a book.', draw: p => { write('كِتَابٌ', 1200, 320, seg(p, 0, .6), { size: 130 }); write('kitaab: a book', 620, 310, seg(p, .6, 1), { size: 40, color: C.blue }); } }, { say: 'And this one is jadeed: new.', draw: p => { write('جَدِيدٌ', 1200, 490, seg(p, 0, .6), { size: 130, color: C.orange }); write('jadeed: new', 620, 480, seg(p, .6, 1), { size: 40, color: C.orange }); } }, { say: 'Together they say: a new book.', draw: p => { write('كِتَابٌ جَدِيدٌ', 640, 660, seg(p, 0, .7), { size: 110, color: C.green, center: true }); check(960, 610, seg(p, .7, 1)); } }, ], });examples/languages.js2.3 KBe0314fa6e621upstream ↗
// One word, "book", in eight languages, each written the way it is written by hand. Arabic, Urdu and Hebrew // start at their right end (`x` is where the pen starts); everything else runs left to right. Urdu shares // Arabic's letters, so `lang: 'ur'` asks for its nastaliq hand. The voice speaks English throughout. scene({ beats: [ { say: 'Every language writes the word book its own way.', draw: p => { write('book', 60, 85, seg(p, 0, .5), { size: 60, color: C.yellow }); stroke(line([60, 110], [1220, 110]), seg(p, .5, 1), { color: C.yellow, width: 3 }); } }, { say: 'Arabic runs from right to left,', draw: p => { write('كِتَابٌ', 1220, 250, seg(p, 0, .7), { size: 100 }); write('Arabic', 700, 230, seg(p, .7, 1), { size: 34, color: C.blue }); } }, { say: 'and Urdu uses the same letters in a slanting hand.', draw: p => { write('کتاب', 1220, 410, seg(p, 0, .7), { size: 70, color: C.orange, lang: 'ur' }); write('Urdu', 700, 380, seg(p, .7, 1), { size: 34, color: C.blue }); } }, { say: 'Hebrew runs right to left as well.', draw: p => { write('סֵפֶר', 1220, 560, seg(p, 0, .7), { size: 100, color: C.pink }); write('Hebrew', 700, 530, seg(p, .7, 1), { size: 34, color: C.blue }); arrow([1220, 640], [900, 640], seg(p, .7, 1), { color: C.yellow }); } }, { say: 'Hindi hangs every letter from one line.', draw: p => { write('किताब', 60, 250, seg(p, 0, .7), { size: 90, color: C.green }); write('Hindi', 380, 230, seg(p, .7, 1), { size: 34, color: C.blue }); } }, { say: 'Chinese, Japanese and Korean fill a square for each sound.', draw: p => { write('书', 60, 400, seg(p, 0, .3), { size: 90, color: C.purple }); write('本', 170, 400, seg(p, .3, .6), { size: 90, color: C.purple }); write('책', 280, 400, seg(p, .6, .9), { size: 90, color: C.purple }); write('CJK', 420, 380, seg(p, .9, 1), { size: 34, color: C.blue }); } }, { say: 'And Russian has an alphabet of its own.', draw: p => { write('книга', 60, 550, seg(p, 0, .7), { size: 80, color: C.red }); write('Russian', 380, 530, seg(p, .7, 1), { size: 34, color: C.blue }); arrow([60, 640], [380, 640], seg(p, .7, 1), { color: C.yellow }); } }, ], });examples/shots/clone.jpg193 KB3f76e3bd7a98upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
examples/shots/repo.jpg196 KB8bf3090c7767upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
examples/ui-tutorial.js1.8 KB16ce5c112af1upstream ↗
// A draw-over-UI tutorial in 4 beats. Copy this for product walkthroughs. // The stills are Playwright captures at a 1280x720 viewport (deviceScaleFactor 1.5), so CSS pixels // are board units. Every rectangle below is a getBoundingClientRect() value read while capturing, // passed through view() untouched. With a capture of another width, change the 1280. // Labels float in empty space, so they are placed in board units (1280x720) directly. const page = view(1280); const codeBtn = { x: 827, y: 265, w: 109, h: 32 }; const cloneUrl = { x: 552, y: 390, w: 332, h: 32 }, copyBtn = { x: 888, y: 390, w: 32, h: 32 }; // measured again with the menu open scene({ rate: 150, gap: 0.6, // tutorial pace: slower voice, more air between beats beats: [ { bg: 'shots/repo.jpg', say: 'On the repo page, press the green Code button.', draw: p => { stroke(ring(page.r(codeBtn), 10), seg(p, .3, .65), { color: C.yellow }); write('1. Press Code', 560, 222, seg(p, .65, .92), { size: 40, color: C.yellow }); arrow([800, 232], page.p(846, 256), seg(p, .92, 1), { color: C.yellow }); } }, { bg: 'shots/clone.jpg', say: 'A menu opens, with a link to the code.', draw: p => { stroke(around(page.r(cloneUrl), 5), seg(p, .35, 1), { color: C.blue }); } }, { say: 'Press the two squares to copy it.', draw: p => { stroke(ring(page.r(copyBtn), 7), seg(p, 0, .35), { color: C.pink }); write('2. Copy it', 640, 338, seg(p, .35, .8), { size: 34, color: C.pink }); arrow([800, 344], page.p(892, 384), seg(p, .8, 1), { color: C.pink }); } }, { say: 'Then paste it to Claude Code, and ask for your first video.', draw: p => { write('3. Paste it to Claude Code', 300, 222, seg(p, .1, .8), { size: 40, color: C.green }); } }, ], });LICENSE1.0 KB038915c8de2eupstream ↗
MIT License Copyright (c) 2026 Haider Farooq Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.tests/fonts.js1.7 KBdf4c82749156upstream ↗
#!/usr/bin/env node // Which face each script actually gets on this machine: node tests/fonts.js // A face counts as installed when text set in it measures differently from the same text in two generic fallbacks. const path = require('path'); const { chromium } = require(path.join(__dirname, '../scripts/node_modules/playwright')); const SAMPLE = { Hebrew: 'ספר', Urdu: 'نئی کتاب', Arabic: 'كتاب', Syriac: 'ܟܬܒܐ', Devanagari: 'किताब', Bengali: 'নতুন বই', Gurmukhi: 'ਕਿਤਾਬ', Gujarati: 'પુસ્તક', Tamil: 'புத்தகம்', Telugu: 'పుస్తకం', Kannada: 'ಪುಸ್ತಕ', Thai: 'หนังสือ', Kana: 'あたらしい', Hangul: '새 책', Han: '新书', Cyrillic: 'книга' }; (async () => { const b = await chromium.launch(), pg = await b.newPage(); await pg.goto('file://' + path.join(__dirname, '../scripts/board.html')); const rows = await pg.evaluate(SAMPLE => { const c = document.createElement('canvas').getContext('2d'), w = (f, s) => { c.font = `40px ${f}`; return c.measureText(s).width; }; const has = (fam, s) => ['monospace', 'serif'].some(g => w(`"${fam}",${g}`, s) !== w(g, s)); const name = k => k.urdu ? 'Urdu' : (k.re.source.match(/Script=(\w+)/) || [])[1]?.replace(/^Hiragana$/, 'Kana') || '?'; return SCRIPTS.map(k => { const n = name(k), s = SAMPLE[n] || ''; const fams = k.face.split(',').map(f => f.replace(/"/g, '')); return { script: n, uses: s ? fams.find(f => has(f, s)) || 'NONE (system fallback)' : '-', tried: fams.join(', ') }; }); }, SAMPLE); await b.close(); rows.forEach(r => console.log(`${r.script.padEnd(11)} ${r.uses.padEnd(28)} (${r.tried})`)); })();tests/languages/ar.js481 B7b16eca495ddupstream ↗
// "A new book" in ar: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'ar', beats: [ { say: "كِتَابٌ", draw: p => write("كِتَابٌ", 1200, 260, p, { size: 130 }) }, { say: "هذا كتاب جديد.", draw: p => write("كِتَابٌ جَدِيدٌ", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: كِتَابٌ", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/languages/bn.js465 Bac9060c73e9cupstream ↗
// "A new book" in bn: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'bn', beats: [ { say: "বই", draw: p => write("বই", 80, 260, p, { size: 130 }) }, { say: "এটা একটা নতুন বই।", draw: p => write("নতুন বই", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: বই", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/languages/el.js485 B84736776fb31upstream ↗
// "A new book" in el: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'el', beats: [ { say: "βιβλίο", draw: p => write("βιβλίο", 80, 260, p, { size: 130 }) }, { say: "Αυτό είναι ένα νέο βιβλίο.", draw: p => write("νέο βιβλίο", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: βιβλίο", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/languages/es.js432 Bd404ae50ffb6upstream ↗
// "A new book" in es: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'es', beats: [ { say: "libro", draw: p => write("libro", 80, 260, p, { size: 130 }) }, { say: "Este es un libro nuevo.", draw: p => write("libro nuevo", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: libro", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/languages/fa.js455 B8f7f77c119a4upstream ↗
// "A new book" in fa: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'fa', beats: [ { say: "کتاب", draw: p => write("کتاب", 1200, 260, p, { size: 130 }) }, { say: "این یک کتاب نو است.", draw: p => write("کتاب نو", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: کتاب", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/languages/fr.js434 B3290ee2182a4upstream ↗
// "A new book" in fr: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'fr', beats: [ { say: "livre", draw: p => write("livre", 80, 260, p, { size: 130 }) }, { say: "Voici un nouveau livre.", draw: p => write("nouveau livre", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: livre", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/languages/he.js457 B48420777fbd7upstream ↗
// "A new book" in he: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'he', beats: [ { say: "סֵפֶר", draw: p => write("סֵפֶר", 1200, 260, p, { size: 130 }) }, { say: "זה ספר חדש.", draw: p => write("סֵפֶר חָדָשׁ", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: סֵפֶר", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/languages/hi.js496 B25970823f7dfupstream ↗
// "A new book" in hi: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'hi', beats: [ { say: "किताब", draw: p => write("किताब", 80, 260, p, { size: 130 }) }, { say: "यह एक नई किताब है।", draw: p => write("नई किताब", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: किताब", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/languages/ja.js434 Bdc60e01f9781upstream ↗
// "A new book" in ja: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'ja', beats: [ { say: "本", draw: p => write("本", 80, 260, p, { size: 130 }) }, { say: "これは新しい本です。", draw: p => write("新しい本", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: 本", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/languages/ko.js426 Bcfd1b213efa4upstream ↗
// "A new book" in ko: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'ko', beats: [ { say: "책", draw: p => write("책", 80, 260, p, { size: 130 }) }, { say: "이것은 새 책입니다.", draw: p => write("새 책", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: 책", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/languages/ru.js463 Bc7ada945dfefupstream ↗
// "A new book" in ru: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'ru', beats: [ { say: "книга", draw: p => write("книга", 80, 260, p, { size: 130 }) }, { say: "Это новая книга.", draw: p => write("новая книга", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: книга", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/languages/ta.js556 B5796351d37d2upstream ↗
// "A new book" in ta: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'ta', beats: [ { say: "புத்தகம்", draw: p => write("புத்தகம்", 80, 260, p, { size: 130 }) }, { say: "இது ஒரு புதிய புத்தகம்.", draw: p => write("புதிய புத்தகம்", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: புத்தகம்", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/languages/th.js530 Be39e826f0f04upstream ↗
// "A new book" in th: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'th', beats: [ { say: "หนังสือ", draw: p => write("หนังสือ", 80, 260, p, { size: 130 }) }, { say: "นี่คือหนังสือใหม่", draw: p => write("หนังสือใหม่", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: หนังสือ", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/languages/ur.js458 B033c671ce183upstream ↗
// "A new book" in ur: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'ur', beats: [ { say: "کتاب", draw: p => write("کتاب", 1200, 260, p, { size: 130 }) }, { say: "یہ ایک نئی کتاب ہے۔", draw: p => write("نئی کتاب", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: کتاب", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/languages/zh.js419 B10210d38e12bupstream ↗
// "A new book" in zh: the word, the phrase, then the same phrase quoted in a Latin label. scene({ lang: 'zh', beats: [ { say: "书", draw: p => write("书", 80, 260, p, { size: 130 }) }, { say: "这是一本新书。", draw: p => write("新书", 640, 500, p, { size: 110, color: C.orange, center: true }) }, { dur: 1, draw: p => write("book: 书", 640, 660, p, { size: 50, color: C.blue, center: true }) }, ]});tests/run.js1.6 KB791171a41c72upstream ↗
#!/usr/bin/env node // Render every example and every language scene, and fail on any WARN or FAIL: node tests/run.js [outDir] // A language with no built-in voice on this machine is reported as skipped, not failed. const { spawnSync } = require('child_process'); const fs = require('fs'), path = require('path'); const root = path.join(__dirname, '..'), out = path.resolve(process.argv[2] || path.join(root, 'out')); fs.mkdirSync(out, { recursive: true }); const scenes = [...fs.readdirSync(path.join(root, 'examples')).filter(f => f.endsWith('.js')).map(f => path.join(root, 'examples', f)), ...fs.readdirSync(path.join(__dirname, 'languages')).filter(f => f.endsWith('.js')).map(f => path.join(__dirname, 'languages', f))]; let bad = 0; for (const f of scenes) { const name = path.basename(f, '.js'), mp4 = path.join(out, name + '.mp4'); const r = spawnSync('node', [path.join(root, 'scripts/render.js'), f, mp4], { encoding: 'utf8' }); const log = r.stdout + r.stderr, sheet = (log.match(/^sheet (.+)$/m) || [])[1]; if (sheet) fs.copyFileSync(sheet, path.join(out, name + '-sheet.jpg')); const warns = log.split('\n').filter(l => l.startsWith('WARN')); let verdict = r.status === 0 && !warns.length ? 'ok' : 'FAIL'; if (r.status !== 0 && /no built-in voice|is not installed/.test(log)) verdict = 'skip'; if (verdict === 'FAIL') bad++; console.log(`${verdict.padEnd(4)} ${name.padEnd(12)} ${(log.match(/^ok .* ([\d.]+s)$/m) || [])[1] || ''}`); if (verdict !== 'ok') console.log(' ' + (warns.join('\n ') || log.trim().split('\n').slice(-8).join('\n '))); } console.log(bad ? `${bad} failed` : 'all passed'); process.exit(bad ? 1 : 0);
Plain-text copy, no login: /skill-bundles/haiderfarooq3-khan-explainer.md