diff --git a/.claude/skills/screencast/SKILL.md b/.claude/skills/screencast/SKILL.md new file mode 100644 index 0000000000..76ff101ad6 --- /dev/null +++ b/.claude/skills/screencast/SKILL.md @@ -0,0 +1,137 @@ +--- +name: screencast +description: Make a short narrated video screencast of a Sheprd feature, recorded in a virtual Mac, voiced by ElevenLabs in English and French, in the classic and Moonframe windows, with a captioned cut for Twitter/X and an .srt for YouTube. Use when the user asks for a screencast, demo video, feature video, or a clip of what a release adds for Twitter/X, YouTube, or the website. +--- + +# Feature screencasts + +One feature, one video of 30 seconds at most, per window and language. The +tooling lives in `scripts/screencast/` (read its `README.md` first): a feature +file says what to do in the app and what to say, and `screencast.py` voices +it, records it once per window in the `agent-test` machine, and renders the +MP4s. Never record the user's own desktop: their display is shared and their +workspaces are private. + +## 1. Pick the feature + +For a release, read what it adds, then agree on one feature per video with +the user: + +```sh +gh release view -R sheprd-labs/sheprd --json tagName,body -q '.tagName, .body' +``` + +`design/sheprd-website/assets/features.js` lists every feature with a one-line +description, which makes a good first narration line. + +## 2. Put the build in the machine + +The machine must run the build that has the feature, at +`/Users/admin/Apps/Sheprd.app`. Keep the one it replaces in `~/Apps/old`. + +- **A published release:** download `sheprd-VERSION-macos-universal.app.tar.gz` + with `gh release download`, then push it in as below. +- **Unreleased `main`:** build outside a Git worktree, or the window shows a + worktree banner: `git archive HEAD | tar -x -C DIR`, symlink a warm + `target/` into `DIR`, then `just bundle` there. + +Push a file in through the agent: `base64 | split -a 4 -b 190000`, then per +chunk `sheprd machine exec agent-test -- sh -c 'printf %s "$1" | base64 -D >> +/tmp/Sheprd.zip' _ "$(cat CHUNK)"`. Compare `shasum` on both sides before +unpacking. Quit Sheprd in the machine first (bring it to the front with `open +~/Apps/Sheprd.app`, then `machine key agent-test cmd+q`). + +## 3. Check the machine + +- `sheprd machine list`: `agent-test` running at 2560x1440. `sheprd machine + agent agent-test` answers with both permissions. +- Take a `machine screenshot` and look at it: awake, unlocked (password + `admin`), no Finder window or dialog in front, and no other session using + the machine. If another agent's build or tabs are there, ask before + replacing them. + +## 4. Write the feature file + +Copy `scripts/screencast/features/themes.json` to `features/NAME.json`: + +- `title`: shown over the first segment, per language. +- `setup`: puts the app in a known state before recording: reset what the + last run changed, open a clean terminal. Not recorded. +- `segments`: 4 to 6, each one sentence in `say` (en and fr, plus the other + languages' text so they are ready) and the `actions` shown while it plays: + `["key", "cmd+shift+p"]`, `["type", "text"]`, `["slowtype", "text", 0.05]`, + `["click", x, y]` in screenshot pixels, `["wait", seconds]`, + `["repeat", n, [actions]]`. +- `teardown`: undo what the video changed, such as the theme. + +Narration: plain words a new user understands, the action before the result, +no keyboard-shortcut captions on visible buttons. Keep the total of the +longest takes under about 25 seconds; the script prints segment times. + +Work out every click position from a screenshot first, and walk the steps by +hand with `sheprd machine key/type/click` and a screenshot after each, before +recording. + +## 5. Record and render + +```sh +set -a; source .envrc; set +a # ELEVENLABS_API_KEY; .envrc is git-ignored +python3 scripts/screencast/screencast.py scripts/screencast/features/NAME.json +python3 scripts/screencast/screencast.py scripts/screencast/features/NAME.json \ + --skip-record --captions --langs en # the Twitter/X cut from the same take +``` + +The key lives in the `.envrc` of the checkout that made the first videos; +copy that line, never print the key. Defaults: both windows +(`--window classic,moonframe`), English and French, River in English and +Julien in French (`scripts/screencast/README.md`, Voices). Spoken lines are +cached, so re-renders cost no characters. + +Outputs, under `target/screencasts/WINDOW/elevenlabs-river/`: + +| File | For | +| --- | --- | +| `NAME.LANG.mp4` | YouTube and the website, no captions | +| `NAME.LANG.srt` | YouTube's subtitle upload | +| `NAME.en.captioned.mp4` | Twitter/X, which autoplays muted | + +All are 1920x1080 H.264 with AAC, which Twitter/X, YouTube and the site take +as is. + +## 6. Check before showing anyone + +Tile the video and look at every second against the narration: + +```sh +ffmpeg -v error -i OUT.mp4 -vf "fps=1,scale=240:-1,tile=6x5" -frames:v 1 tile.png +``` + +Each action must appear while its sentence plays, with nothing else on screen +(no Finder, dialog, or error in the status bar). If the app shows a bug, stop +and tell the user rather than recording around it. + +## 7. Hand it over + +Push the MP4s to the orphan `screencast-previews` branch (under +`FEATURE/WINDOW/`) and link the GitHub pages, which play on a phone. Posting to +Twitter/X or YouTube, or publishing the website, is the user's call: never do +it without their explicit go-ahead for that post. + +## Gotchas + +- `screencapture -v` writes a frame only when the screen changes and its movie + ends at the last one; the script turns on the menu bar clock's seconds so it + keeps going. It can also take about ten seconds to start, which the script + waits for and trims. +- Command-Q and keys go to the front app: bring Sheprd to the front with + `open ~/Apps/Sheprd.app` before them. A click on the desktop raises Finder. +- After a dialog closes or the app relaunches, click inside the window + before typing. +- Window > Fill (`ctrl+fn+f`) maximizes; a title bar double-click toggles. +- A theme set in a run sticks: `setup` must reset it. +- `machine exec` keeps only the last 64 KB of output and refuses `rm` inside + `sh -c`; truncate with `cp /dev/null FILE`. `osascript` hangs on a hidden + permission prompt: don't use it. +- Moonframe can draw with Rune only in apps written wholly in Luau. Sheprd's + terminals and pages are a GPUI view, so there is no Rune version of Sheprd + to record yet. diff --git a/.gitattributes b/.gitattributes index f27fdf3373..1cbefb04f1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -22,3 +22,9 @@ crates/sheprd-relay/src/tests/fixtures/** -text website/site/relays.json -text website/site/relays.json.asc -text website/site/relays.json.sig -text +# Videos, such as the feature screencasts scripts/screencast renders, go to +# Git LFS so clones and history stay small. Deploys that serve them need LFS +# fetched (Netlify: GIT_LFS_ENABLED=true). +*.mov filter=lfs diff=lfs merge=lfs -text +*.mp4 filter=lfs diff=lfs merge=lfs -text +*.webm filter=lfs diff=lfs merge=lfs -text diff --git a/.githooks/post-checkout b/.githooks/post-checkout new file mode 100755 index 0000000000..9a2684c354 --- /dev/null +++ b/.githooks/post-checkout @@ -0,0 +1,5 @@ +#!/bin/sh +# Git LFS keeps the videos (.gitattributes). Its own hooks fail without +# git-lfs installed; these do nothing then, so other work is unaffected. +command -v git-lfs >/dev/null 2>&1 || exit 0 +exec git lfs post-checkout "$@" diff --git a/.githooks/post-commit b/.githooks/post-commit new file mode 100755 index 0000000000..50d11c09cc --- /dev/null +++ b/.githooks/post-commit @@ -0,0 +1,5 @@ +#!/bin/sh +# Git LFS keeps the videos (.gitattributes). Its own hooks fail without +# git-lfs installed; these do nothing then, so other work is unaffected. +command -v git-lfs >/dev/null 2>&1 || exit 0 +exec git lfs post-commit "$@" diff --git a/.githooks/post-merge b/.githooks/post-merge new file mode 100755 index 0000000000..f819a117a8 --- /dev/null +++ b/.githooks/post-merge @@ -0,0 +1,5 @@ +#!/bin/sh +# Git LFS keeps the videos (.gitattributes). Its own hooks fail without +# git-lfs installed; these do nothing then, so other work is unaffected. +command -v git-lfs >/dev/null 2>&1 || exit 0 +exec git lfs post-merge "$@" diff --git a/.githooks/pre-push b/.githooks/pre-push new file mode 100755 index 0000000000..5077f7d700 --- /dev/null +++ b/.githooks/pre-push @@ -0,0 +1,5 @@ +#!/bin/sh +# Git LFS keeps the videos (.gitattributes). Its own hooks fail without +# git-lfs installed; these do nothing then, so other work is unaffected. +command -v git-lfs >/dev/null 2>&1 || exit 0 +exec git lfs pre-push "$@" diff --git a/scripts/screencast/README.md b/scripts/screencast/README.md new file mode 100644 index 0000000000..821c800172 --- /dev/null +++ b/scripts/screencast/README.md @@ -0,0 +1,67 @@ +# Feature screencasts + +Short narrated videos, one per feature, one MP4 per language, recorded in a +virtual Mac so nobody's own desktop or sessions show. + +```sh +set -a; source .envrc; set +a # ELEVENLABS_API_KEY (git-ignored) +python3 scripts/screencast/screencast.py scripts/screencast/features/themes.json +``` + +Each feature is recorded once per window (`--window classic,moonframe`, both +by default), so viewers can pick the look they use: the script quits Sheprd +in the machine and reopens it with that window's arguments (`WINDOWS` in +`screencast.py`) before recording, and keeps `preflight.png` of how it came +up. Add a window there (Rune is planned) with its arguments and the share of +the screen its maximized window fills. + +- `features/NAME.json`: the steps Sheprd is driven through (`sheprd machine + key/type/click`) and the narration of each segment in every language. +- `screencast.py`: voices every segment, records the machine once with each + segment as long as its longest take, then renders + `target/screencasts/WINDOW/elevenlabs-VOICE/NAME.LANG.mp4` and an `.srt` per + language for YouTube's subtitles. `--captions` burns them in instead. +- `tts.py`: ElevenLabs (also OpenAI and macOS `say`, which were rejected). + Spoken lines are cached in `target/screencasts/tts-cache`, so a re-render + costs no characters until the narration changes. + +Videos committed to the repository (the website's clips, for example) are +stored with Git LFS (`.gitattributes`): run `git lfs install` once per machine +before committing one. + +## Voices + +Chosen by listening to tryouts on 2026-11-22. The model is `eleven_v4`, with +each language's `language_code`. + +| Language | Voice | Notes | +| --- | --- | --- | +| English and the default | River (`SAz9YHcvj6GT2YYXdXww`), or Eric (`cjVigY5qzO86Huf0OWal`) | Both liked; not yet decided. Premade voices, so ElevenLabs publishes no usage for either. | +| French | Julien, friendly tech explainer (`VuE88ydpXAhBTNxFI7WF`) | Native fr-FR. Fallback: Damien Doré, deep narrator (`kSNoLVC4Ox0vkBz1IKux`). | + +Videos are made in English and French only for now (`screencast.py`'s +`LANGS`). The feature files keep narration for de, es, pt-BR, ja and zh-CN. + +**Rule: every language gets a native voice.** Nobody on the team can judge +the other languages by ear, so before adding one, pick its voice from the +ElevenLabs library by data, not by listening: `locale` of that country +(de-DE, es-ES, pt-BR, ja-JP, zh-CN), `accent` "standard" (or the capital's), +a use case of `informative_educational` or `narrative_story`, and the most +users (`cloned_by_count`) and characters in the last year. Add it to +`ELEVENLABS_VOICES` and `ELEVENLABS_NATIVE` and to the table above, with a +fallback. + +The English voices speak French with a Canadian accent, so a language with a +native pick in `tts.ELEVENLABS_NATIVE` uses it whatever voice is named on the +command line. `ELEVENLABS_VOICE_FR=damien` (or any voice ID) overrides it for +one run. + +## The machine + +- The `agent-test` machine runs a build of `main` at `~/Apps/Sheprd.app` with + the Dock hidden, built outside a Git worktree (`git archive` into a plain + folder, then `just bundle`) so it shows no worktree banner. Older builds + are in `~/Apps/old`. Its display is a fixed 2560×1440 (`sheprd machine set + agent-test --display 2560x1440`, applied at its next boot), so videos are + 16:9 with no bars; a display that follows its tab would change shape. +- Wake and unlock it first (`admin`), and check no other session is using it. diff --git a/scripts/screencast/features/themes.json b/scripts/screencast/features/themes.json new file mode 100644 index 0000000000..c2947a5d8f --- /dev/null +++ b/scripts/screencast/features/themes.json @@ -0,0 +1,290 @@ +{ + "id": "themes", + "feature": "Hundreds of themes", + "title": { + "en": "Themes with live preview", + "fr": "Thèmes avec aperçu en direct", + "es": "Temas con vista previa en vivo", + "de": "Themes mit Live-Vorschau", + "pt-BR": "Temas com pré-visualização ao vivo", + "ja": "ライブプレビュー付きのテーマ", + "zh-CN": "实时预览的主题" + }, + "setup": [ + [ + "key", + "escape" + ], + [ + "click", + 1600, + 700 + ], + [ + "key", + "ctrl+c" + ], + [ + "key", + "cmd+shift+p" + ], + [ + "wait", + 0.6 + ], + [ + "type", + "themes" + ], + [ + "wait", + 0.6 + ], + [ + "key", + "return" + ], + [ + "wait", + 0.8 + ], + [ + "type", + "default" + ], + [ + "wait", + 0.8 + ], + [ + "key", + "return" + ], + [ + "wait", + 0.8 + ], + [ + "click", + 1600, + 700 + ], + [ + "type", + "clear; cd /System/Library; ls -G" + ], + [ + "key", + "return" + ], + [ + "wait", + 1.5 + ] + ], + "segments": [ + { + "say": { + "en": "Sheprd lets you change its whole look in seconds.", + "fr": "Sheprd change entièrement d'apparence en quelques secondes.", + "es": "Sheprd cambia todo su aspecto en segundos.", + "de": "Sheprd ändert sein ganzes Aussehen in Sekunden.", + "pt-BR": "O Sheprd muda todo o visual em segundos.", + "ja": "Sheprd の見た目は、数秒でまるごと変えられます。", + "zh-CN": "几秒钟就能改变 Sheprd 的整体外观。" + }, + "actions": [] + }, + { + "say": { + "en": "Open the command palette with Command Shift P, and search for themes.", + "fr": "Ouvrez la palette de commandes avec Commande Majuscule P, puis cherchez « thèmes ».", + "es": "Abre la paleta de comandos con Comando Mayúsculas P y busca «temas».", + "de": "Öffnen Sie die Befehlspalette mit Befehl Umschalt P und suchen Sie nach Themes.", + "pt-BR": "Abra a paleta de comandos com Command Shift P e procure por temas.", + "ja": "Command Shift P でコマンドパレットを開き、テーマを検索します。", + "zh-CN": "按 Command Shift P 打开命令面板,搜索“主题”。" + }, + "actions": [ + [ + "wait", + 0.8 + ], + [ + "key", + "cmd+shift+p" + ], + [ + "wait", + 0.7 + ], + [ + "slowtype", + "themes", + 0.05 + ], + [ + "wait", + 0.5 + ], + [ + "key", + "return" + ] + ] + }, + { + "say": { + "en": "Move through the list: every theme previews live, across the whole window.", + "fr": "Parcourez la liste : chaque thème s'applique en direct à toute la fenêtre.", + "es": "Recorre la lista: cada tema se previsualiza en vivo en toda la ventana.", + "de": "Gehen Sie die Liste durch: Jedes Theme erscheint sofort im ganzen Fenster.", + "pt-BR": "Percorra a lista: cada tema aparece ao vivo na janela inteira.", + "ja": "リストを移動すると、各テーマがウィンドウ全体にすぐ反映されます。", + "zh-CN": "在列表中移动,每个主题都会实时应用到整个窗口。" + }, + "actions": [ + [ + "wait", + 0.2 + ], + [ + "key", + "up" + ], + [ + "wait", + 0.25 + ], + [ + "key", + "up" + ], + [ + "wait", + 0.25 + ], + [ + "key", + "up" + ], + [ + "wait", + 1.3 + ], + [ + "key", + "up" + ], + [ + "wait", + 0.2 + ], + [ + "key", + "up" + ], + [ + "wait", + 0.2 + ], + [ + "key", + "up" + ], + [ + "wait", + 0.8 + ] + ] + }, + { + "say": { + "en": "Type to filter, then press Return to keep the one you like.", + "fr": "Tapez pour filtrer, puis appuyez sur Entrée pour garder celui qui vous plaît.", + "es": "Escribe para filtrar y pulsa Intro para quedarte con el que te guste.", + "de": "Tippen Sie zum Filtern und drücken Sie Return, um Ihr Lieblings-Theme zu behalten.", + "pt-BR": "Digite para filtrar e pressione Return para ficar com o que você gostou.", + "ja": "入力して絞り込み、Return キーで気に入ったテーマを保存します。", + "zh-CN": "输入文字进行筛选,按回车键保留你喜欢的主题。" + }, + "actions": [ + [ + "wait", + 0.4 + ], + [ + "slowtype", + "github l", + 0.02 + ], + [ + "wait", + 0.9 + ], + [ + "key", + "return" + ] + ] + }, + { + "say": { + "en": "It's saved, and you can change it again anytime.", + "fr": "C'est enregistré, et vous pouvez en changer à tout moment.", + "es": "Queda guardado, y puedes cambiarlo cuando quieras.", + "de": "Es ist gespeichert, und Sie können es jederzeit wieder ändern.", + "pt-BR": "Fica salvo, e você pode mudar quando quiser.", + "ja": "設定は保存され、いつでも変更できます。", + "zh-CN": "设置会被保存,你随时都可以再次更改。" + }, + "actions": [] + } + ], + "teardown": [ + [ + "key", + "escape" + ], + [ + "key", + "cmd+shift+p" + ], + [ + "wait", + 0.6 + ], + [ + "type", + "themes" + ], + [ + "wait", + 0.6 + ], + [ + "key", + "return" + ], + [ + "wait", + 0.8 + ], + [ + "type", + "default" + ], + [ + "wait", + 0.8 + ], + [ + "key", + "return" + ], + [ + "wait", + 0.8 + ] + ] +} diff --git a/scripts/screencast/screencast.py b/scripts/screencast/screencast.py new file mode 100644 index 0000000000..c9278680cf --- /dev/null +++ b/scripts/screencast/screencast.py @@ -0,0 +1,400 @@ +#!/usr/bin/env python3 +"""Record a narrated, captioned screencast of one Sheprd feature in a virtual Mac. + + screencast.py FEATURE.json [--machine NAME] [--out DIR] [--langs en,fr,...] + [--window classic,moonframe] + [--tts openai,elevenlabs,say] [--captions] [--skip-record] + +1. Speaks every segment in every language with each voice provider (`tts.py`: + OpenAI, ElevenLabs, or macOS `say`) and measures it, so each segment lasts + as long as its longest take. +2. Drives Sheprd inside the machine through `sheprd machine` while the guest + records its own screen with `screencapture -v`, logging when each segment + starts. +3. Pulls the recording back and renders one MP4 per voice and language: the cropped, + scaled screen, a title, and the voice, plus an SRT for YouTube; --captions + also burns the narration in. + +Recording happens once; languages differ only in voice and captions. +""" + +import argparse +import base64 +import json +import os +import shutil +import subprocess +import sys +import time +from pathlib import Path + +# The `sheprd` command of the running app that shows the machine: $SHEPRD, +# else the one on PATH, else the installed app's. +SHEPRD = ( + os.environ.get("SHEPRD") + or shutil.which("sheprd") + or "/Applications/Sheprd.app/Contents/MacOS/sheprd" +) + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import tts # noqa: E402 + +# Narration exists for every language in tts.LANGUAGE_NAMES; videos are made +# in these until each other language has a native voice picked. +LANGS = ["en", "fr"] + +LATIN_FONT = "/System/Library/Fonts/SFNS.ttf" +CJK_FONT = "/System/Library/Fonts/Hiragino Sans GB.ttc" + +WIDTH, HEIGHT = 1920, 1080 +LEAD_IN = 1.0 # seconds of screen before the first segment +# screencapture can take seconds to start recording, so wait this long before +# the first segment and trim what it caught before LEAD_IN. +WARMUP = 12.0 +GAP = 0.5 # silence after each segment's voice +TAIL = 1.5 # seconds after the last segment +CHUNK = 45000 # bytes per pulled chunk; base64 of it stays under the exec output cap +APP = "~/Apps/Sheprd.app" # where the machine keeps the build being recorded + +# Each window the app can open, as the arguments that open it and the share of +# the guest screen's height, from the top, the maximized window fills (the +# rest is desktop). A video is recorded once per window asked for, so people +# can pick the one they use. Rune is to come. +WINDOWS = { + "classic": (["--classic"], 1.0), + "moonframe": ([], 1.0), +} + + +def run(*args, **kw): + return subprocess.run(args, check=True, text=True, capture_output=True, **kw).stdout + + +def machine(name, *args): + return run(SHEPRD, "machine", *args[:1], name, *args[1:]) + + +# --- voice ----------------------------------------------------------------- + + +def duration(path): + return float( + run("ffprobe", "-v", "error", "-show_entries", "format=duration", + "-of", "csv=p=0", str(path)).strip() + ) + + +def slug(provider): + return provider.replace(":", "-") + + +def voice_file(work, provider, lang, i): + return work / "voice" / slug(provider) / lang / f"{i}.{tts.extension(provider)}" + + +def speak(spec, providers, langs, work, cache): + """Voice every segment with every provider; return each segment's longest take.""" + longest = [0.0] * len(spec["segments"]) + for provider in providers: + for lang in langs: + for i, seg in enumerate(spec["segments"]): + path = voice_file(work, provider, lang, i) + path.parent.mkdir(parents=True, exist_ok=True) + tts.synthesize(provider, seg["say"][lang], lang, path, cache) + longest[i] = max(longest[i], duration(path)) + return longest + + +# --- recording ------------------------------------------------------------- + + +def act(name, action): + kind, *args = action + if kind == "wait": + time.sleep(args[0]) + elif kind == "key": + machine(name, "key", args[0]) + elif kind == "type": + machine(name, "type", args[0]) + elif kind == "slowtype": + for ch in args[0]: + machine(name, "type", ch) + time.sleep(args[1]) + elif kind == "click": + machine(name, "click", str(args[0]), str(args[1])) + elif kind == "repeat": + for _ in range(args[0]): + for inner in args[1]: + act(name, inner) + else: + sys.exit(f"unknown action {kind}") + + +def launch(name, window, work): + """Quit Sheprd in the machine and open it in `window`, keeping a screenshot + of how it came up in work/preflight.png.""" + # Activate it first: Command-Q goes to whichever app is in front. + machine(name, "exec", "--", "sh", "-c", f"open {APP}") + time.sleep(1) + machine(name, "key", "cmd+q") + for _ in range(20): + time.sleep(0.5) + alive = machine(name, "exec", "--", "sh", "-c", "pgrep -x sheprd || true").strip() + if not alive: + break + else: + sys.exit("Sheprd did not quit in the machine") + args = " ".join(WINDOWS[window][0]) + machine(name, "exec", "--", "sh", "-c", + f"open {APP}" + (f" --args {args}" if args else "")) + for _ in range(40): + time.sleep(0.5) + if machine(name, "exec", "--", "sh", "-c", "pgrep -x sheprd || true").strip(): + break + else: + sys.exit("Sheprd did not start in the machine") + time.sleep(8) + # Bring it to the front before any click: one that lands on the desktop + # while Sheprd is still drawing its window raises Finder instead, and the + # setup then types into Finder. + machine(name, "exec", "--", "sh", "-c", f"open {APP}") + time.sleep(1) + # Window > Fill (Globe-Control-F): unlike a title bar double-click, it + # fills the screen whatever the window's size was, never toggling back. + machine(name, "key", "ctrl+fn+f") + time.sleep(1.5) + work.mkdir(parents=True, exist_ok=True) + machine(name, "screenshot", str(work / "preflight.png")) + + +def record(spec, name, slots, work): + """Run the feature in the machine while it records; return segment start times.""" + machine(name, "exec", "--", "sh", "-c", + "nohup caffeinate -du -t 900 >/dev/null 2>&1 &") + # screencapture writes a frame only when the screen changes, and its + # movie ends at the last one. A ticking menu bar clock keeps frames coming + # every second, so the movie ends when it is stopped, which the segment + # times are measured back from. + machine(name, "exec", "--", "sh", "-c", + "defaults write com.apple.menuextra.clock ShowSeconds -bool true; " + "killall ControlCenter; sleep 2") + for a in spec.get("setup", []): + act(name, a) + + movie = f"/tmp/screencast-{spec['id']}-{int(time.time())}.mov" + recorder = machine(name, "exec", "--", "sh", "-c", + f"nohup screencapture -v -x {movie} >/tmp/screencast.log 2>&1 & " + "echo $!").strip() + if not recorder.isdigit(): + sys.exit(f"screencapture did not start in the machine: {recorder}") + t0 = time.monotonic() + + def stop(): + # SIGINT makes screencapture finish the movie; only this run's recorder. + machine(name, "exec", "--", "sh", "-c", f"kill -INT {recorder}; sleep 2") + + try: + time.sleep(WARMUP) + starts = [] + for seg, slot in zip(spec["segments"], slots): + begin = time.monotonic() + starts.append(begin - t0) + for a in seg["actions"]: + act(name, a) + left = slot - (time.monotonic() - begin) + if left > 0: + time.sleep(left) + time.sleep(TAIL) + stopped = time.monotonic() - t0 + except BaseException: + # A failed action or Control-C: stop the recorder and put the app back + # as best we can, then report the original failure. + for cleanup in [stop] + [lambda a=a: act(name, a) for a in spec.get("teardown", [])]: + try: + cleanup() + except (subprocess.CalledProcessError, OSError) as error: + print(f"cleanup step failed: {error}", file=sys.stderr) + raise + stop() + for a in spec.get("teardown", []): + act(name, a) + + raw = work / "screen.mov" + pull(name, movie, raw) + # The movie ends when it was stopped; place segment starts on its clock. + offset = duration(raw) - stopped + starts = [s + offset for s in starts] + (work / "timing.json").write_text(json.dumps({"starts": starts, "slots": slots})) + return starts + + +def pull(name, remote, local): + size = int(machine(name, "exec", "--", "stat", "-f", "%z", remote).strip()) + with open(local, "wb") as f: + for i in range((size + CHUNK - 1) // CHUNK): + out = machine(name, "exec", "--", "sh", "-c", + f"dd if={remote} bs={CHUNK} skip={i} count=1 2>/dev/null | base64") + f.write(base64.b64decode(out)) + if local.stat().st_size != size: + sys.exit(f"pulled {local.stat().st_size} of {size} bytes") + + +# --- rendering ------------------------------------------------------------- + + +def font(lang): + return CJK_FONT if lang in ("ja", "zh-CN") else LATIN_FONT + + +def caption(text, lang, path, size, width): + run("magick", "-background", "none", "-fill", "white", "-font", font(lang), + "-pointsize", str(size), "-size", f"{width}x", "-gravity", "center", + f"caption:{text}", "-bordercolor", "none", "-border", "28x16", + "(", "+clone", "-background", "#000000c0", "-alpha", "background", + "-channel", "A", "-evaluate", "set", "78%", "+channel", ")", + "+swap", "-composite", str(path)) + + +def title_card(text, lang, path): + run("magick", "-background", "#000000b0", "-fill", "white", "-font", font(lang), + "-pointsize", "64", f"label:{text}", "-bordercolor", "#000000b0", + "-border", "40x24", str(path)) + + +def srt_time(t): + ms = int(round(t * 1000)) + return f"{ms // 3600000:02}:{ms // 60000 % 60:02}:{ms // 1000 % 60:02},{ms % 1000:03}" + + +def render(spec, provider, lang, starts, work, window, out, captions=False, crop=None): + """Render one language and voice of the recording in work/WINDOW.""" + screen = work / window / "screen.mov" + crop = crop or WINDOWS[window][1] + # Keep LEAD_IN of screen before the first segment; the recorder's warm-up + # before that is cut. + head = max(0.0, starts[0] - LEAD_IN) + starts = [start - head for start in starts] + d = work / window / "render" / slug(provider) / lang + d.mkdir(parents=True, exist_ok=True) + title_card(spec["title"][lang], lang, d / "title.png") + + inputs = ["-i", str(screen), "-loop", "1", "-i", str(d / "title.png")] + filters = [ + # Keep the top `crop` of the guest screen (the window, not the desktop below). + # screencapture writes a frame only when the screen changes: make the + # rate constant before cutting the warm-up, and hold the last frame. + f"[0:v]fps=30,trim=start={head:.3f},setpts=PTS-STARTPTS," + f"tpad=stop_mode=clone:stop_duration=5,crop=iw:ih*{crop}:0:0,scale={WIDTH}:{HEIGHT}:force_original_aspect_ratio=decrease," + f"pad={WIDTH}:{HEIGHT}:(ow-iw)/2:(oh-ih)/2:color=0x101014[v0]", + f"[v0][1:v]overlay=(W-w)/2:150:shortest=1:enable='lt(t,{starts[1]:.3f})'[v1]", + ] + srt, audio_labels = [], [] + last = "v1" + burned = 0 + for i, seg in enumerate(spec["segments"]): + length = duration(voice_file(work, provider, lang, i)) + start, end = starts[i], starts[i] + length + GAP + srt.append(f"{i + 1}\n{srt_time(start)} --> {srt_time(end)}\n{seg['say'][lang]}\n") + if not captions: + continue + cap = d / f"cap{i}.png" + caption(seg["say"][lang], lang, cap, 46, WIDTH - 360) + inputs += ["-loop", "1", "-i", str(cap)] + n = 2 + burned + burned += 1 + filters.append( + f"[{last}][{n}:v]overlay=(W-w)/2:H-h-70:shortest=1:" + f"enable='between(t,{start:.3f},{end:.3f})'[v{n}]" + ) + last = f"v{n}" + base = 2 + burned + for i in range(len(spec["segments"])): + inputs += ["-i", str(voice_file(work, provider, lang, i))] + ms = int(starts[i] * 1000) + filters.append(f"[{base + i}:a]adelay={ms}|{ms},aresample=48000[a{i}]") + audio_labels.append(f"[a{i}]") + filters.append( + f"{''.join(audio_labels)}amix=inputs={len(audio_labels)}:normalize=0," + f"loudnorm=I=-16:TP=-1.5,apad[aout]" + ) + + out.mkdir(parents=True, exist_ok=True) + # Captioned cuts (Twitter/X autoplays muted) sit beside the plain ones. + suffix = ".captioned" if captions else "" + mp4 = out / window / slug(provider) / f"{spec['id']}.{lang}{suffix}.mp4" + mp4.parent.mkdir(parents=True, exist_ok=True) + run("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", *inputs, + "-filter_complex", ";".join(filters), "-map", f"[{last}]", "-map", "[aout]", + "-c:v", "libx264", "-preset", "slow", "-crf", "20", "-pix_fmt", "yuv420p", + "-c:a", "aac", "-b:a", "160k", "-movflags", "+faststart", + "-t", f"{duration(screen) - head:.3f}", str(mp4)) + (mp4.parent / f"{spec['id']}.{lang}.srt").write_text("\n".join(srt)) + return mp4 + + +def fits(recorded, wanted, window): + """Exit unless narration of `wanted` slot lengths fits a recording made for + `recorded` ones: each segment must have as many and no longer slots, or a + sentence would run over the next or past the movie's end.""" + if len(recorded) != len(wanted): + sys.exit(f"{window}: recorded for {len(recorded)} segments, the feature has " + f"{len(wanted)}; record again (drop --skip-record)") + for i, (old, new) in enumerate(zip(recorded, wanted)): + if new > old + 0.05: + sys.exit(f"{window}: segment {i + 1} now needs {new:.1f}s but was recorded " + f"with {old:.1f}s; record again (drop --skip-record)") + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("feature", type=Path) + p.add_argument("--machine", default="agent-test") + p.add_argument("--out", type=Path, default=Path("target/screencasts")) + p.add_argument("--langs", default=",".join(LANGS)) + p.add_argument("--window", default=",".join(WINDOWS), + help=f"comma-separated windows to record: {', '.join(WINDOWS)}") + p.add_argument("--tts", default="elevenlabs:river", + help=f"comma-separated voices to render: {', '.join(tts.PROVIDERS)}") + p.add_argument("--crop", type=float, + help="fraction of the guest screen's height to keep, from the top " + "(default: the window's own)") + p.add_argument("--captions", action="store_true", + help="burn the narration in as captions (the .srt is always written)") + p.add_argument("--skip-record", action="store_true", + help="re-render from the last recording") + a = p.parse_args() + + spec = json.loads(a.feature.read_text()) + langs = a.langs.split(",") + work = a.out / "work" / spec["id"] + work.mkdir(parents=True, exist_ok=True) + + providers = a.tts.split(",") + missing = [p for p in providers if not tts.available(p)] + if missing: + sys.exit(f"no API key for {', '.join(missing)} (OPENAI_API_KEY, ELEVENLABS_API_KEY)") + longest = speak(spec, providers, langs, work, a.out / "tts-cache") + slots = [d + GAP for d in longest] + windows = a.window.split(",") + unknown = [w for w in windows if w not in WINDOWS] + if unknown: + sys.exit(f"unknown window {', '.join(unknown)}: {', '.join(WINDOWS)}") + for window in windows: + if a.skip_record: + saved = json.loads((work / window / "timing.json").read_text()) + fits(saved["slots"], slots, window) + starts = saved["starts"] + else: + launch(a.machine, window, work / window) + starts = record(spec, a.machine, slots, work / window) + print(window, "segments start at", ", ".join(f"{s:.1f}s" for s in starts)) + for provider in providers: + for lang in langs: + print(render(spec, provider, lang, starts, work, window, a.out, + a.captions, a.crop)) + + +if __name__ == "__main__": + if not shutil.which("ffmpeg") or not shutil.which("magick"): + sys.exit("needs ffmpeg and ImageMagick") + main() diff --git a/scripts/screencast/tts.py b/scripts/screencast/tts.py new file mode 100644 index 0000000000..88b8692d70 --- /dev/null +++ b/scripts/screencast/tts.py @@ -0,0 +1,138 @@ +"""Text to speech for screencasts: macOS `say`, OpenAI, or ElevenLabs. + +Each provider writes one audio file per line of narration. Cloud results are +cached by provider, voice, and text, so re-rendering a feature costs nothing +until its narration changes. Keys come from the environment: +OPENAI_API_KEY, ELEVENLABS_API_KEY (and optionally OPENAI_TTS_VOICE, +ELEVENLABS_VOICE_ID). +""" + +import hashlib +import json +import os +import subprocess +import urllib.request +from pathlib import Path + +LANGUAGE_NAMES = { + "en": "English", + "fr": "French", + "es": "Spanish", + "de": "German", + "pt-BR": "Brazilian Portuguese", + "ja": "Japanese", + "zh-CN": "Mandarin Chinese", +} + +SAY_VOICES = { + "en": "Samantha", + "fr": "Thomas", + "es": "Mónica", + "de": "Anna", + "pt-BR": "Luciana", + "ja": "Kyoko", + "zh-CN": "Tingting", +} + +OPENAI_MODEL = "gpt-4o-mini-tts" +ELEVENLABS_MODEL = os.environ.get("ELEVENLABS_MODEL", "eleven_v4") +# Voices picked in the voice tryouts (README.md, "Voices"). River and Eric are +# premade voices every account has; the others come from the voice library. +ELEVENLABS_VOICES = { + "damien": "kSNoLVC4Ox0vkBz1IKux", # Damien Doré, deep narrator, fr-FR + "eric": "cjVigY5qzO86Huf0OWal", + "julien": "VuE88ydpXAhBTNxFI7WF", # Julien, friendly tech explainer, fr-FR + "river": "SAz9YHcvj6GT2YYXdXww", +} +ELEVENLABS_DEFAULT_VOICE = ELEVENLABS_VOICES["river"] +# A native voice for a language beats the voice named on the command line: the +# English voices speak French with a Canadian accent. +ELEVENLABS_NATIVE = { + "fr": "julien", # fallback: "damien" +} +# The language_code ElevenLabs takes (ISO 639-1). +ELEVENLABS_LANGUAGE = {"pt-BR": "pt", "zh-CN": "zh"} + +PROVIDERS = ("say", "openai", "elevenlabs", "elevenlabs:VOICE") + + +def _post(url, headers, body): + req = urllib.request.Request(url, data=json.dumps(body).encode(), headers=headers) + with urllib.request.urlopen(req, timeout=120) as resp: + return resp.read() + + +def _openai(text, lang): + key = os.environ["OPENAI_API_KEY"] + voice = os.environ.get("OPENAI_TTS_VOICE", "coral") + body = { + "model": OPENAI_MODEL, + "voice": voice, + "input": text, + "response_format": "mp3", + "instructions": ( + f"Speak {LANGUAGE_NAMES[lang]} natively, as a friendly, confident " + "narrator of a short product demo. Clear, warm, unhurried." + ), + } + headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"} + return voice, _post("https://api.openai.com/v1/audio/speech", headers, body) + + +def _elevenlabs_voice(provider, lang): + native = os.environ.get(f"ELEVENLABS_VOICE_{lang.upper().replace('-', '_')}", + ELEVENLABS_NATIVE.get(lang)) + if native: + return ELEVENLABS_VOICES.get(native, native) + _, _, name = provider.partition(":") + if name: + return ELEVENLABS_VOICES.get(name, name) + return os.environ.get("ELEVENLABS_VOICE_ID", ELEVENLABS_DEFAULT_VOICE) + + +def _elevenlabs(text, lang, voice): + key = os.environ["ELEVENLABS_API_KEY"] + body = { + "text": text, + "model_id": ELEVENLABS_MODEL, + "language_code": ELEVENLABS_LANGUAGE.get(lang, lang), + } + headers = {"xi-api-key": key, "Content-Type": "application/json", + "Accept": "audio/mpeg"} + url = (f"https://api.elevenlabs.io/v1/text-to-speech/{voice}" + "?output_format=mp3_44100_128") + return _post(url, headers, body) + + +def available(provider): + if provider.startswith("elevenlabs"): + return bool(os.environ.get("ELEVENLABS_API_KEY")) + return {"say": True, "openai": bool(os.environ.get("OPENAI_API_KEY"))}[provider] + + +def synthesize(provider, text, lang, path, cache): + """Write `text` spoken in `lang` to `path` (an .aiff for say, else .mp3).""" + if provider == "say": + subprocess.run(["say", "-v", SAY_VOICES[lang], "-o", str(path), text], + check=True) + return + if provider == "openai": + voice = os.environ.get("OPENAI_TTS_VOICE", "coral") + model = OPENAI_MODEL + else: + voice = _elevenlabs_voice(provider, lang) + model = ELEVENLABS_MODEL + key = f"{model}\0{voice}\0{lang}\0{text}" + cached = Path(cache) / f"{hashlib.sha256(key.encode()).hexdigest()[:32]}.mp3" + if not cached.exists(): + cached.parent.mkdir(parents=True, exist_ok=True) + if provider == "openai": + _, audio = _openai(text, lang) + else: + audio = _elevenlabs(text, lang, voice) + cached.write_bytes(audio) + path.write_bytes(cached.read_bytes()) + + +def extension(provider): + return "aiff" if provider == "say" else "mp3"