commit 02d340e32abfcaff4e19cbb40821957dd54af0ca
parent 9ad6c5fec4c37ab9fcb80671ce64a257e9cef460
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 11 Nov 2026 18:56:48 -0500
Merge main (5b9035bd) into lane/remote-archive
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
91 files changed, 5809 insertions(+), 292 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -103,7 +103,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi
| `archilyzer docs cli` | `[--check]` | write COMMANDS.md from this command table and `pnpm ops --help` |
| `archilyzer settings example` | `[--check]` | write settings.json.example + SETTINGS.md from the schema |
| `archilyzer tts setup` | `[--engine kokoro\|orpheus\|espeak-ng] [--from <dir>] [--python <py>] [--check]` | install a text-to-speech engine under settings.tts.home/<engine> (default ~/.local/share/archilyzer/tts/<engine>): a python venv with its pinned packages (uv venv --python 3.12 when uv is on PATH, else --python <py> -m venv) — kokoro-onnx for kokoro, onnxruntime and numpy for orpheus — and its model files, downloaded once (kokoro: the kokoro-onnx model-files-v1.0 release; orpheus: the Q8\_0 GGUF and the SNAC decoder from Hugging Face, 3.5 GB) one stream at a time with no retries, verified by size and sha256; --from <dir> takes already-downloaded model files from <dir> instead (hard links where it can, else copies; verified the same way); orpheus's llama-server is not installed here (settings.tts.orpheus.serverBin) but is checked; --check installs nothing, lists what is missing and exits 1 when anything is |
-| `archilyzer voice setup` | `--engine deepfilternet\|openvoice\|seed-vc\|rnnoise [--from <dir>] [--python <py>] [--home <dir>] [--dry-run] [--check]` | install a voice engine under settings.voice.home/<engine> (default ~/.local/share/archilyzer/voice/<engine>), saying first what it fetches and how big: deepfilternet is DeepFilterNet's static binary (v0.5.6, 36 MB, its GitHub release); openvoice and seed-vc are a python 3.12 venv (uv venv when uv is on PATH, else --python <py> -m venv) with torch 2.4.0's CPU wheels and their pinned packages, the engine's code at a pinned commit (git fetch --depth 1), and its weights from Hugging Face (openvoice: the v2 converter, 131 MB; seed-vc: the DiT, whisper-small, BigVGAN v2 and CAM++, 1.9 GB) — one download at a time with no retries, each verified by size and sha256; rnnoise needs nothing (ffmpeg's arnndn and the model in the repo) and setup says whether ffmpeg has it; --from <dir> takes already-downloaded files from <dir>/<name> (hard links where it can); --home installs elsewhere (then point settings.voice.home at it); --dry-run says what it would fetch and stops; --check installs nothing, lists what is missing and exits 1 when anything is |
+| `archilyzer voice setup` | `--engine deepfilternet\|openvoice\|seed-vc\|rnnoise [--with f0] [--from <dir>] [--python <py>] [--home <dir>] [--dry-run] [--check]` | install a voice engine under settings.voice.home/<engine> (default ~/.local/share/archilyzer/voice/<engine>), saying first what it fetches and how big: deepfilternet is DeepFilterNet's static binary (v0.5.6, 36 MB, its GitHub release); openvoice and seed-vc are a python 3.12 venv (uv venv when uv is on PATH, else --python <py> -m venv) with torch 2.4.0's CPU wheels and their pinned packages, the engine's code at a pinned commit (git fetch --depth 1), and its weights from Hugging Face (openvoice: the v2 converter, 131 MB; seed-vc: the DiT, whisper-small, BigVGAN v2 and CAM++, 1.9 GB; --with f0 adds seed-vc's OPTIONAL f0-conditioned 44.1 kHz model, its BigVGAN and the RMVPE pitch tracker, 1.49 GB — what voice-convert's pitch source and contour run on, and an install without it still converts at the target's pitch) — one download at a time with no retries, each verified by size and sha256; rnnoise needs nothing (ffmpeg's arnndn and the model in the repo) and setup says whether ffmpeg has it; --from <dir> takes already-downloaded files from <dir>/<name> (hard links where it can); --home installs elsewhere (then point settings.voice.home at it); --dry-run says what it would fetch and stops; --check installs nothing, lists what is missing and exits 1 when anything is (an optional group is said, and counted only with --with) |
| `archilyzer service install` | `[--mode docker\|host] [--apps <a,b>] [--sites <id>:<port>,…] [--overlays <name,…>\|none] [--bind <host>] [--editor-port <n>] [--umtool-port <n>] [--editor-memory <N>G] [--umtool-memory <N>G] [--idle-boot] [--no-housekeeping] [--linger] [--no-start] [--force] [--dry-run]` | install the apps as systemd USER units and start them: docker mode (the default when `docker compose` answers) is ONE unit, archilyzer.service, running `docker compose up` in the foreground with a profile per --apps (editor, umtool, site, homepage, ollama; default editor) and the overlays given or found (anthropic when the key file exists, storage when docker-compose.storage.yml does); host mode is archilyzer-editor.service and archilyzer-umtool.service (node running `next start` from the app dir, -H --bind default 0.0.0.0, ports 3001/3050, MemoryHigh/Max sized from MemTotal) plus archilyzer-site-<id>.service per --sites (a built bundle on 127.0.0.1) and archilyzer-housekeeping.timer, weekly and Persistent, starting the oneshot archilyzer-housekeeping.service (`archilyzer housekeeping --by timer`; a run the heavy slot turns away exits 75 and is retried hourly for a day; --no-housekeeping leaves the pair out); each unit refuses to start while its build or image is missing. A unit already installed under the same name is ADOPTED when identical and shown as a diff and refused when not (--force replaces it; a running unit is not restarted); --no-start enables without starting; --linger runs loginctl enable-linger (start at boot with nobody logged in); --dry-run prints the units and commands and writes nothing. Linux and systemd only |
| `archilyzer service status` | | read-only: each installed archilyzer unit's state, enablement and pid; for an app its build id, its port and what / answers; the transcription lane's held state; in docker mode each container; for archilyzer-housekeeping.timer its next and last trigger and the last recorded run |
| `archilyzer service logs` | `[--apps <a,b>] [--lines <n>] [--follow]` | the units' journal (journalctl --user), the last 200 lines by default |
@@ -185,7 +185,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. "whilePaused": true runs it during a pause-all on a worker the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` |
| `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags <laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn> <gasp> are performed by orpheus and stripped for the others; any other <...> is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` |
| `voice-enhance` | voice-enhance cleans a speech recording up (denoise, soften the room, level it) as a job on the `voice` queue, behind the heavy slot: {"file": "/abs/take.wav", "out": "/abs/clean.wav"} (never inside the corpus; 48 kHz mono, exactly as long as the input), "engine" (deepfilternet \| rnnoise; settings.voice), "params" (the engine's knobs: lufs, highpass, attenLimDb, postFilter, mix), "parts" (\[{file, out}\], a take recorded part by part). deepfilternet needs `archilyzer voice setup --engine deepfilternet`; rnnoise needs nothing. The result is {op, engine, wav, seconds, samples, sampleRate, engineMs, durationMs, waitedMs, gainDb, params, parts?, synthetic}; with --wait it is printed on stdout. | |
-| `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "<tts engine>:<stock voice>" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). The target's reference is synthesized once through the tts op and kept. The result adds target, voice, synthetic: true and the disclosure line. | |
+| `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "<tts engine>:<stock voice>" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). "pitch" is where the result's pitch comes from (settings.voice.convert.pitch): "target" — the stock voice's own, the read's intonation flattened to it; "source" — the pitch the take was read at (raise your voice and it rises); "contour" — the read's rises and falls, moved as a whole to the stock voice's register. "semitones" (-12 to 12) then moves a followed pitch; left out, a followed pitch takes settings.voice.convert.semitones (0 unless set). source and contour are seed-vc's, on its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them. The target's reference is synthesized once through the tts op and kept. The result adds target, voice, pitch (semitones and f0 — the medians heard and the move applied — when followed), synthetic: true and the disclosure line. | |
| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'`<br>`pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` |
| `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | |
| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /settings) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` |
@@ -226,6 +226,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `find-clips` | find-clips runs the clip finder's chain for ONE video as one job: {"slug", "id", "target"? (the cut's seconds), "segment"? (one umtool found, "s2"), "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}. Persist the source video, the corpus transcript, word timings (data/<id>/words.json), the chat replay (YouTube), diarization — each step skipped when its output exists, named in the log — then umtool's clip finder (POST UMTOOL\_URL/api/report/clips {mode: "new"}), followed to the end. "whilePaused": true runs this one video past the holds: the two transcriptions during a pause-all on a worker the pause alone switched off, and its diarization in the job when the backfill lane is held. "dryRun": true answers each step's plan and starts nothing. With --wait the result — {project, url, created, segments: \[{id, from, to, why}\], steps} — is printed on stdout. | `pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait` |
| `fetch-chat-backlog` | fetch-chat-backlog fetches a channel's stream chats after its downloads: {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose metadata says it was a stream (live\_status was\_live / post\_live) and whose chat is not here, newest first, one at a time through fetch-chat's pass with the batch downloads' gap between two, as one fetch-chat-backlog job on the platform's download queue; a raw replay already here is only normalized. It stops on a rate limit, a held platform, three failures in a row, a drain or "limit" chats; a re-run skips the chats here and the streams known to have none (chat-backlog.json), and a restart resumes it. The download lane queues it by itself (25 a run) for a channel whose "chat" is "later" once it has nothing left to download. "dryRun": true counts from the disk and starts nothing: chats, normalizeOnly, have, settled, notStreams, ids (the first 50). | `pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}'` |
| `x-run` | x-run fetches several X posts channels IN SEQUENCE as ONE job on X's queue: {"channels": \[slug, ...\]} in that order, each a fetch-posts sync new of at most 200 posts ("limit": N, 1-200, caps it lower), X's queue gap (pacing.jobGapSeconds.twitter) between two channels. Before EACH channel the jar is checked again: once it is past social.x.maxCookieAgeMinutes (or the X alert is up) the run stops and the rest are DEFERRED until the next refresh. It never refreshes the jar: Refresh cookies on /settings, then {"resume": "<run id>"} runs the deferred channels (the console's Resume; a Retry of the job is the same). One run at a time; refused before a job on a stale jar (a new run's channels are kept, deferred). An interrupted run is not resumed on boot: it ends deferred. Answers {jobId, run}; get x-run follows it. The log ends with @@x-run {id, status, stopped?, counts, summary}. | `pnpm ops x-run --json '{"channels":["example-x","other-x"]}'`<br>`pnpm ops x-run --json '{"resume":"xr-01J…"}'` |
+| `lookout-run` | lookout-run lists what a saved lookout (settings.lookouts) would read: {"id", "dryRun": true, "days"?, "maxVideos"?, "until"?: "YYYY-MM-DD"}. Every video of its channels whose AIR date (release\_timestamp, else timestamp, in the lookout's timeZone — not the UTC upload\_date) falls in the window; a duplicate upload of one recording, and a stream's cut-down, folded into it (each named, with why and its score); the longest maxVideos recordings read and the rest listed as skipped for the cap; under minSeconds and no transcript yet listed too. A local media library channel or a slug this archive does not hold is named in "refused". Answers {plan: {window, counts, read, skipped, refused, estimate}}: readCalls is one per transcript chunk, priced once a run has been measured. Synchronous, reads text only, writes nothing; without "dryRun": true it is refused (the model run is not in this build). | `pnpm ops lookout-run --json '{"id":"example-week","dryRun":true}'`<br>`pnpm ops lookout-run --json '{"id":"example-week","dryRun":true,"days":3,"until":"2026-11-10"}'` |
### Usage, flags and environment
@@ -251,6 +252,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops get x-run [<run id>]
pnpm ops get cleanup <slug>
pnpm ops get speakers
+ pnpm ops get lookouts [<id>]
pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]
pnpm ops get transcript <videoId> [--slug <slug>]
pnpm ops get coverage <slug>
@@ -344,6 +346,11 @@ get speakers is the speakers readout the lane deck and /cleanup print
noFingerprintPossible (diarized, audio already gone), per channel with
corpus-disk channels first; and the lane: armed, held, the operations
it dispatches, its order, cleanAfterCapture and requireVoiceprints.
+get lookouts [<id>] is the saved lookouts (settings.lookouts, SETTINGS.md):
+ each one's channels, days, cap and zone, its runs (transcripts/.lookouts/
+ <id>/), the latest run (when, window, model, calls, seconds, ideas), how
+ many of that run's ideas have no verdict yet, and the verdicts given.
+ Reads settings and the store only, never a channel's videos.
get cleanup <slug> is one channel's /cleanup row: what each sweep would
reclaim (they overlap — never add them), what holds the rest, and the
failed-transcriptions count. measured: false means unknown, not zero.
diff --git a/OPERATING.md b/OPERATING.md
@@ -916,21 +916,41 @@ pnpm ops get generation-usage
pnpm archilyzer voice setup --engine deepfilternet --dry-run # what it fetches, how big; then without --dry-run
pnpm archilyzer voice setup --engine openvoice
pnpm archilyzer voice setup --engine seed-vc --check
+pnpm archilyzer voice setup --engine seed-vc --with f0 # the optional f0 model (1.49 GB): a conversion that follows your pitch
pnpm ops voice-enhance --json '{"file":"/abs/take.wav","out":"/abs/take.clean.wav"}' --wait
pnpm ops voice-convert --json '{"file":"/abs/take.wav","out":"/abs/take.zac.wav","voice":"orpheus:zac"}' --wait
umtool posts narrate <project> <item> --derive 1 --op enhance
umtool posts narrate <project> <item> --derive 2 --op convert --voice zac --engine seed-vc
+pnpm ops voice-convert --json '{"file":"/abs/take.wav","out":"/abs/take.bella.wav","voice":"kokoro:af_bella","engine":"seed-vc","pitch":"source","semitones":2}' --wait
+umtool posts narrate <project> <item> --derive 2 --op convert --voice kokoro:af_bella --engine seed-vc --pitch contour
+umtool cast set <character> --convert-engine seed-vc --convert-pitch contour --convert-semitones 2
```
- Two editor ops over a speech recording, each a job on the `voice` queue, one at a time, its engine run behind the
heavy slot with the engine's declared estimate (`settings.voice.heavyEstimateMB`): **enhance** (denoise, soften the
- room, level by one static gain) and **convert** (the timing and pitch contour kept, the timbre swapped for a STOCK
- synthetic voice). The result is a 48 kHz mono WAV exactly as long as the input; `out` is never inside the corpus.
+ room, level by one static gain) and **convert** (the timing kept, the timbre swapped for a STOCK
+ synthetic voice; the pitch as `pitch` says, below). The result is a 48 kHz mono WAV exactly as long as the input; `out` is never inside the corpus.
umtool's derived takes are the usual caller: a new take from take n, the original kept, a parted take part by part.
- **A convert target is a stock voice of our own TTS engines** — `orpheus:zac`, `orpheus:leah`, `kokoro:am_michael`,
or a bare name one engine has (`zac`). A file, a path or a recording is refused, whatever it holds: these engines
clone from seconds of audio, so no real person's voice is ever a target. Its reference (the voice reading "The North
Wind and the Sun") is asked of the `tts` op the first time and kept under `settings.voice.home/targets/`.
+- **The pitch a conversion lands on** is `pitch` (default `settings.voice.convert.pitch`, `target`):
+ - `target`: the stock voice's own pitch. The converter is given none of yours, so a read with a median of 128 Hz and
+ one of 237 Hz both come out near 197 Hz, and the range narrows — voice acting is flattened.
+ - `source`: the pitch you read at. Raise your voice for a character and the result is raised the same.
+ - `contour`: your rises and falls, moved as a whole so their median sits on the stock voice's. Read in your ordinary
+ voice and the character speaks in its own register with your intonation.
+ - `semitones` (-12 to 12) moves a followed pitch (`source`, `contour`); with `target` it is refused.
+ - `source` and `contour` are seed-vc's, on its f0-conditioned 44.1 kHz model: optional files, fetched by `voice setup
+ --engine seed-vc --with f0`. openvoice refuses them; without the files the op refuses, naming that command. An
+ install without them still converts at the target's pitch. It takes about 1.7 times as long as seed-vc's plain run (measured: 170 s against 103 s for a 7 s read on a busy machine) and
+ declares its own estimate (`settings.voice.heavyEstimateMB["seed-vc-f0"]`, 6500 MB: a take of 20 s or more peaks near 5.8 GB).
+ - The result says what was done: `pitch`, `semitones`, and `f0` — the median pitch heard in the target's reference
+ and in your take, and the whole move applied, in semitones.
+ - In umtool a character keeps its pitch in the cast (`umtool cast set <id> --convert-pitch …`), so every recording
+ made that character's lands the same way; `--pitch` / `--semitones` on `posts narrate … --recording` or `--derive`
+ are for one read.
- Engines (`settings.voice`): enhance `deepfilternet` (DeepFilterNet 3, the default) or `rnnoise` (ffmpeg's arnndn,
nothing to install); convert `openvoice` (OpenVoice v2's converter, the default) or `seed-vc` (Seed-VC v1, closer
to the target, several times slower). All on the CPU. `voice setup` says what it fetches first; `--check` lists
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -59,6 +59,7 @@ A copied example PINS every default it spells — including each lane's `autoQue
| [`clips`](#clips) | object — see below |
| [`jobs`](#jobs) | object — see below |
| [`serviceCookies`](#servicecookies) | object — see below |
+| [`lookouts`](#lookouts) | object — see below |
## `adminTitle`
@@ -1079,8 +1080,8 @@ The voice ops (release 39): a speech recording ENHANCED (denoised, de-reverbed,
| `home` | `""` | Where `archilyzer voice setup` installs the voice engines, one directory per engine (`<home>/deepfilternet`: its binary; `<home>/openvoice`, `<home>/seed-vc`: a python venv, a pinned checkout and the weights), and where the stock targets' reference clips are kept (`<home>/targets/`). Blank = `~/.local/share/archilyzer/voice`. Absolute, or `~/`-relative. |
| `threads` | `4` | CPU threads a torch engine (openvoice, seed-vc) may use. 1–16. |
| `enhance` | object — see below | The enhance op's default engine. See VoiceEnhanceSettings (`voice.enhance` below). |
-| `convert` | object — see below | The convert op's default engine and target. See VoiceConvertSettings (`voice.convert` below). |
-| `heavyEstimateMB` | object — see below | Per engine id: the memory (MB) its job is admitted to the machine's heavy slot with (`queue-lock --heavy --estimate`) — it runs only when that much is free above the floor. The defaults are the 2026-11-03 bake-off's measured peaks plus a margin. An engine left out takes its default; 0 declares nothing (the job then runs ALONE in the slot). |
+| `convert` | object — see below | The convert op's default engine, target and pitch. See VoiceConvertSettings (`voice.convert` below). |
+| `heavyEstimateMB` | object — see below | Per engine id: the memory (MB) its job is admitted to the machine's heavy slot with (`queue-lock --heavy --estimate`) — it runs only when that much is free above the floor. The defaults are the 2026-11-03 bake-off's measured peaks plus a margin; `seed-vc-f0` is seed-vc's run when it follows the input's pitch (`pitch: source \| contour` — another, bigger model; measured 2026-11-11 over a take long enough to fill a 30 s window: 5.8 GB). An engine left out takes its default; 0 declares nothing (the job then runs ALONE in the slot). |
#### `voice.enhance`
@@ -1094,6 +1095,8 @@ The voice ops (release 39): a speech recording ENHANCED (denoised, de-reverbed,
|---|---|---|
| `engine` | `"openvoice"` | The engine `voice-convert` uses when the request names none: `openvoice` (OpenVoice v2's tone-colour converter, MIT, light) or `seed-vc` (Seed-VC v1, GPL-3.0, a closer timbre match, slower). Both run on the CPU; `archilyzer voice setup --engine <id>` installs one. An unknown id falls back to the default. |
| `target` | `"orpheus:zac"` | The stock synthetic voice a conversion lands on when the request names none: `<tts engine>:<stock voice>` (`orpheus:zac`, `orpheus:leah`, `kokoro:am_michael`, …). Never a file or a recording — no real person's voice is a target. Its reference clip is synthesized once through the `tts` op and kept under `home`. Anything else falls back to `orpheus:zac`. |
+| `pitch` | `"target"` | The pitch a conversion lands on when the request names none — for an engine that can follow the input's (seed-vc, with its optional f0 model: `archilyzer voice setup --engine seed-vc --with f0`; openvoice always lands on the target's). `target`: the stock voice's own pitch — the read's intonation is flattened to it (what there was before). `source`: the pitch the take was read at — raise your voice and the result rises. `contour`: the read's rises and falls, moved as a whole so their median sits on the stock voice's. Anything else falls back to `target`. |
+| `semitones` | `0` | Semitones a FOLLOWED pitch (`source`, `contour`) is moved by when the request names none: -12 to 12, 0 = as followed. Ignored for `target`. It applies to a request that names its own `pitch` too: `{"pitch": "source"}` with no `semitones` is moved by this many — send `"semitones": 0` for none. |
Default:
@@ -1106,13 +1109,16 @@ Default:
},
"convert": {
"engine": "openvoice",
- "target": "orpheus:zac"
+ "target": "orpheus:zac",
+ "pitch": "target",
+ "semitones": 0
},
"heavyEstimateMB": {
"deepfilternet": 400,
"rnnoise": 300,
"openvoice": 2000,
- "seed-vc": 3500
+ "seed-vc": 3500,
+ "seed-vc-f0": 6500
}
}
```
@@ -1392,3 +1398,41 @@ Default:
]
}
```
+
+## `lookouts`
+
+Saved lookouts (lane/lookout): each names channels, a number of days back and an optional prompt, and a run reads those channels' recent transcripts — by air date, duplicate uploads and stream cut-downs folded in — and answers with video ideas. OFF and empty by default; nothing a lookout writes is published. `pnpm ops get lookouts` is the readout, `pnpm ops lookout-run --json '{"id":"…","dryRun":true}'` lists what one would read. See LookoutsSettings and common/lib/lookoutSettings.ts.
+
+#### `lookouts`
+
+| Key | Default | Description |
+|---|---|---|
+| `enabled` | `false` | The lookouts' master switch. Off: no lookout runs, by hand or after a sync; a dry run (`pnpm ops lookout-run --json '{"id":"…","dryRun":true}'`) still lists what a lookout would read, and writes nothing. Default false. |
+| `afterSync` | `false` | Run each lookout after a sync of one of its channels finishes — at most once a day per lookout, never while render mode holds the machine. Not acted on before the after-sync slice lands. Default false. |
+| `items` | `[]` | The saved lookouts, one entry each (`lookouts.items[]` below). The list is replaced whole by a settings patch. Default [] — no lookout. |
+
+#### `lookouts.items[]`
+
+Per entry — each entry spells its own values.
+
+| Key | Description |
+|---|---|
+| `id` | The lookout's id: a lowercase slug (`a-z`, `0-9`, `-`, at most 64), the name its runs and verdicts are kept under (`transcripts/.lookouts/<id>/`). Omitted: made from `label`. An entry with neither is dropped, and so is a second entry with an id already used. |
+| `label` | What the lookout is called on its page. Omitted: the id. |
+| `channels` | The channel slugs it reads (`transcripts/channels/<slug>/`). A local media library channel, or a slug this archive does not hold (a channel only on a remote site), is refused by name when the lookout runs. |
+| `days` | How many days back it reads, today included, by AIR date in `timeZone` (`release_timestamp`, else `timestamp`, from the video's metadata — not yt-dlp's UTC `upload_date`). Clamped to [1, 60]; default 7. |
+| `prompt` | What the operator wants from the ideas, added to the grouping step only — the per-video reading is the same for every lookout. At most 4000 characters; default "". |
+| `maxVideos` | The most recordings one run reads, after duplicate uploads and stream cut-downs are folded in: the longest first, and every one left out listed as skipped for the cap. Clamped to [1, 500]; default 40. |
+| `minSeconds` | Videos shorter than this are not read (and are counted as skipped). Clamped to [0, 3600]; default 90. |
+| `timeZone` | The IANA time zone its days are counted in ("America/New_York"). "" = the machine's. An unknown zone is dropped to "". Default "". |
+| `siteOrigin` | The public site its links are built on ("https://example.pages.dev"), when the channels are published; "" = each video's source URL with its start second. Default "". |
+
+Default:
+
+```json
+{
+ "enabled": false,
+ "afterSync": false,
+ "items": []
+}
+```
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -1131,11 +1131,12 @@ export const COMMANDS: Command[] = [
{
path: ["voice", "setup"],
usage:
- "--engine deepfilternet|openvoice|seed-vc|rnnoise [--from <dir>] [--python <py>] [--home <dir>] [--dry-run] [--check] install a voice engine under settings.voice.home/<engine> (default ~/.local/share/archilyzer/voice/<engine>), saying first what it fetches and how big: deepfilternet is DeepFilterNet's static binary (v0.5.6, 36 MB, its GitHub release); openvoice and seed-vc are a python 3.12 venv (uv venv when uv is on PATH, else --python <py> -m venv) with torch 2.4.0's CPU wheels and their pinned packages, the engine's code at a pinned commit (git fetch --depth 1), and its weights from Hugging Face (openvoice: the v2 converter, 131 MB; seed-vc: the DiT, whisper-small, BigVGAN v2 and CAM++, 1.9 GB) — one download at a time with no retries, each verified by size and sha256; rnnoise needs nothing (ffmpeg's arnndn and the model in the repo) and setup says whether ffmpeg has it; --from <dir> takes already-downloaded files from <dir>/<name> (hard links where it can); --home installs elsewhere (then point settings.voice.home at it); --dry-run says what it would fetch and stops; --check installs nothing, lists what is missing and exits 1 when anything is",
- flags: { engine: "string", from: "string", python: "string", home: "string", "dry-run": "boolean", check: "boolean" },
+ "--engine deepfilternet|openvoice|seed-vc|rnnoise [--with f0] [--from <dir>] [--python <py>] [--home <dir>] [--dry-run] [--check] install a voice engine under settings.voice.home/<engine> (default ~/.local/share/archilyzer/voice/<engine>), saying first what it fetches and how big: deepfilternet is DeepFilterNet's static binary (v0.5.6, 36 MB, its GitHub release); openvoice and seed-vc are a python 3.12 venv (uv venv when uv is on PATH, else --python <py> -m venv) with torch 2.4.0's CPU wheels and their pinned packages, the engine's code at a pinned commit (git fetch --depth 1), and its weights from Hugging Face (openvoice: the v2 converter, 131 MB; seed-vc: the DiT, whisper-small, BigVGAN v2 and CAM++, 1.9 GB; --with f0 adds seed-vc's OPTIONAL f0-conditioned 44.1 kHz model, its BigVGAN and the RMVPE pitch tracker, 1.49 GB — what voice-convert's pitch source and contour run on, and an install without it still converts at the target's pitch) — one download at a time with no retries, each verified by size and sha256; rnnoise needs nothing (ffmpeg's arnndn and the model in the repo) and setup says whether ffmpeg has it; --from <dir> takes already-downloaded files from <dir>/<name> (hard links where it can); --home installs elsewhere (then point settings.voice.home at it); --dry-run says what it would fetch and stops; --check installs nothing, lists what is missing and exits 1 when anything is (an optional group is said, and counted only with --with)",
+ flags: { engine: "string", with: "string", from: "string", python: "string", home: "string", "dry-run": "boolean", check: "boolean" },
run: async ({ flags }) =>
(await import("./voice-setup")).main({
...(typeof flags.engine === "string" ? { engine: flags.engine } : {}),
+ ...(typeof flags.with === "string" ? { with: flags.with.split(",").map((x) => x.trim()).filter(Boolean) } : {}),
...(typeof flags.from === "string" ? { from: flags.from } : {}),
...(typeof flags.python === "string" ? { python: flags.python } : {}),
...(typeof flags.home === "string" ? { home: flags.home } : {}),
diff --git a/common/bin/voice-setup.test.ts b/common/bin/voice-setup.test.ts
@@ -1,10 +1,11 @@
import { test, after } from "node:test";
import assert from "node:assert/strict";
-import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
+import { mkdtemp, mkdir, open, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { main, voiceSetupPlan } from "./voice-setup";
-import { VOICE_ENGINES } from "../lib/voiceApps";
+import { SEEDVC_F0_FILES, SEEDVC_FILES, VOICE_ENGINES } from "../lib/voiceApps";
+import { VOICE_CODE_MARKER, voiceGroupState, voiceInstallState } from "../lib/voiceInstall";
// Run with:
// pnpm --filter yt-dlp-transcript-common exec tsx --test bin/voice-setup.test.ts
@@ -32,7 +33,16 @@ test("the plan names every file, its size and its source, and the total", () =>
assert.ok(plan.some((l) => /a python 3\.12 venv \(uv\), with: torch==2\.4\.0\+cpu/.test(l)));
assert.ok(plan.some((l) => /the code: https:\/\/github\.com\/Plachtaa\/seed-vc at 51383efd/.test(l)));
assert.ok(plan.some((l) => /whisper-small\/model\.safetensors — 967\.0 MB from https:\/\/huggingface\.co\/openai\/whisper-small\/resolve\/973afd24/.test(l)));
- assert.match(plan.at(-1)!, /files: 1\.88 GB/);
+ // The optional f0 group is listed after the total, not fetched or counted…
+ const total = plan.findIndex((l) => /^ {2}files: /.test(l));
+ assert.match(plan[total], /files: 1\.88 GB/);
+ assert.match(plan[total + 1], /optional, not fetched without `--with f0` — the f0-conditioned 44\.1 kHz model/);
+ assert.ok(plan.slice(total).some((l) => /rmvpe\.pt — 181\.2 MB from https:\/\/huggingface\.co\/lj1995\/VoiceConversionWebUI\/resolve\/e6d0c1a1/.test(l)));
+ assert.match(plan.at(-1)!, /1\.49 GB more/);
+ // …and with --with f0 it is part of what is fetched.
+ const withF0 = voiceSetupPlan(VOICE_ENGINES["seed-vc"], ["f0"]);
+ assert.ok(withF0.some((l) => /bigvgan-44k\/bigvgan_generator\.pt — 489\.0 MB from https:\/\/huggingface\.co\/nvidia\/bigvgan_v2_44khz_128band_512x\/resolve\/95a9d1dc/.test(l)));
+ assert.match(withF0.at(-1)!, /files: 3\.38 GB/);
assert.match(voiceSetupPlan(VOICE_ENGINES.deepfilternet).at(-1)!, /files: 36\.4 MB$/);
assert.match(voiceSetupPlan(VOICE_ENGINES.rnnoise)[0], /nothing to download/);
});
@@ -55,6 +65,58 @@ test("--check over an empty home lists what is missing and exits 1", async () =>
assert.match(c.lines.join("\n"), /DeepFilterNet 3 at .*empty\/deepfilternet — missing:\n {2}- deep-filter\nRun `archilyzer voice setup --engine deepfilternet`/);
});
+async function sparse(dir: string, files: readonly { name: string; bytes: number }[]) {
+ for (const f of files) {
+ const p = path.join(dir, f.name);
+ await mkdir(path.dirname(p), { recursive: true });
+ const fh = await open(p, "w");
+ await fh.truncate(f.bytes);
+ await fh.close();
+ }
+}
+
+test("seed-vc's f0 files are optional: an install without them checks out, --with f0 counts them", async () => {
+ const home = path.join(ROOT, "seed-home");
+ const dir = path.join(home, "seed-vc");
+ const seed = VOICE_ENGINES["seed-vc"];
+ assert.ok(seed.setup.kind === "python-venv");
+ if (seed.setup.kind !== "python-venv") return;
+ await mkdir(path.join(dir, "venv", "bin"), { recursive: true });
+ await writeFile(path.join(dir, "venv", "bin", "python"), "");
+ await mkdir(path.join(dir, "code"), { recursive: true });
+ await writeFile(path.join(dir, "code", VOICE_CODE_MARKER), `${seed.setup.code.commit}\n`);
+ await sparse(dir, SEEDVC_FILES);
+ // The install made before the group existed is installed; the group is said.
+ const state = voiceInstallState(seed, { home, voiceModelsDir: ROOT });
+ assert.equal(state.installed, true);
+ assert.deepEqual(state.optional.map((g) => [g.id, g.installed, g.missing.length]), [["f0", false, SEEDVC_F0_FILES.length]]);
+ // --check (the venv here is a stub, so the import fails: read the lines about the group).
+ const plain = capture();
+ await main({ engine: "seed-vc", check: true, home, log: plain.log });
+ assert.ok(plain.lines.some((l) => /optional f0 \(.*follows the input's pitch.*\): not installed — `archilyzer voice setup --engine seed-vc --with f0` fetches it/.test(l)), plain.lines.join("\n"));
+ assert.equal(plain.lines.some((l) => /- rmvpe\.pt/.test(l)), false);
+ const asked = capture();
+ assert.equal(await main({ engine: "seed-vc", check: true, with: ["f0"], home, log: asked.log }), 1);
+ assert.ok(asked.lines.some((l) => /^ {2}- rmvpe\.pt$/.test(l)));
+ assert.match(asked.lines.at(-1)!, /Run `archilyzer voice setup --engine seed-vc --with f0`/);
+ // There: said as installed.
+ await sparse(dir, SEEDVC_F0_FILES);
+ assert.equal(voiceGroupState(seed, "f0", { home })!.installed, true);
+ const there = capture();
+ await main({ engine: "seed-vc", check: true, with: ["f0"], home, log: there.log });
+ assert.ok(there.lines.some((l) => /with f0 \(.*\): installed/.test(l)));
+ assert.equal(there.lines.some((l) => /rmvpe/.test(l)), false);
+ // A group the engine does not have.
+ const no = capture();
+ assert.equal(await main({ engine: "seed-vc", with: ["f1"], dryRun: true, home, log: no.log }), 2);
+ assert.match(no.lines[0], /seed-vc has no optional group "f1" — --with is one of f0/);
+ assert.equal(await main({ engine: "openvoice", with: ["f0"], dryRun: true, home, log: no.log }), 2);
+ // --dry-run --with f0 lists them as fetched.
+ const dry = capture();
+ assert.equal(await main({ engine: "seed-vc", with: ["f0"], dryRun: true, home, log: dry.log }), 0);
+ assert.ok(dry.lines.some((l) => /with f0 — the f0-conditioned/.test(l)));
+});
+
test("an engine is required, by its id", async () => {
const c = capture();
assert.equal(await main({ log: c.log }), 2);
diff --git a/common/bin/voice-setup.ts b/common/bin/voice-setup.ts
@@ -15,6 +15,11 @@
// code/ Plachtaa/seed-vc at a pinned commit
// … the DiT (440 MB), whisper-small (967
// MB), BigVGAN v2 (449 MB), CAM++ (28 MB)
+// … (--with f0) OPTIONAL: the f0-conditioned 44.1 kHz
+// DiT (821 MB), its BigVGAN (489 MB) and
+// RMVPE (181 MB) — what `pitch: source |
+// contour` runs on; an install without
+// them converts at the target's pitch
// install.json what was installed, and when
// rnnoise has nothing to install (ffmpeg, and the model in the repo): setup
// says whether ffmpeg has `arnndn`.
@@ -31,7 +36,9 @@
//
// `--check` installs nothing: it lists what is missing (the venv, the package
// importing, the checkout at its commit, each file at its size) and exits 1
-// when anything is.
+// when anything is. An optional group that is not there is SAID (with the
+// command that fetches it) and does not fail the check, unless it was asked
+// for (`--check --with f0`).
//
// Scratch (pip's build dirs) goes to `<install dir>/.tmp`, never the OS temp
// dir: it may be a small RAM tmpfs.
@@ -48,6 +55,7 @@ import {
voiceInstallDir,
voiceVenvPython,
type VoiceEngine,
+ type VoiceFileGroup,
} from "../lib/voiceApps";
import { VOICE_CODE_MARKER, voiceInstallState } from "../lib/voiceInstall";
import { DEFAULT_VOICE_SETTINGS, resolveVoiceHome } from "../lib/voiceSettings";
@@ -58,6 +66,8 @@ import { adoptModelFile, downloadModelFile, verifyModelFile } from "./tts-setup"
export type VoiceSetupOptions = {
engine?: string;
from?: string;
+ // Optional file groups to install too (seed-vc: "f0").
+ with?: string[];
python?: string;
check?: boolean;
dryRun?: boolean;
@@ -76,8 +86,22 @@ function mb(n: number): string {
return n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)} MB` : `${(n / 1000).toFixed(1)} kB`;
}
-/** What setup fetches for an engine, in words: one line each, then the total. */
-export function voiceSetupPlan(engine: VoiceEngine): string[] {
+/** The engine's optional groups by these ids, or the ids it does not have. */
+export function pickVoiceGroups(engine: VoiceEngine, ids: readonly string[]): { groups: VoiceFileGroup[]; unknown: string[]; known: string[] } {
+ const all = engine.setup.kind === "python-venv" ? engine.setup.optional ?? [] : [];
+ return {
+ groups: all.filter((g) => ids.includes(g.id)),
+ unknown: ids.filter((id) => !all.some((g) => g.id === id)),
+ known: all.map((g) => g.id),
+ };
+}
+
+/**
+ * What setup fetches for an engine, in words: one line each, then the total.
+ * The optional groups asked for (`withGroups`) are fetched and counted; the
+ * others are listed after, as what `--with <id>` would add.
+ */
+export function voiceSetupPlan(engine: VoiceEngine, withGroups: readonly string[] = []): string[] {
const s = engine.setup;
if (s.kind === "bundled") return [`${engine.label}: nothing to download (${s.hint})`];
const lines: string[] = [];
@@ -90,7 +114,20 @@ export function voiceSetupPlan(engine: VoiceEngine): string[] {
lines.push(` ${f.name} — ${mb(f.bytes)} from ${f.url}`);
total += f.bytes;
}
+ const optional = s.kind === "python-venv" ? s.optional ?? [] : [];
+ for (const g of optional.filter((x) => withGroups.includes(x.id))) {
+ lines.push(` with ${g.id} — ${g.label}:`);
+ for (const f of g.files) {
+ lines.push(` ${f.name} — ${mb(f.bytes)} from ${f.url}`);
+ total += f.bytes;
+ }
+ }
lines.push(` files: ${mb(total)}${s.kind === "python-venv" ? " (plus the packages: torch's CPU wheels are ~200 MB)" : ""}`);
+ for (const g of optional.filter((x) => !withGroups.includes(x.id))) {
+ lines.push(` optional, not fetched without \`--with ${g.id}\` — ${g.label}:`);
+ for (const f of g.files) lines.push(` ${f.name} — ${mb(f.bytes)} from ${f.url}`);
+ lines.push(` ${mb(g.files.reduce((n, f) => n + f.bytes, 0))} more`);
+ }
return lines;
}
@@ -138,24 +175,43 @@ export async function main(opts: VoiceSetupOptions = {}): Promise<number> {
}
const dir = voiceInstallDir(home, engine);
+ const picked = pickVoiceGroups(engine, opts.with ?? []);
+ if (picked.unknown.length) {
+ log(`voice setup: ${engine.id} has no optional group "${picked.unknown.join('", "')}" — ${picked.known.length ? `--with is one of ${picked.known.join(", ")}` : "it has none"}`);
+ return 2;
+ }
+ const withIds = picked.groups.map((g) => g.id);
if (opts.check) {
const state = voiceInstallState(engine, { home, voiceModelsDir: paths.voiceModelsDir });
const missing = [...state.missing];
if (setup.kind === "python-venv" && !missing.some((m) => m.startsWith("the python venv"))) {
if ((await importsAt(voiceVenvPython(dir), setup.importName)) === null) missing.push(`${setup.importName} does not import in the venv`);
}
+ // A group asked for is part of the check; one not asked for is only said.
+ for (const g of state.optional) if (withIds.includes(g.id)) missing.push(...g.missing);
+ const said = () => {
+ for (const g of state.optional) {
+ if (g.installed) log(` with ${g.id} (${g.label}): installed`);
+ else if (!withIds.includes(g.id)) {
+ log(` optional ${g.id} (${g.label}): not installed — \`archilyzer voice setup --engine ${engine.id} --with ${g.id}\` fetches it`);
+ }
+ }
+ };
+ const withArg = withIds.map((id) => ` --with ${id}`).join("");
if (missing.length === 0) {
log(`${engine.label}: installed at ${dir}`);
+ said();
return 0;
}
log(`${engine.label} at ${dir} — missing:`);
for (const m of missing) log(` - ${m}`);
- log(`Run \`archilyzer voice setup --engine ${engine.id}\` to install it.`);
+ said();
+ log(`Run \`archilyzer voice setup --engine ${engine.id}${withArg}\` to install it.`);
return 1;
}
log(`${opts.dryRun ? "Would install" : "Installing"} ${engine.label} (${engine.license}) at ${dir}:`);
- for (const l of voiceSetupPlan(engine)) log(l);
+ for (const l of voiceSetupPlan(engine, withIds)) log(l);
if (opts.dryRun) return 0;
const scratch = path.join(dir, ".tmp");
@@ -215,7 +271,7 @@ export async function main(opts: VoiceSetupOptions = {}): Promise<number> {
}
}
// 4. The files, one at a time.
- for (const spec of setup.files) {
+ for (const spec of [...setup.files, ...picked.groups.flatMap((g) => g.files)]) {
const target = path.join(dir, spec.name);
await mkdir(path.dirname(target), { recursive: true });
if ((await verifyModelFile(target, spec)) === "ok") {
@@ -238,10 +294,14 @@ export async function main(opts: VoiceSetupOptions = {}): Promise<number> {
return 1;
}
const state = voiceInstallState(engine, { home, voiceModelsDir: paths.voiceModelsDir });
- if (!state.installed) {
- log(`voice setup: still missing ${state.missing.join("; ")}`);
+ const stillMissing = [...state.missing, ...state.optional.filter((g) => withIds.includes(g.id)).flatMap((g) => g.missing)];
+ if (stillMissing.length) {
+ log(`voice setup: still missing ${stillMissing.join("; ")}`);
return 1;
}
+ // What is there now, whichever run fetched it.
+ const groupsThere = picked.known.filter((id) => state.optional.find((g) => g.id === id)?.installed);
+ const optionalGroups = pickVoiceGroups(engine, groupsThere).groups;
await writeJsonAtomic(
path.join(dir, "install.json"),
{
@@ -250,10 +310,13 @@ export async function main(opts: VoiceSetupOptions = {}): Promise<number> {
license: engine.license,
...(setup.kind === "python-venv" ? { packages: setup.packages, code: setup.code } : {}),
files: setup.files.map((f) => ({ name: f.name, bytes: f.bytes, sha256: f.sha256, url: f.url })),
+ ...(optionalGroups.length
+ ? { optional: optionalGroups.map((g) => ({ id: g.id, files: g.files.map((f) => ({ name: f.name, bytes: f.bytes, sha256: f.sha256, url: f.url })) })) }
+ : {}),
installedAt: new Date().toISOString(),
},
{ indent: 2 },
);
- log(`${engine.label} installed: ${dir}`);
+ log(`${engine.label} installed: ${dir}${optionalGroups.length ? ` (with ${optionalGroups.map((g) => g.id).join(", ")})` : ""}`);
return 0;
}
diff --git a/common/controller/lookoutPlan.test.ts b/common/controller/lookoutPlan.test.ts
@@ -0,0 +1,375 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, rm, writeFile, readdir } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { sanitizeLookoutItem } from "../lib/lookoutSettings";
+import { metaDatesOf, planLookout, LookoutPlanRefusal } from "./lookoutPlan";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/lookoutPlan.test.ts
+//
+// The dry run over a fixture corpus (lane/lookout slice 1, acceptance a): a
+// stream whose UTC upload date is the next day, its twin upload on another
+// channel and a cut-down of it → the plan lists the stream ONCE, on the local
+// date, with both alternates. Every channel name here is invented.
+
+// The real start of an evening stream: 2026-11-04T01:20:53Z, which is
+// 2026-11-03 20:20 in New York — `upload_date` says 4 Nov, the air says 3 Nov.
+const STREAM_RELEASE = 1793755253;
+const STREAM_UPLOAD = 1793754765;
+
+// Deterministic words: a small LCG over a synthetic vocabulary, so the texts
+// have real shingles and two "transcripts" of the same speech differ the way
+// two ASR engines do (a word in ten replaced).
+function words(seed: number, n: number): string[] {
+ let x = seed >>> 0;
+ const out: string[] = [];
+ for (let i = 0; i < n; i++) {
+ x = (Math.imul(x, 1664525) + 1013904223) >>> 0;
+ out.push(`w${(x >>> 16) % 2000}`);
+ }
+ return out;
+}
+function garble(ws: string[], seed: number, every = 10): string[] {
+ return ws.map((w, i) => (i % every === seed % every ? `x${i}` : w));
+}
+function cuesOf(ws: string[], seconds: number) {
+ const per = 10;
+ const n = Math.ceil(ws.length / per);
+ const step = seconds / n;
+ return Array.from({ length: n }, (_, i) => ({
+ start: Math.round(i * step * 100) / 100,
+ end: Math.round((i + 1) * step * 100) / 100,
+ text: ws.slice(i * per, (i + 1) * per).join(" "),
+ }));
+}
+
+type VideoFixture = {
+ channel: string;
+ dir: string;
+ id?: string;
+ title: string;
+ platform: string;
+ duration: number;
+ uploadDate: string;
+ timestamp?: number;
+ releaseTimestamp?: number;
+ liveStatus?: string;
+ text?: string[];
+};
+
+async function writeVideo(channelsDir: string, v: VideoFixture): Promise<void> {
+ const dir = path.join(channelsDir, v.channel, "data", v.dir);
+ await mkdir(dir, { recursive: true });
+ const meta: Record<string, unknown> = {
+ id: v.id ?? v.dir,
+ title: v.title,
+ formats: [{ format_id: "1", url: "https://example.invalid/f" }],
+ duration: v.duration,
+ live_status: v.liveStatus ?? "not_live",
+ webpage_url: `https://example.invalid/watch/${v.dir}`,
+ upload_date: v.uploadDate,
+ };
+ if (v.timestamp !== undefined) meta.timestamp = v.timestamp;
+ if (v.releaseTimestamp !== undefined) meta.release_timestamp = v.releaseTimestamp;
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(meta, null, 1));
+ if (v.text) {
+ await writeFile(
+ path.join(dir, "transcript.cues.json"),
+ JSON.stringify({
+ version: 2,
+ source: v.platform === "youtube" ? "vtt" : "whisper",
+ slug: `${v.channel}/${v.id ?? v.dir}`,
+ id: v.id ?? v.dir,
+ channelSlug: v.channel,
+ title: v.title,
+ uploadDate: v.uploadDate,
+ duration: v.duration,
+ channel: v.channel,
+ description: "",
+ platform: v.platform,
+ webpageUrl: `https://example.invalid/${v.dir}`,
+ cues: cuesOf(v.text, v.duration),
+ }),
+ );
+ }
+}
+
+async function fixture(): Promise<{ root: string; paths: Paths }> {
+ const root = await mkdtemp(path.join(os.tmpdir(), "lookout-plan-"));
+ const transcriptsDir = path.join(root, "transcripts");
+ const channelsDir = path.join(transcriptsDir, "channels");
+ const channel = async (slug: string, config: Record<string, unknown>) => {
+ await mkdir(path.join(channelsDir, slug, "data"), { recursive: true });
+ await writeFile(path.join(channelsDir, slug, "config.json"), JSON.stringify(config));
+ };
+ await channel("alpha-rumble", { name: "Alpha", handling: "transcribe", url: "https://rumble.com/c/alpha-invented" });
+ await channel("alpha-clips", { name: "Alpha Clips", handling: "youtube", url: "https://www.youtube.com/@alpha-invented" });
+ await channel("alpha-library", { name: "Library", handling: "transcribe", localMedia: { sourceId: "library-1", directory: "/mnt/recordings" } });
+
+ const stream = words(1, 6000);
+ // The stream on one channel, dated by its start.
+ await writeVideo(channelsDir, {
+ channel: "alpha-rumble",
+ dir: "v1stream",
+ id: "v0embed1",
+ title: "Election Night LIVE!",
+ platform: "rumble",
+ duration: 7200,
+ uploadDate: "20261104",
+ timestamp: STREAM_UPLOAD,
+ releaseTimestamp: STREAM_RELEASE,
+ liveStatus: "was_live",
+ text: stream,
+ });
+ // Its twin upload on another channel: the same title, a second longer,
+ // captions from another engine; uploaded the next morning.
+ await writeVideo(channelsDir, {
+ channel: "alpha-clips",
+ dir: "TwinUpload1",
+ title: "Election Night LIVE!",
+ platform: "youtube",
+ duration: 7201,
+ uploadDate: "20261104",
+ timestamp: 1793790000,
+ text: garble(stream, 3),
+ });
+ // A cut-down: twelve minutes of the stream, re-titled.
+ await writeVideo(channelsDir, {
+ channel: "alpha-clips",
+ dir: "CutDown0001",
+ title: "He SNAPPED On Air",
+ platform: "youtube",
+ duration: 720,
+ uploadDate: "20261104",
+ timestamp: 1793800000,
+ text: garble(stream.slice(2000, 2600), 7),
+ });
+ // An unrelated video in the window.
+ await writeVideo(channelsDir, {
+ channel: "alpha-clips",
+ dir: "Unrelated01",
+ title: "Something Else Entirely",
+ platform: "youtube",
+ duration: 600,
+ uploadDate: "20261105",
+ timestamp: 1793880000,
+ text: words(99, 1500),
+ });
+ // A short.
+ await writeVideo(channelsDir, {
+ channel: "alpha-clips",
+ dir: "ShortOne001",
+ title: "A Short #shorts",
+ platform: "youtube",
+ duration: 58,
+ uploadDate: "20261104",
+ timestamp: 1793810000,
+ text: words(7, 120),
+ });
+ // In the window, no transcript yet.
+ await writeVideo(channelsDir, {
+ channel: "alpha-clips",
+ dir: "NoCues00001",
+ title: "Not Transcribed",
+ platform: "youtube",
+ duration: 900,
+ uploadDate: "20261105",
+ timestamp: 1793870000,
+ });
+ // The UTC trap the other way: 2026-11-03T04:30Z is 2 Nov in New York —
+ // `upload_date` puts it inside a 3–5 Nov window, the air date does not.
+ await writeVideo(channelsDir, {
+ channel: "alpha-rumble",
+ dir: "v1latenight",
+ title: "Late Night",
+ platform: "rumble",
+ duration: 1200,
+ uploadDate: "20261103",
+ timestamp: 1793680200,
+ text: words(55, 2000),
+ });
+ // Long before the window.
+ await writeVideo(channelsDir, {
+ channel: "alpha-rumble",
+ dir: "v1old",
+ title: "Old",
+ platform: "rumble",
+ duration: 1200,
+ uploadDate: "20260101",
+ timestamp: 1767268800,
+ text: words(56, 2000),
+ });
+ return { root, paths: { transcriptsDir, channelsDir } as Paths };
+}
+
+function lookout(over: Record<string, unknown> = {}) {
+ const item = sanitizeLookoutItem({
+ id: "alpha-week",
+ channels: ["alpha-rumble", "alpha-clips"],
+ days: 3,
+ timeZone: "America/New_York",
+ ...over,
+ });
+ assert.ok(item);
+ return item;
+}
+
+test("the stream is listed once, on its local date, with its twin and its cut-down", async () => {
+ const { root, paths } = await fixture();
+ try {
+ const plan = await planLookout(paths, lookout(), { until: "2026-11-05" });
+ assert.deepEqual(plan.refused, []);
+ assert.deepEqual(plan.window, { from: "2026-11-03", to: "2026-11-05", days: 3, timeZone: "America/New_York" });
+ const keys = plan.read.map((r) => `${r.channel}/${r.video}`);
+ assert.deepEqual(keys, ["alpha-rumble/v1stream", "alpha-clips/Unrelated01"]);
+ const s = plan.read[0]!;
+ assert.equal(s.airDate, "2026-11-03", "the air date in New York, not the UTC upload date");
+ assert.equal(s.dateSource, "release_timestamp");
+ assert.equal(s.airAt, "2026-11-04T01:20:53.000Z");
+ assert.equal(s.id, "v0embed1", "the record's id beside its directory");
+ assert.deepEqual(
+ s.folded.map((f) => [`${f.channel}/${f.video}`, f.reason]),
+ [
+ ["alpha-clips/TwinUpload1", "duplicate-upload"],
+ ["alpha-clips/CutDown0001", "covered-by-stream"],
+ ],
+ );
+ assert.equal(s.folded[0]!.titleMatch, true);
+ assert.ok(s.folded[1]!.score >= 0.4, `cut-down share ${s.folded[1]!.score}`);
+ assert.equal(s.folded[0]!.airDate, "2026-11-04");
+ assert.equal(plan.counts.inWindow, 5, "stream, twin, cut-down, unrelated, short — not the late-night one");
+ assert.equal(plan.counts.noTranscript, 1);
+ assert.equal(plan.counts.underMinSeconds, 1);
+ assert.equal(plan.counts.qualified, 4);
+ assert.equal(plan.counts.duplicateUploads, 1);
+ assert.equal(plan.counts.coveredByStream, 1);
+ assert.equal(plan.counts.recordings, 2);
+ assert.equal(plan.counts.read, 2);
+ assert.equal(plan.counts.skippedForCap, 0);
+ assert.deepEqual(
+ plan.skipped.map((k) => [k.video, k.reason]),
+ [
+ ["ShortOne001", "under-min-seconds"],
+ ["NoCues00001", "no-transcript"],
+ ],
+ );
+ const bare = plan.skipped.find((k) => k.video === "NoCues00001")!;
+ assert.equal(bare.title, "Not Transcribed", "named from its metadata");
+ assert.equal(bare.url, "https://example.invalid/watch/NoCues00001");
+ assert.ok(!keys.includes("alpha-rumble/v1latenight"), "aired 2 Nov in New York");
+ assert.ok(s.chunks > 1, "a two-hour stream is several chunks");
+ assert.equal(plan.estimate.readCalls, plan.read.reduce((n, r) => n + r.chunks, 0));
+ assert.equal(plan.estimate.secondsPerCall, null, "no run measured yet");
+ // Nothing was written: the corpus holds exactly what the fixture put there.
+ assert.deepEqual((await readdir(paths.transcriptsDir)).sort(), ["channels"]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("in UTC the late-night video is in the window and the stream moves to 4 Nov", async () => {
+ const { root, paths } = await fixture();
+ try {
+ const plan = await planLookout(paths, lookout({ timeZone: "UTC" }), { until: "2026-11-05" });
+ const byKey = new Map(plan.read.map((r) => [`${r.channel}/${r.video}`, r]));
+ assert.equal(byKey.get("alpha-rumble/v1stream")?.airDate, "2026-11-04");
+ assert.equal(byKey.get("alpha-rumble/v1latenight")?.airDate, "2026-11-03");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("the cap reads the longest recordings and lists the rest with what folded into them", async () => {
+ const { root, paths } = await fixture();
+ try {
+ const plan = await planLookout(paths, lookout(), { until: "2026-11-05", maxVideos: 1 });
+ assert.deepEqual(plan.read.map((r) => r.video), ["v1stream"]);
+ assert.equal(plan.counts.skippedForCap, 1);
+ const cap = plan.skipped.find((k) => k.reason === "cap");
+ assert.equal(cap?.video, "Unrelated01");
+ assert.deepEqual(cap?.folded, []);
+ assert.ok((cap?.chunks ?? 0) >= 1);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a local library and a slug the archive does not hold are refused by name; the rest is read", async () => {
+ const { root, paths } = await fixture();
+ try {
+ const plan = await planLookout(
+ paths,
+ lookout({ channels: ["alpha-library", "remote-only-invented", "alpha-rumble"] }),
+ { until: "2026-11-05" },
+ );
+ assert.deepEqual(
+ plan.refused.map((r) => r.channel),
+ ["alpha-library", "remote-only-invented"],
+ );
+ assert.match(plan.refused[0]!.reason, /local media library/);
+ assert.match(plan.refused[1]!.reason, /remote site/);
+ assert.deepEqual(plan.read.map((r) => r.video), ["v1stream"]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a directory unchanged since before the window is listed, not opened", async () => {
+ const { root, paths } = await fixture();
+ try {
+ // Every fixture directory was made just now; a window years later starts
+ // after all of their ctimes, so none can hold a video aired in it.
+ const plan = await planLookout(paths, lookout(), { until: "2031-01-10" });
+ assert.equal(plan.counts.scanned, 8);
+ assert.equal(plan.counts.examined, 0);
+ assert.equal(plan.counts.inWindow, 0);
+ const now = await planLookout(paths, lookout(), { until: "2026-11-05" });
+ assert.equal(now.counts.examined, 8);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a lookout with no channels is refused", async () => {
+ const { root, paths } = await fixture();
+ try {
+ await assert.rejects(planLookout(paths, lookout({ channels: [] })), LookoutPlanRefusal);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("metaDatesOf reads the scalars wherever yt-dlp put them", () => {
+ // YouTube's order: upload_date then timestamp, near the end; a comment's
+ // nested timestamp earlier is not taken, nor a storyboard fragment's duration.
+ const yt =
+ '{"id": "a", "formats": [{"format_id": "sb0", "fragments": [{"url": "u", "duration": 496.98}, {"url": "u", "duration": 250.02}]}], ' +
+ '"comments": [{"timestamp": 1600000000}], "duration": 747, "live_status": "not_live", "webpage_url": "https://example.invalid/a", ' +
+ '"upload_date": "20261106", "timestamp": 1793993883, "is_live": false}';
+ assert.deepEqual(metaDatesOf(yt), {
+ releaseTimestamp: null,
+ timestamp: 1793993883,
+ uploadDate: "20261106",
+ liveStatus: "not_live",
+ duration: 747,
+ title: null,
+ webpageUrl: "https://example.invalid/a",
+ });
+ // Rumble's order: timestamp early, release_timestamp later, upload_date last.
+ const rumble =
+ '{"id": "v", "title": "She said \\"no\\" \\u2014 caf\u00c3\u00a9", "timestamp": 1793754765, "duration": 12970, "live_status": "was_live", ' +
+ '"release_timestamp": 1793755253, "upload_date": "20261104"}';
+ assert.deepEqual(metaDatesOf(rumble), {
+ releaseTimestamp: 1793755253,
+ timestamp: 1793754765,
+ uploadDate: "20261104",
+ liveStatus: "was_live",
+ duration: 12970,
+ // Escapes decoded, and the file's UTF-8 bytes (a string argument stands for them, one char a byte).
+ title: 'She said "no" — café',
+ webpageUrl: null,
+ });
+});
diff --git a/common/controller/lookoutPlan.ts b/common/controller/lookoutPlan.ts
@@ -0,0 +1,522 @@
+// WHAT A LOOKOUT WOULD READ — stages 1 and 2 of a lookout run, with no model
+// (lane/lookout slice 1). `pnpm ops lookout-run {"id", "dryRun": true}` answers
+// this; the run itself (slice 2) reads exactly the `read` list it returns.
+//
+// Stage 1, select: every video of the lookout's channels whose AIR date
+// (lib/lookout.ts airDateOf: `release_timestamp`, else `timestamp`, in the
+// lookout's zone) falls in the window. A video with no transcript yet is listed
+// and not read; one under `minSeconds` is listed and not read.
+// Stage 2, fold and cap: duplicate uploads and a stream's cut-downs are folded
+// into one recording (lib/lookout.ts foldRecordings); then the longest
+// `maxVideos` recordings are read and every other one is listed as skipped for
+// the cap — with what was folded into it.
+//
+// READS ONLY TEXT, WRITES NOTHING. Per channel: `data/` listed, each video's
+// transcript.cues.json HEAD (its UTC upload date and duration), and for the
+// few within two days of the window its metadata.info.json (the timestamps)
+// and its whole cues (the text the folding compares). Behind the text guard
+// (lib/channelMedia.ts): a channel whose text cannot be read is refused by
+// name, never read as empty. No network, no model.
+//
+// REFUSED BY NAME in v1: a local media library channel, and a slug this
+// archive does not hold (a channel only on a remote site).
+
+import { open as openFile, readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { assertChannelTextReadable } from "../lib/channelMedia";
+import { mapConcurrent } from "../lib/concurrency";
+import { comparisonText, shingles } from "../lib/duplicates";
+import { LOCAL_RECORDING_ID_RE } from "../lib/localMedia";
+import {
+ LOOKOUT_SHINGLE_SIZE,
+ addDays,
+ airDateOf,
+ foldRecordings,
+ inWindow,
+ isoOfUploadDate,
+ lookoutWindow,
+ type AirDate,
+ type DedupeVideo,
+ type LookoutPlan,
+ type LookoutPlanFolded,
+ type LookoutPlanRead,
+ type LookoutPlanSkipped,
+ type LookoutPlanVideo,
+ type LookoutWindow,
+} from "../lib/lookout";
+import type { LookoutItem } from "../lib/lookoutSettings";
+import { measuredSecondsPerCall } from "../lib/lookoutStore";
+import { CHUNK_CHARS, chunksOf } from "../lib/report/draft/tasks/sweep-pipeline";
+import type { Cue } from "../lib/vtt";
+import { CUES_JSON_FILENAME } from "../lib/videoStatus";
+import { readChannelConfig } from "./channels";
+import { heldVideoIds } from "./videoCues";
+
+export type LookoutPlanOptions = {
+ /** Override the lookout's `days` for this plan. */
+ days?: number;
+ /** Override the lookout's `maxVideos` for this plan. */
+ maxVideos?: number;
+ /** The window's last day (YYYY-MM-DD); default today in the lookout's zone. */
+ until?: string;
+ now?: Date;
+ /** Files read at once (default 32). */
+ concurrency?: number;
+};
+
+export class LookoutPlanRefusal extends Error {}
+
+const META_FILENAME = "metadata.info.json";
+const CUES_HEAD_BYTES = 16 * 1024;
+const META_TAIL_BYTES = 16 * 1024;
+// A video whose UTC upload date is this many days outside the window cannot
+// air inside it (the zone moves a date by one; a stream's start precedes its
+// upload by hours) and is not read further.
+const PREFILTER_SLACK_DAYS = 2;
+
+// THE DIRECTORY'S ctime, FIRST. A big channel holds thousands of video
+// directories and a lookout wants a week of them; opening every one's cues is
+// ~1 ms a file (23,516 directories: 28 s, measured 11 Nov), a stat is a
+// seventh of that. A video that aired in the window got its transcript after
+// it aired, and writing transcript.cues.json — created or renamed into place —
+// sets its directory's ctime, which no copy or `touch` can set back. So a
+// directory whose ctime is before the window (less the slack) cannot hold a
+// video that aired in it with a transcript, and is not opened. A bulk pass that
+// touches every directory only makes this slower, never wrong. A video with no
+// transcript yet is listed only if its directory changed in that time too.
+const CTIME_SLACK_MS = PREFILTER_SLACK_DAYS * 86_400_000 + 14 * 3_600_000;
+
+async function readHead(file: string, bytes: number): Promise<string | null> {
+ let fh;
+ try {
+ fh = await openFile(file, "r");
+ const buf = Buffer.allocUnsafe(bytes);
+ const { bytesRead } = await fh.read(buf, 0, bytes, 0);
+ return buf.toString("latin1", 0, bytesRead);
+ } catch {
+ return null;
+ } finally {
+ await fh?.close().catch(() => {});
+ }
+}
+
+async function readTail(file: string, bytes: number): Promise<string | null> {
+ let fh;
+ try {
+ fh = await openFile(file, "r");
+ const { size } = await fh.stat();
+ const len = Math.min(bytes, size);
+ const buf = Buffer.allocUnsafe(len);
+ await fh.read(buf, 0, len, size - len);
+ return buf.toString("latin1");
+ } catch {
+ return null;
+ } finally {
+ await fh?.close().catch(() => {});
+ }
+}
+
+const num = (s: string | undefined): number | null => {
+ if (s === undefined) return null;
+ const n = Number(s);
+ return Number.isFinite(n) ? n : null;
+};
+
+function lastMatch(text: string, re: RegExp): RegExpExecArray | null {
+ let last: RegExpExecArray | null = null;
+ for (const m of text.matchAll(re)) last = m as RegExpExecArray;
+ return last;
+}
+
+export type MetaDates = {
+ releaseTimestamp: number | null;
+ timestamp: number | null;
+ uploadDate: string | null;
+ liveStatus: string | null;
+ duration: number | null;
+ /** The record's title and page URL — what a video with no transcript is listed by. */
+ title: string | null;
+ webpageUrl: string | null;
+};
+
+// The JSON string after the first `"<key>":` in `buf`, decoded (escapes and
+// UTF-8); null when it is absent, not a string, or longer than `max` bytes.
+function stringOf(buf: Buffer, key: string, max = 4096): string | null {
+ const at = buf.indexOf(`"${key}":`, 0, "latin1");
+ if (at < 0) return null;
+ let i = at + key.length + 3;
+ while (i < buf.length && (buf[i] === 0x20 || buf[i] === 0x0a || buf[i] === 0x0d || buf[i] === 0x09)) i++;
+ if (buf[i] !== 0x22) return null;
+ const end = Math.min(buf.length, i + 1 + max);
+ for (let j = i + 1; j < end; j++) {
+ if (buf[j] === 0x5c) j++;
+ else if (buf[j] === 0x22) {
+ try {
+ const v: unknown = JSON.parse(buf.toString("utf8", i, j + 1));
+ return typeof v === "string" && v.trim() ? v : null;
+ } catch {
+ return null;
+ }
+ }
+ }
+ return null;
+}
+
+// The value after `"<key>":` at byte `at` of `buf` (whitespace skipped): a
+// number's digits, or a string's contents — never more than 64 bytes.
+function valueAt(buf: Buffer, at: number, key: string): string | null {
+ let i = at + key.length + 3;
+ while (i < buf.length && (buf[i] === 0x20 || buf[i] === 0x0a || buf[i] === 0x0d || buf[i] === 0x09)) i++;
+ const quoted = buf[i] === 0x22;
+ if (quoted) i++;
+ const end = Math.min(buf.length, i + 64);
+ let j = i;
+ while (j < end && (quoted ? buf[j] !== 0x22 : /[0-9.a-z_]/.test(String.fromCharCode(buf[j]!)))) j++;
+ return j > i ? buf.toString("latin1", i, j) : null;
+}
+
+function first(buf: Buffer, key: string): string | null {
+ const at = buf.indexOf(`"${key}":`, 0, "latin1");
+ return at < 0 ? null : valueAt(buf, at, key);
+}
+
+function last(buf: Buffer, key: string, before = buf.length): { at: number; value: string | null } | null {
+ const at = buf.lastIndexOf(`"${key}":`, before, "latin1");
+ return at < 0 ? null : { at, value: valueAt(buf, at, key) };
+}
+
+/**
+ * The dating fields of a metadata.info.json, found by byte search — a YouTube
+ * record is megabytes of formats and caption URLs, and only these five scalars
+ * (and the title and page URL, two short strings) are wanted, so the file is
+ * never decoded whole or parsed. `release_timestamp` is
+ * taken wherever it is (no nested object carries one); `duration` is the last
+ * before `upload_date` (formats' fragments carry their own); `timestamp` is the one
+ * right after the last `upload_date` (yt-dlp's top-level order) when it is
+ * there, else the last in the file; airDateOf then refuses any timestamp more
+ * than two days from `upload_date`.
+ */
+export function metaDatesOf(input: Buffer | string): MetaDates {
+ const buf = typeof input === "string" ? Buffer.from(input, "latin1") : input;
+ const upload = last(buf, "upload_date");
+ let timestamp: string | null = null;
+ if (upload) {
+ const next = buf.indexOf('"timestamp":', upload.at, "latin1");
+ // Adjacent: only the upload date's value and a comma lie between them.
+ if (next > 0 && next - upload.at < 40) timestamp = valueAt(buf, next, "timestamp");
+ }
+ timestamp ??= last(buf, "timestamp")?.value ?? null;
+ const uploadDate = upload?.value && /^\d{8}$/.test(upload.value) ? upload.value : null;
+ const live = first(buf, "live_status");
+ // The record's own duration, not a format's: a YouTube storyboard format
+ // lists `"fragments": [{"duration": …}]` long before the top-level key, so
+ // the first in the file can be one sheet's seconds. The top-level one is the
+ // last before `upload_date`; with no upload date, the last in the file.
+ const duration = (upload ? last(buf, "duration", upload.at) : last(buf, "duration"))?.value ?? first(buf, "duration");
+ return {
+ releaseTimestamp: num(first(buf, "release_timestamp") ?? undefined),
+ timestamp: num(timestamp ?? undefined),
+ uploadDate,
+ liveStatus: live && /^[a-z_]+$/.test(live) ? live : null,
+ duration: num(duration ?? undefined),
+ // yt-dlp writes `id` then `title` first, before any nested object; the
+ // page URL has no nested namesake (`webpage_url_basename` is another key).
+ title: stringOf(buf, "title"),
+ webpageUrl: stringOf(buf, "webpage_url"),
+ };
+}
+
+type Scanned = {
+ channel: string;
+ video: string;
+ dir: string;
+ hasCues: boolean;
+ headUploadDate: string | null;
+ headDuration: number | null;
+};
+
+async function scanVideo(channel: string, dataDir: string, video: string): Promise<Scanned> {
+ const dir = path.join(dataDir, video);
+ const head = await readHead(path.join(dir, CUES_JSON_FILENAME), CUES_HEAD_BYTES);
+ if (head !== null) {
+ return {
+ channel,
+ video,
+ dir,
+ hasCues: true,
+ headUploadDate: /"uploadDate":\s*"(\d{8})"/.exec(head)?.[1] ?? null,
+ headDuration: num(/"duration":\s*(\d+(?:\.\d+)?)/.exec(head)?.[1]),
+ };
+ }
+ // No transcript: its upload date from the metadata's tail, where yt-dlp
+ // writes it (controller/recencyIndex.ts measured 99.8 %).
+ const tail = await readTail(path.join(dir, META_FILENAME), META_TAIL_BYTES);
+ return {
+ channel,
+ video,
+ dir,
+ hasCues: false,
+ headUploadDate: tail ? (lastMatch(tail, /"upload_date":\s*"(\d{8})"/g)?.[1] ?? null) : null,
+ headDuration: null,
+ };
+}
+
+type Cand = Scanned & {
+ air: AirDate;
+ meta: MetaDates | null;
+};
+
+type Loaded = {
+ video: LookoutPlanVideo;
+ cues: Cue[];
+ chars: number;
+ chunks: number;
+ shingles: Set<string>;
+};
+
+function cueLines(cues: readonly Cue[]): [number, string][] {
+ return cues.filter((c) => c.text.trim()).map((c) => [Math.floor(c.start), c.text.trim()] as [number, string]);
+}
+
+const NOT_FINISHED = new Set(["is_live", "is_upcoming"]);
+
+/**
+ * The plan for one lookout: what it would read, what it would not and why,
+ * and the estimate. Writes nothing.
+ */
+export async function planLookout(
+ paths: Paths,
+ item: LookoutItem,
+ opts: LookoutPlanOptions = {},
+): Promise<LookoutPlan> {
+ const days = opts.days ?? item.days;
+ const maxVideos = opts.maxVideos ?? item.maxVideos;
+ const window: LookoutWindow = lookoutWindow({ days, timeZone: item.timeZone, until: opts.until, now: opts.now });
+ const limit = opts.concurrency ?? 32;
+ const warnings: string[] = [];
+ const refused: LookoutPlan["refused"] = [];
+ if (item.channels.length === 0) throw new LookoutPlanRefusal(`lookout "${item.id}" names no channels`);
+
+ // ─── Stage 1: select ───
+ const scanned: Scanned[] = [];
+ let listed = 0;
+ for (const channel of item.channels) {
+ const config = await readChannelConfig(paths, channel);
+ if (!config) {
+ refused.push({ channel, reason: "not a channel this archive holds (a channel only on a remote site is not read in v1)" });
+ continue;
+ }
+ if (config.localMedia && !config.url?.trim()) {
+ refused.push({ channel, reason: "a local media library channel (not read in v1)" });
+ continue;
+ }
+ let dataDir: string;
+ try {
+ dataDir = (await assertChannelTextReadable(paths, channel, config)).dataDir;
+ } catch (err) {
+ refused.push({ channel, reason: (err as Error).message });
+ continue;
+ }
+ const videos = [...(await heldVideoIds(dataDir))].sort();
+ listed += videos.length;
+ const since = Date.parse(`${window.from}T00:00:00Z`) - CTIME_SLACK_MS;
+ const changed = await mapConcurrent(videos, limit, (v) =>
+ stat(path.join(dataDir, v)).then(
+ (st) => st.ctimeMs >= since,
+ () => false,
+ ),
+ );
+ const recent = videos.filter((_, i) => changed[i]);
+ scanned.push(...(await mapConcurrent(recent, limit, (v) => scanVideo(channel, dataDir, v))));
+ }
+
+ const lo = addDays(window.from, -PREFILTER_SLACK_DAYS);
+ const hi = addDays(window.to, PREFILTER_SLACK_DAYS);
+ const near = scanned.filter((s) => {
+ const d = isoOfUploadDate(s.headUploadDate);
+ return d === null || (d >= lo && d <= hi);
+ });
+ // A YouTube record's metadata is ~10 MB: a few at a time, never 32 at once
+ // in the editor's heap.
+ const dated = await mapConcurrent(near, Math.min(limit, 4), async (s): Promise<Cand | null> => {
+ let meta: MetaDates | null = null;
+ try {
+ meta = metaDatesOf(await readFile(path.join(s.dir, META_FILENAME)));
+ } catch {
+ meta = null;
+ }
+ const air = airDateOf(
+ {
+ releaseTimestamp: meta?.releaseTimestamp,
+ timestamp: meta?.timestamp,
+ uploadDate: meta?.uploadDate ?? s.headUploadDate,
+ },
+ window.timeZone,
+ );
+ return air && inWindow(air.date, window) ? { ...s, air, meta } : null;
+ });
+ const inWin = dated.filter((c): c is Cand => c !== null);
+
+ const skipped: LookoutPlanSkipped[] = [];
+ const brief = (c: Cand, over: Partial<LookoutPlanVideo> = {}): LookoutPlanVideo => ({
+ channel: c.channel,
+ video: c.video,
+ id: c.video,
+ // From the metadata: all a video with no transcript has to be named by.
+ title: c.meta?.title ?? "",
+ platform: "",
+ airDate: c.air.date,
+ airAt: c.air.at,
+ dateSource: c.air.source,
+ duration: c.headDuration ?? c.meta?.duration ?? null,
+ url: c.meta?.webpageUrl ?? null,
+ ...over,
+ });
+
+ // The transcripts of what is in the window: each read whole, once.
+ const loaded = new Map<string, Loaded>();
+ const withCues = inWin.filter((c) => c.hasCues);
+ const loads = await mapConcurrent(withCues, Math.min(limit, 8), async (c) => {
+ let doc: Record<string, unknown> | null = null;
+ try {
+ doc = JSON.parse(await readFile(path.join(c.dir, CUES_JSON_FILENAME), "utf8")) as Record<string, unknown>;
+ } catch {
+ warnings.push(`${c.channel}/${c.video}: transcript.cues.json is not readable JSON — treated as no transcript`);
+ }
+ return { c, doc };
+ });
+ let underMin = 0;
+ let other = 0;
+ let noTranscript = 0;
+ for (const c of inWin) {
+ if (!c.hasCues) {
+ noTranscript++;
+ skipped.push({ ...brief(c), reason: "no-transcript" });
+ }
+ }
+ for (const { c, doc } of loads) {
+ if (!doc) {
+ noTranscript++;
+ skipped.push({ ...brief(c), reason: "no-transcript" });
+ continue;
+ }
+ const cues = (Array.isArray(doc.cues) ? doc.cues : []).filter(
+ (x): x is Cue => !!x && typeof (x as Cue).start === "number" && typeof (x as Cue).text === "string",
+ );
+ const lastEnd = cues.length ? Math.round(cues[cues.length - 1]!.end) : null;
+ const duration = (typeof doc.duration === "number" && doc.duration > 0 ? doc.duration : null) ?? c.meta?.duration ?? lastEnd;
+ const video = brief(c, {
+ id: typeof doc.id === "string" ? doc.id : c.video,
+ title: typeof doc.title === "string" && doc.title ? doc.title : (c.meta?.title ?? ""),
+ platform: typeof doc.platform === "string" ? doc.platform : "",
+ duration,
+ url: typeof doc.webpageUrl === "string" && doc.webpageUrl ? doc.webpageUrl : (c.meta?.webpageUrl ?? null),
+ });
+ if (video.platform === "local" || LOCAL_RECORDING_ID_RE.test(video.id)) {
+ other++;
+ skipped.push({ ...video, reason: "local-recording" });
+ continue;
+ }
+ if (c.meta?.liveStatus && NOT_FINISHED.has(c.meta.liveStatus)) {
+ other++;
+ skipped.push({ ...video, reason: "not-finished" });
+ continue;
+ }
+ if (duration !== null && duration < item.minSeconds) {
+ underMin++;
+ skipped.push({ ...video, reason: "under-min-seconds" });
+ continue;
+ }
+ const chars = cues.reduce((s, x) => s + x.text.length, 0);
+ loaded.set(`${c.channel}/${c.video}`, {
+ video,
+ cues,
+ chars,
+ chunks: chunksOf(cueLines(cues), CHUNK_CHARS).length,
+ shingles: shingles(comparisonText(cues), LOOKOUT_SHINGLE_SIZE),
+ });
+ }
+
+ // ─── Stage 2: fold, then cap ───
+ const dedupe: DedupeVideo[] = [...loaded.entries()].map(([key, l]) => ({
+ key,
+ title: l.video.title,
+ platform: l.video.platform,
+ duration: l.video.duration,
+ airAt: l.video.airAt ?? l.video.airDate,
+ shingles: l.shingles,
+ }));
+ const groups = foldRecordings(dedupe);
+ const foldedOf = (keys: ReturnType<typeof foldRecordings>[number]["folded"]): LookoutPlanFolded[] =>
+ keys.map(({ key, ...rest }) => ({ ...loaded.get(key)!.video, ...rest }));
+ const read: LookoutPlanRead[] = [];
+ let duplicateUploads = 0;
+ let coveredByStream = 0;
+ let capped = 0;
+ for (const g of groups) {
+ for (const f of g.folded) {
+ if (f.reason === "duplicate-upload") duplicateUploads++;
+ else coveredByStream++;
+ }
+ const p = loaded.get(g.primary)!;
+ if (read.length < maxVideos) {
+ read.push({ ...p.video, chars: p.chars, chunks: p.chunks, folded: foldedOf(g.folded) });
+ } else {
+ capped++;
+ skipped.push({ ...p.video, reason: "cap", chunks: p.chunks, folded: foldedOf(g.folded) });
+ }
+ }
+
+ const readCalls = read.reduce((s, r) => s + r.chunks, 0);
+ const measured = await measuredSecondsPerCall(paths, item.id).catch(() => null);
+ const order: Record<string, number> = { cap: 0, "under-min-seconds": 1, "no-transcript": 2, "not-finished": 3, "local-recording": 4 };
+ skipped.sort(
+ (a, b) =>
+ order[a.reason]! - order[b.reason]! ||
+ (a.airDate < b.airDate ? -1 : a.airDate > b.airDate ? 1 : 0) ||
+ (`${a.channel}/${a.video}` < `${b.channel}/${b.video}` ? -1 : 1),
+ );
+ const datedByUploadDate = inWin.filter((c) => c.air.source === "upload_date").length;
+ if (datedByUploadDate) {
+ warnings.push(`${datedByUploadDate} video(s) in the window carry no timestamp: dated by their UTC upload_date, which may be a day off`);
+ }
+
+ return {
+ version: 1,
+ lookout: { id: item.id, label: item.label },
+ channels: item.channels,
+ refused,
+ window,
+ minSeconds: item.minSeconds,
+ maxVideos,
+ generatedAt: (opts.now ?? new Date()).toISOString(),
+ counts: {
+ scanned: listed,
+ examined: scanned.length,
+ inWindow: inWin.length - noTranscript,
+ noTranscript,
+ underMinSeconds: underMin,
+ qualified: loaded.size,
+ duplicateUploads,
+ coveredByStream,
+ recordings: groups.length,
+ read: read.length,
+ skippedForCap: capped,
+ otherSkipped: other,
+ datedByUploadDate,
+ },
+ read,
+ skipped,
+ estimate: {
+ readCalls,
+ secondsPerCall: measured ? Math.round(measured.secondsPerCall * 10) / 10 : null,
+ seconds: measured ? Math.round(readCalls * measured.secondsPerCall) : null,
+ basis: measured
+ ? `${measured.calls} calls over the last ${measured.runs} run(s); grouping calls (a few) not included`
+ : "no run has been measured yet: the first run records its seconds per call",
+ },
+ warnings,
+ };
+}
+
diff --git a/common/controller/voiceFile.test.ts b/common/controller/voiceFile.test.ts
@@ -50,7 +50,8 @@ if (kind === "openvoice" || kind === "seed-vc") {
const more = argv.includes("--more") ? JSON.parse(argv[argv.indexOf("--more") + 1]) : [];
for (const m of more) fs.copyFileSync(m.input, m.output);
console.error("voice: " + kind + " converted");
- console.log(JSON.stringify({ op: "convert", engine: kind, sampleRate: 48000, seconds: 1, samples: 48000, engineMs: 5, gainDb: 0 }));
+ const f0 = argv.includes("--pitch") ? { f0: { targetHz: 200, sourceHz: 150, shiftSemitones: 6.98 } } : {};
+ console.log(JSON.stringify({ op: "convert", engine: kind, sampleRate: 48000, seconds: 1, samples: 48000, engineMs: 5, gainDb: 0, ...f0 }));
process.exit(0);
}
const r = spawnSync(process.execPath, [${JSON.stringify(WRAPPER)}, ...argv], { stdio: "inherit" });
@@ -83,7 +84,7 @@ const {
} = await import("./voiceFile");
const { getPaths } = await import("../lib/paths");
const { DEFAULT_VOICE_SETTINGS } = await import("../lib/voiceSettings");
-const { OPENVOICE_FILES, getVoiceEngine, stockTargetPaths, voiceCodeDir } = await import("../lib/voiceApps");
+const { OPENVOICE_FILES, SEEDVC_F0_FILES, SEEDVC_FILES, getVoiceEngine, stockTargetPaths, voiceCodeDir } = await import("../lib/voiceApps");
const { VOICE_CODE_MARKER } = await import("../lib/voiceInstall");
const paths = getPaths();
@@ -122,7 +123,7 @@ async function engineRuns(): Promise<string[][]> {
test("the body keys are umtool's contract", () => {
assert.deepEqual([...VOICE_ENHANCE_BODY_KEYS], ["file", "path", "out", "engine", "params", "parts"]);
- assert.deepEqual([...VOICE_CONVERT_BODY_KEYS], ["file", "path", "out", "engine", "params", "parts", "voice", "target"]);
+ assert.deepEqual([...VOICE_CONVERT_BODY_KEYS], ["file", "path", "out", "engine", "params", "parts", "voice", "target", "pitch", "semitones"]);
});
test("the body's shape is judged before the disk", () => {
@@ -191,6 +192,74 @@ test("an engine is the op's own, and its params are checked", () => {
}
});
+test("a pitch is the engine's to follow: openvoice refuses one, seed-vc takes source and contour", () => {
+ const v = DEFAULT_VOICE_SETTINGS;
+ const ask = (b: Record<string, unknown>, voice = v) => {
+ const p = parseVoiceBody("convert", { file: "/a.wav", out: "/b.wav", ...b });
+ assert.ok(p.ok, !p.ok ? p.error : "");
+ return resolveVoiceRequest("convert", p.ok ? p.value : ({} as never), voice);
+ };
+ const refused = (b: Record<string, unknown>, re: RegExp, voice = v) => {
+ const r = ask(b, voice);
+ assert.ok(!r.ok, JSON.stringify(b));
+ if (!r.ok) {
+ assert.match(r.error, re);
+ // One sentence.
+ assert.equal(r.error.includes("\n"), false);
+ }
+ };
+ // Nothing asked: the target's own pitch, on every engine.
+ for (const engine of ["openvoice", "seed-vc"]) {
+ const r = ask({ engine });
+ assert.ok(r.ok);
+ if (r.ok) assert.deepEqual(r.value.pitch, { pitch: "target", semitones: 0 });
+ }
+ // An enhance has no pitch at all.
+ const en = resolveVoiceRequest("enhance", { file: "/a.wav", out: "/b.wav", engine: "rnnoise" }, v);
+ assert.ok(en.ok && en.value.pitch === undefined);
+ // OpenVoice has one pitch.
+ refused({ engine: "openvoice", pitch: "source" }, /^OpenVoice v2 \(tone-colour converter\) has no pitch control — .* "pitch" and "semitones" are seed-vc's/);
+ refused({ engine: "openvoice", semitones: 2 }, /has no pitch control/);
+ assert.ok(ask({ engine: "openvoice", pitch: "target", semitones: 0 }).ok);
+ // The values.
+ refused({ engine: "seed-vc", pitch: "up" }, /"pitch" is one of target, source, contour \(got "up"\)/);
+ refused({ engine: "seed-vc", pitch: "source", semitones: 13 }, /"semitones" is a number from -12 to 12 \(got 13\)/);
+ refused({ engine: "seed-vc", pitch: "source", semitones: "2" }, /"semitones" is a number from -12 to 12/);
+ // Semitones move a FOLLOWED pitch.
+ refused({ engine: "seed-vc", semitones: 2 }, /"semitones" moves a followed pitch — give "pitch": "source" or "contour"/);
+ refused({ engine: "seed-vc", pitch: "target", semitones: -1 }, /moves a followed pitch/);
+ const src = ask({ engine: "seed-vc", pitch: "source" });
+ assert.ok(src.ok);
+ if (src.ok) assert.deepEqual(src.value.pitch, { pitch: "source", semitones: 0 });
+ const con = ask({ engine: "seed-vc", pitch: "contour", semitones: -1.5 });
+ assert.ok(con.ok);
+ if (con.ok) assert.deepEqual(con.value.pitch, { pitch: "contour", semitones: -1.5 });
+ // settings.voice.convert's defaults: for the engine that can follow, and
+ // never a refusal for the one that cannot.
+ const follow = { ...v, convert: { ...v.convert, pitch: "contour" as const, semitones: 2 } };
+ const d = ask({ engine: "seed-vc" }, follow);
+ assert.ok(d.ok);
+ if (d.ok) assert.deepEqual(d.value.pitch, { pitch: "contour", semitones: 2 });
+ // A request naming its own followed pitch and no semitones takes the default semitones; 0 says none.
+ const named = ask({ engine: "seed-vc", pitch: "source" }, follow);
+ assert.ok(named.ok);
+ if (named.ok) assert.deepEqual(named.value.pitch, { pitch: "source", semitones: 2 });
+ const zero = ask({ engine: "seed-vc", pitch: "source", semitones: 0 }, follow);
+ assert.ok(zero.ok);
+ if (zero.ok) assert.deepEqual(zero.value.pitch, { pitch: "source", semitones: 0 });
+ const over = ask({ engine: "seed-vc", pitch: "target" }, follow);
+ assert.ok(over.ok);
+ if (over.ok) assert.deepEqual(over.value.pitch, { pitch: "target", semitones: 0 });
+ const ov = ask({ engine: "openvoice" }, follow);
+ assert.ok(ov.ok);
+ if (ov.ok) assert.deepEqual(ov.value.pitch, { pitch: "target", semitones: 0 });
+ // The argv: nothing new for the target's pitch.
+ const seed = getVoiceEngine("seed-vc")!;
+ const base = { input: "/a.wav", output: "/b.wav", installDir: "/i", params: {}, threads: 4, targetRef: "/r.wav", bins: { ffmpegBin: "ffmpeg", voiceModelsDir: "/m" } };
+ assert.equal(seed.build({ ...base, pitch: { pitch: "target", semitones: 0 } }).includes("--pitch"), false);
+ assert.deepEqual(seed.build({ ...base, pitch: { pitch: "contour", semitones: 2 } }).slice(-4), ["--pitch", "contour", "--semitones", "2"]);
+});
+
// --- the disk checks -----------------------------------------------------------
test("the disk checks: the input, the out, the install", { skip: SKIP }, async () => {
@@ -353,6 +422,68 @@ test("an engine that fails fails the job with its words", { skip: SKIP }, async
assert.match(r.log, /the voice engine exited 3: voice: engine exploded/);
});
+// A seed-vc install, faked to the pinned sizes with sparse files; `f0` adds the
+// optional group a followed pitch runs on.
+async function fakeSeedVcInstall(f0: boolean): Promise<string> {
+ const dir = path.join(HOME, "seed-vc");
+ await mkdir(path.join(dir, "venv", "bin"), { recursive: true });
+ await writeFile(path.join(dir, "venv", "bin", "python"), "");
+ const seed = getVoiceEngine("seed-vc")!;
+ if (seed.setup.kind !== "python-venv") throw new Error("seed-vc is a venv engine");
+ await mkdir(voiceCodeDir(dir), { recursive: true });
+ await writeFile(path.join(voiceCodeDir(dir), VOICE_CODE_MARKER), `${seed.setup.code.commit}\n`);
+ for (const f of [...SEEDVC_FILES, ...(f0 ? SEEDVC_F0_FILES : [])]) {
+ const p = path.join(dir, f.name);
+ await mkdir(path.dirname(p), { recursive: true });
+ const fh = await open(p, "w");
+ await fh.truncate(f.bytes);
+ await fh.close();
+ }
+ return dir;
+}
+
+test("a followed pitch needs seed-vc's f0 model: refused naming the setup command, then run with its own estimate", { skip: SKIP }, async () => {
+ await fakeSeedVcInstall(false);
+ const askTts = async (body: Record<string, unknown>) => {
+ await tone(String(body.out), 2);
+ return { ok: true as const, jobId: "tts-job-2", stream: new ReadableStream<string>(), done: Promise.resolve({ status: "done" as const, jobId: "tts-job-2" }) };
+ };
+ const take = path.join(OUTSIDE, "p-take.wav");
+ await tone(take, 1);
+ const before = (await engineRuns()).length;
+ // An install without the f0 files still converts at the target's pitch…
+ const plain = await runJob("convert", { file: take, out: path.join(OUTSIDE, "p-plain.wav"), engine: "seed-vc", voice: "espeak-ng:en-us" }, { askTts });
+ assert.equal(plain.status, "done", plain.log ?? plain.error);
+ assert.equal(plain.result.pitch, "target");
+ assert.equal("semitones" in plain.result, false);
+ assert.equal("f0" in plain.result, false);
+ assert.match(plain.log!, /estimate 3500 MB/);
+ const plainRun = (await engineRuns()).at(-1)!;
+ assert.equal(plainRun.includes("--pitch"), false);
+ // …and refuses a followed one, in one sentence, before any job.
+ const runs = (await engineRuns()).length;
+ assert.equal(runs, before + 1);
+ const refused = await runJob("convert", { file: take, out: path.join(OUTSIDE, "p-src.wav"), engine: "seed-vc", voice: "espeak-ng:en-us", pitch: "source" }, { askTts });
+ assert.match(
+ refused.error!,
+ /^pitch "source" needs Seed-VC \(v1, 22 kHz speech\)'s f0 model, which is not installed \(.*voice-home\/seed-vc: missing DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2\.pth; .*rmvpe\.pt; .*\) — run `archilyzer voice setup --engine seed-vc --with f0`$/,
+ );
+ assert.equal(refused.error!.includes("\n"), false);
+ assert.equal((await engineRuns()).length, runs);
+ // With them: the wrapper is told, the f0 run's estimate is declared, the result says what was done.
+ await fakeSeedVcInstall(true);
+ const r = await runJob("convert", { file: take, out: path.join(OUTSIDE, "p-con.wav"), engine: "seed-vc", voice: "espeak-ng:en-us", pitch: "contour", semitones: 2 }, { askTts });
+ assert.equal(r.status, "done", r.log ?? r.error);
+ const run = (await engineRuns()).at(-1)!;
+ assert.equal(run[run.indexOf("--pitch") + 1], "contour");
+ assert.equal(run[run.indexOf("--semitones") + 1], "2");
+ assert.match(r.log!, /Convert to espeak-ng:en-us \(pitch: contour \+2 st\)/);
+ assert.match(r.log!, new RegExp(`estimate ${getVoiceEngine("seed-vc")!.pitch!.defaultEstimateMB} MB`));
+ assert.equal(r.result.pitch, "contour");
+ assert.equal(r.result.semitones, 2);
+ assert.deepEqual(r.result.f0, { targetHz: 200, sourceHz: 150, shiftSemitones: 6.98 });
+});
+
test("a cancelled run stops the engine's whole process group", async () => {
const slow = path.join(BIN, "slow-engine");
await writeFile(slow, `#!/bin/sh\nsleep 30 &\nwait\n`);
diff --git a/common/controller/voiceFile.ts b/common/controller/voiceFile.ts
@@ -8,7 +8,13 @@
// THE BODY is umtool's contract (umtool/lib/report/postNarrationCli.mjs
// deriveTake): `{file, out, engine?, params?, parts?}`, and for convert
// `voice?` — the stock target (`target` is the same key's other name; `path`
-// is `file`'s). `file` is an absolute path to the recording (any format ffmpeg
+// is `file`'s) — and `pitch?` / `semitones?`: the pitch the conversion lands on
+// (lib/voiceApps.ts VoicePitch: `target`, the stock voice's own; `source`, the
+// read's; `contour`, the read's rises and falls at the stock voice's register;
+// `semitones` moves a followed one; defaults settings.voice.convert). An engine
+// with one pitch (openvoice) refuses another; a followed pitch whose model is
+// not installed (seed-vc's optional `f0` files) is refused naming the setup
+// command. `file` is an absolute path to the recording (any format ffmpeg
// reads, at most VOICE_MAX_SECONDS); `out` an absolute `.wav` path the result
// is written to — never inside the corpus, its directory existing; `engine`
// one of the op's engines (default settings.voice.<op>.engine); `params` the
@@ -37,7 +43,9 @@
// THE RESULT is logged as ONE line starting with VOICE_RESULT_MARKER (the
// marker umtool's askEditorOp reads): `{op, engine, wav, seconds, samples,
// sampleRate, engineMs, durationMs, waitedMs, gainDb, params, parts?,
-// target?, voice?, synthetic, disclosure?}`. `wav` is `out`, 48 kHz mono 16-bit, as
+// target?, voice?, pitch?, semitones?, f0?, synthetic, disclosure?}` (`pitch`
+// on every conversion; `f0` — {targetHz, sourceHz, shiftSemitones}, the medians
+// the tracker heard and the whole move — on a followed one). `wav` is `out`, 48 kHz mono 16-bit, as
// long as the input to the sample.
//
// WHAT IT TOUCHES: reads `file` and each part (anywhere); writes `out`, each
@@ -55,9 +63,11 @@ import type { StorageLocation } from "../lib/storageLocations";
import {
NO_CLONING,
VOICE_REFERENCE_TEXT,
+ describeVoicePitch,
getVoiceEngine,
parseStockTarget,
resolveVoiceParams,
+ resolveVoicePitch,
stockTargetPaths,
voiceConvertDisclosure,
voiceEngineIds,
@@ -65,8 +75,9 @@ import {
type StockTarget,
type VoiceEngine,
type VoiceOp,
+ type VoicePitchChoice,
} from "../lib/voiceApps";
-import { voiceInstallState } from "../lib/voiceInstall";
+import { voiceGroupState, voiceInstallState } from "../lib/voiceInstall";
import { DEFAULT_VOICE_SETTINGS, resolveVoiceHome, type VoiceSettings } from "../lib/voiceSettings";
import { getTtsEngine } from "../lib/ttsApps";
import { ttsInstallState } from "../lib/ttsInstall";
@@ -86,7 +97,7 @@ export const VOICE_RESULT_MARKER = "@@voice-result ";
// The bodies the routes accept; anything else is a 400.
export const VOICE_ENHANCE_BODY_KEYS = ["file", "path", "out", "engine", "params", "parts"] as const;
-export const VOICE_CONVERT_BODY_KEYS = [...VOICE_ENHANCE_BODY_KEYS, "voice", "target"] as const;
+export const VOICE_CONVERT_BODY_KEYS = [...VOICE_ENHANCE_BODY_KEYS, "voice", "target", "pitch", "semitones"] as const;
// The longest recording one op takes (a post read in full runs ~25 minutes).
export const VOICE_MAX_SECONDS = 1800;
@@ -103,6 +114,9 @@ export type VoiceFileBody = {
params?: unknown;
parts?: VoicePart[];
target?: string;
+ // Convert: as given, judged against the engine by resolveVoiceRequest.
+ pitch?: unknown;
+ semitones?: unknown;
};
function absWav(key: string, v: unknown, wav: boolean): Check<string> {
@@ -164,6 +178,8 @@ export function parseVoiceBody(op: VoiceOp, body: Record<string, unknown>): Chec
...(body.params !== undefined ? { params: body.params } : {}),
...(parts ? { parts } : {}),
...(target !== undefined ? { target } : {}),
+ ...(op === "convert" && body.pitch !== undefined ? { pitch: body.pitch } : {}),
+ ...(op === "convert" && body.semitones !== undefined ? { semitones: body.semitones } : {}),
},
};
}
@@ -178,6 +194,8 @@ export type VoiceRequest = {
out: string;
parts: VoicePart[];
target?: StockTarget;
+ // Convert: the pitch it lands on (target = the stock voice's own).
+ pitch?: VoicePitchChoice;
};
// The body plus settings.voice, resolved against the registry. Pure.
@@ -194,14 +212,27 @@ export function resolveVoiceRequest(
const params = resolveVoiceParams(engine, body.params);
if (!params.ok) return params;
let target: StockTarget | undefined;
+ let pitch: VoicePitchChoice | undefined;
if (op === "convert") {
const t = parseStockTarget(body.target ?? voice.convert.target);
if (!t.ok) return t;
target = t.value;
+ const p = resolveVoicePitch(engine, { pitch: body.pitch, semitones: body.semitones }, voice.convert);
+ if (!p.ok) return p;
+ pitch = p.value;
}
return {
ok: true,
- value: { op, engine, params: params.value, file: body.file, out: body.out, parts: body.parts ?? [], ...(target ? { target } : {}) },
+ value: {
+ op,
+ engine,
+ params: params.value,
+ file: body.file,
+ out: body.out,
+ parts: body.parts ?? [],
+ ...(target ? { target } : {}),
+ ...(pitch ? { pitch } : {}),
+ },
};
}
@@ -293,6 +324,18 @@ export async function checkVoiceRequest(req: VoiceRequest, ctx: VoiceFileContext
(req.engine.setup.kind === "bundled" ? req.engine.setup.hint : `run \`archilyzer voice setup --engine ${req.engine.id}\``),
};
}
+ // A followed pitch runs on the engine's optional model.
+ if (req.pitch && req.pitch.pitch !== "target" && req.engine.pitch) {
+ const group = voiceGroupState(req.engine, req.engine.pitch.group, { home: ctx.home });
+ if (group && !group.installed) {
+ return {
+ ok: false,
+ error:
+ `pitch "${req.pitch.pitch}" needs ${req.engine.label}'s ${group.id} model, which is not installed (${install.dir}: missing ${group.missing.join("; ")}) — ` +
+ `run \`archilyzer voice setup --engine ${req.engine.id} --with ${group.id}\``,
+ };
+ }
+ }
if (req.target) {
const tts = ctx.tts ?? DEFAULT_TTS_SETTINGS;
const ref = await stockReferenceState(req.target, ctx.home, tts);
@@ -368,6 +411,8 @@ export type EngineRunResult = {
sampleRate?: number;
engineMs?: number;
gainDb?: number;
+ // A followed pitch: the medians the tracker heard and the whole move applied.
+ f0?: { targetHz: number | null; sourceHz: number | null; shiftSemitones: number };
// The parts, when the run had more files (scripts/voice.mjs --more).
more?: { output: string; seconds: number; samples?: number; gainDb?: number }[];
};
@@ -482,12 +527,17 @@ export type VoiceResult = {
// shape a umtool take records).
target?: string;
voice?: string;
+ // Convert: the pitch it landed on, and for a followed one what was heard.
+ pitch?: VoicePitchChoice["pitch"];
+ semitones?: number;
+ f0?: EngineRunResult["f0"];
synthetic: boolean;
disclosure?: string;
};
function describe(req: VoiceRequest, seconds: number): string {
- const what = req.op === "enhance" ? "Enhance" : `Convert to ${req.target!.id}`;
+ const followed = describeVoicePitch(req.pitch);
+ const what = req.op === "enhance" ? "Enhance" : `Convert to ${req.target!.id}${followed ? ` (pitch: ${followed})` : ""}`;
const parts = req.parts.length ? ` and its ${req.parts.length} part(s)` : "";
return `${what}: ${Math.round(seconds * 10) / 10} s of ${req.file}${parts} with ${req.engine.id}`;
}
@@ -520,7 +570,11 @@ export async function enqueueVoiceFile(op: VoiceOp, body: Record<string, unknown
if (!checked.ok) return checked;
const req = checked.value;
const installDir = voiceInstallDir(home, req.engine);
- const estimateMB = voice.heavyEstimateMB[req.engine.id] ?? req.engine.defaultEstimateMB;
+ // A followed pitch is another model's run, with its own estimate.
+ const follows = req.pitch && req.pitch.pitch !== "target" ? req.engine.pitch : undefined;
+ const estimateMB = follows
+ ? (voice.heavyEstimateMB[follows.estimateKey] ?? follows.defaultEstimateMB)
+ : (voice.heavyEstimateMB[req.engine.id] ?? req.engine.defaultEstimateMB);
const asked = Date.now();
return runManagedFunction({
kind: VOICE_JOB_KIND[op],
@@ -558,6 +612,7 @@ export async function enqueueVoiceFile(op: VoiceOp, body: Record<string, unknown
threads: voice.threads,
...(targetRef ? { targetRef } : {}),
...(targetSe ? { targetSe } : {}),
+ ...(req.pitch ? { pitch: req.pitch } : {}),
bins: { ffmpegBin: opts.paths.ffmpegBin, voiceModelsDir: opts.paths.voiceModelsDir },
});
onLog(`Running ${req.engine.label}${req.parts.length ? ` over the take and its ${req.parts.length} part(s)` : ""} behind the heavy slot (estimate ${estimateMB} MB)…`);
@@ -582,6 +637,8 @@ export async function enqueueVoiceFile(op: VoiceOp, body: Record<string, unknown
params: req.params,
...(parts.length ? { parts } : {}),
...(req.target ? { target: req.target.id, voice: req.target.voice, disclosure: voiceConvertDisclosure(req.engine, req.target) } : {}),
+ ...(req.pitch ? { pitch: req.pitch.pitch, ...(req.pitch.pitch !== "target" ? { semitones: req.pitch.semitones } : {}) } : {}),
+ ...(follows && whole.f0 ? { f0: whole.f0 } : {}),
synthetic: op === "convert",
};
onLog(`${VOICE_RESULT_MARKER}${JSON.stringify(result)}`);
diff --git a/common/lib/duplicates.ts b/common/lib/duplicates.ts
@@ -266,7 +266,7 @@ const PLATFORM_PREFERENCE: ReadonlyArray<string> = [
"bitchute",
];
-function platformRank(platform: string): number {
+export function platformRank(platform: string): number {
const i = PLATFORM_PREFERENCE.indexOf(platform);
return i < 0 ? PLATFORM_PREFERENCE.length : i;
}
diff --git a/common/lib/lookout.test.ts b/common/lib/lookout.test.ts
@@ -0,0 +1,164 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ COVERED_THRESHOLD,
+ addDays,
+ airDateOf,
+ foldRecordings,
+ inWindow,
+ isIsoDate,
+ localDateOf,
+ lookoutWindow,
+ type DedupeVideo,
+} from "./lookout";
+import { shingles } from "./duplicates";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/lookout.test.ts
+
+// A real start time: 2026-11-04T01:20:53Z, an evening stream in New York.
+const EVENING_STREAM = 1793755253;
+
+test("the UTC trap: an evening stream airs on the local date, not on upload_date's", () => {
+ const ny = airDateOf({ releaseTimestamp: EVENING_STREAM, timestamp: EVENING_STREAM - 488, uploadDate: "20261104" }, "America/New_York");
+ assert.deepEqual(ny, { date: "2026-11-03", at: "2026-11-04T01:20:53.000Z", source: "release_timestamp" });
+ assert.equal(airDateOf({ releaseTimestamp: EVENING_STREAM, uploadDate: "20261104" }, "UTC")?.date, "2026-11-04");
+ assert.equal(airDateOf({ releaseTimestamp: EVENING_STREAM, uploadDate: "20261104" }, "Europe/Berlin")?.date, "2026-11-04");
+});
+
+test("release_timestamp, else timestamp, else upload_date — and a far-off timestamp is not believed", () => {
+ assert.equal(airDateOf({ timestamp: EVENING_STREAM, uploadDate: "20261104" }, "America/New_York")?.source, "timestamp");
+ assert.deepEqual(airDateOf({ uploadDate: "20261104" }, "America/New_York"), { date: "2026-11-04", at: null, source: "upload_date" });
+ // A nested key read by mistake, months away: the upload date wins.
+ assert.deepEqual(airDateOf({ timestamp: 1600000000, uploadDate: "20261104" }, "UTC"), { date: "2026-11-04", at: null, source: "upload_date" });
+ assert.equal(airDateOf({}, "UTC"), null);
+ assert.equal(airDateOf({ timestamp: 0, uploadDate: "garbage" }, "UTC"), null);
+});
+
+test("the window counts calendar days in the lookout's zone, both ends included", () => {
+ assert.deepEqual(lookoutWindow({ days: 7, timeZone: "America/New_York", until: "2026-11-10" }), {
+ from: "2026-11-04",
+ to: "2026-11-10",
+ days: 7,
+ timeZone: "America/New_York",
+ });
+ // "Today" is the zone's today: 03:00Z on 11 Nov is still 10 Nov in New York.
+ const now = new Date("2026-11-11T03:00:00Z");
+ assert.equal(lookoutWindow({ days: 1, timeZone: "America/New_York", now }).to, "2026-11-10");
+ assert.equal(lookoutWindow({ days: 1, timeZone: "UTC", now }).to, "2026-11-11");
+ assert.ok(inWindow("2026-11-04", { from: "2026-11-04", to: "2026-11-10" }));
+ assert.ok(!inWindow("2026-11-03", { from: "2026-11-04", to: "2026-11-10" }));
+ assert.equal(addDays("2026-02-28", 1), "2026-03-01");
+ assert.equal(addDays("2026-03-01", -1), "2026-02-28");
+ assert.ok(isIsoDate("2026-11-10") && !isIsoDate("2026-02-30") && !isIsoDate("20261110"));
+ assert.equal(localDateOf(Date.UTC(2026, 10, 4, 4, 59), "America/New_York"), "2026-11-03");
+});
+
+function text(seed: number, n: number): string[] {
+ let x = seed >>> 0;
+ return Array.from({ length: n }, () => {
+ x = (Math.imul(x, 1664525) + 1013904223) >>> 0;
+ return `w${(x >>> 16) % 3000}`;
+ });
+}
+const sh = (ws: string[]) => shingles(ws.join(" "), 5);
+function vid(key: string, o: Partial<DedupeVideo> & { words: string[] }): DedupeVideo {
+ return {
+ key,
+ title: o.title ?? key,
+ platform: o.platform ?? "youtube",
+ duration: o.duration ?? 600,
+ airAt: o.airAt ?? "2026-11-04T12:00:00.000Z",
+ shingles: sh(o.words),
+ };
+}
+
+test("a twin upload with the same title and runtime is folded, the first on the air read", () => {
+ const ws = text(1, 2000);
+ const groups = foldRecordings([
+ vid("b/yt", { words: ws, title: "Big News!", duration: 824, airAt: "2026-11-04T15:00:00.000Z" }),
+ vid("a/rumble", { words: ws.map((w, i) => (i % 12 === 0 ? "zz" : w)), title: "BIG NEWS", platform: "rumble", duration: 825, airAt: "2026-11-04T14:00:00.000Z" }),
+ ]);
+ assert.equal(groups.length, 1);
+ assert.equal(groups[0]!.primary, "a/rumble");
+ assert.deepEqual(groups[0]!.folded.map((f) => [f.key, f.reason, f.titleMatch]), [["b/yt", "duplicate-upload", true]]);
+});
+
+test("a re-titled mirror is caught by its text; a same-titled different video is caught by its runtime", () => {
+ const ws = text(2, 2000);
+ const retitled = foldRecordings([
+ vid("a/one", { words: ws, title: "THIS IS DISGRACEFUL!", duration: 825 }),
+ vid("b/two", { words: ws, title: "Massive Story Revealed & More", duration: 824, platform: "rumble" }),
+ ]);
+ assert.equal(retitled.length, 1);
+ assert.equal(retitled[0]!.folded[0]!.titleMatch, undefined);
+ assert.ok(retitled[0]!.folded[0]!.score > 0.9);
+ // The same title, a runtime 10 % off, unrelated text: two recordings.
+ const series = foldRecordings([
+ vid("a/ep1", { words: text(3, 2000), title: "Daily Show", duration: 900 }),
+ vid("a/ep2", { words: text(4, 2000), title: "Daily Show", duration: 1000 }),
+ ]);
+ assert.equal(series.length, 2);
+ // The same title and the same runtime, unrelated text: two episodes, both read.
+ const episodes = foldRecordings([
+ vid("a/mon", { words: text(5, 2000), title: "Daily Show", duration: 900 }),
+ vid("a/tue", { words: text(6, 2000), title: "Daily Show", duration: 905 }),
+ ]);
+ assert.equal(episodes.length, 2);
+ // ...unless one has no text to compare: then the title and runtime decide.
+ const silent = foldRecordings([
+ vid("a/mon", { words: text(5, 2000), title: "Daily Show", duration: 900 }),
+ vid("b/copy", { words: [], title: "Daily Show", duration: 905 }),
+ ]);
+ assert.equal(silent.length, 1);
+ // Near-identical text but runtimes far apart is not a twin (it may be a cut-down; see below).
+ const apart = foldRecordings([
+ vid("a/x", { words: ws, duration: 600 }),
+ vid("b/y", { words: ws, duration: 700 }),
+ ]);
+ assert.equal(apart.length, 2);
+});
+
+test("a cut-down is credited to the stream it is cut from, with its share", () => {
+ const stream = text(5, 20000);
+ const groups = foldRecordings([
+ vid("s/stream", { words: stream, duration: 7200, platform: "rumble", airAt: "2026-11-04T01:20:53.000Z" }),
+ vid("c/cut", { words: stream.slice(5000, 6500), duration: 700, title: "Clip" }),
+ vid("c/cut-twin", { words: stream.slice(5000, 6500), duration: 701, title: "Clip", platform: "rumble" }),
+ vid("o/other", { words: text(6, 1500), duration: 700, title: "Other" }),
+ ]);
+ assert.deepEqual(groups.map((g) => g.primary), ["s/stream", "o/other"]);
+ const s = groups[0]!;
+ assert.deepEqual(
+ s.folded.map((f) => [f.key, f.reason, f.matched]).sort(),
+ [
+ ["c/cut", "covered-by-stream", "s/stream"],
+ ["c/cut-twin", "covered-by-stream", "s/stream"],
+ ],
+ );
+ assert.ok(s.folded.every((f) => f.score >= COVERED_THRESHOLD));
+});
+
+test("a short video sharing a little of a stream is not its cut-down", () => {
+ const stream = text(7, 20000);
+ const mixed = [...stream.slice(100, 300), ...text(8, 800)];
+ const groups = foldRecordings([
+ vid("s/stream", { words: stream, duration: 7200 }),
+ vid("c/mixed", { words: mixed, duration: 400 }),
+ ]);
+ assert.equal(groups.length, 2);
+});
+
+test("every input appears exactly once, as a primary or folded", () => {
+ const stream = text(9, 10000);
+ const vids = [
+ vid("s/1", { words: stream, duration: 4000 }),
+ vid("s/2", { words: stream, duration: 4010, platform: "rumble" }),
+ vid("c/1", { words: stream.slice(0, 900), duration: 500 }),
+ vid("c/2", { words: text(10, 900), duration: 500 }),
+ vid("c/3", { words: text(10, 900), duration: 501, platform: "rumble" }),
+ ];
+ const groups = foldRecordings(vids);
+ const seen = groups.flatMap((g) => [g.primary, ...g.folded.map((f) => f.key)]).sort();
+ assert.deepEqual(seen, vids.map((v) => v.key).sort());
+});
diff --git a/common/lib/lookout.ts b/common/lib/lookout.ts
@@ -0,0 +1,407 @@
+// A LOOKOUT'S SELECTION, the pure half (lane/lookout stages 1–2): air dates,
+// the window, and the folding of one recording's several uploads into one read.
+// No I/O — controller/lookoutPlan.ts reads the channels and calls these.
+//
+// AIR DATE, NOT UPLOAD DATE. yt-dlp's `upload_date` is a UTC date, so an
+// evening stream in the Americas lands on the next day: an election-night
+// stream that started at 20:20 in New York is 4 Nov by `upload_date` and 3 Nov
+// on the air. A lookout's days are counted in its own time zone from the
+// metadata's `release_timestamp` (a stream's or premiere's start), else its
+// `timestamp` (the upload), and only when neither is there from `upload_date`,
+// which the plan then marks as such.
+//
+// ONE RECORDING, READ ONCE. Two cases, both decided on the cues, because
+// `transcripts/duplicates.json` is built rarely and does not know this week:
+// - a DUPLICATE UPLOAD — the same recording on two channels or platforms —
+// is two videos whose runtimes agree within 2 % and whose normalised titles
+// match or whose transcripts are near-duplicates (5-word shingle Jaccard ≥
+// 0.35, the duplicate detector's own threshold: two ASR engines over the
+// same audio land at 0.35–0.60). A re-titled mirror is caught by the text.
+// A title match alone is not enough when both have text: two episodes of
+// a show with one title and one length share none, so it also needs a
+// Jaccard of 0.1.
+// - a CUT-DOWN of a stream — a shorter upload whose text is an excerpt of a
+// long recording in the window — is a video under 30 minutes at least 40 %
+// of whose shingles are in one stream (the pilot's measured rule). It is
+// credited to the stream as an alternate source and not read on its own.
+// Every folded video stays in the plan, under the recording it was folded into,
+// with why and its score.
+
+import {
+ DEFAULT_NEAR_THRESHOLD,
+ DEFAULT_SHINGLE_SIZE,
+ DEFAULT_TITLE_DURATION_RATIO,
+ UnionFind,
+ durationsCompatible,
+ intersectionSize,
+ jaccard,
+ normalizeTitleKey,
+ platformRank,
+} from "./duplicates";
+
+// ─── Air dates and the window ───
+
+export type AirDateSource = "release_timestamp" | "timestamp" | "upload_date";
+
+export type AirDate = {
+ /** YYYY-MM-DD in the lookout's time zone (or the UTC upload date, when that is all there is). */
+ date: string;
+ /** ISO 8601 instant, when a timestamp gave it. */
+ at: string | null;
+ source: AirDateSource;
+};
+
+/** The machine's IANA zone (what a lookout's `timeZone: ""` means). */
+export function machineTimeZone(): string {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
+}
+
+/** `tz`, or the machine's when it is "". */
+export function resolveTimeZone(tz: string): string {
+ return tz ? tz : machineTimeZone();
+}
+
+/** The calendar date (YYYY-MM-DD) of an instant in `tz`. */
+export function localDateOf(ms: number, tz: string): string {
+ const parts = new Intl.DateTimeFormat("en-US", {
+ timeZone: tz,
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ }).formatToParts(new Date(ms));
+ const get = (t: string) => parts.find((p) => p.type === t)?.value ?? "";
+ return `${get("year")}-${get("month")}-${get("day")}`;
+}
+
+/** "20261104" → "2026-11-04"; null for anything else. */
+export function isoOfUploadDate(yyyymmdd: string | null | undefined): string | null {
+ if (typeof yyyymmdd !== "string" || !/^\d{8}$/.test(yyyymmdd)) return null;
+ return `${yyyymmdd.slice(0, 4)}-${yyyymmdd.slice(4, 6)}-${yyyymmdd.slice(6, 8)}`;
+}
+
+const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
+
+export function isIsoDate(s: unknown): s is string {
+ if (typeof s !== "string" || !ISO_DATE_RE.test(s)) return false;
+ const d = new Date(`${s}T00:00:00Z`);
+ return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s;
+}
+
+/** A YYYY-MM-DD date `n` days later (negative: earlier). */
+export function addDays(date: string, n: number): string {
+ const d = new Date(`${date}T00:00:00Z`);
+ d.setUTCDate(d.getUTCDate() + n);
+ return d.toISOString().slice(0, 10);
+}
+
+/** Whole days from `a` to `b` (both YYYY-MM-DD). */
+export function daysBetween(a: string, b: string): number {
+ return Math.round((Date.parse(`${b}T00:00:00Z`) - Date.parse(`${a}T00:00:00Z`)) / 86_400_000);
+}
+
+// A timestamp further than this from the record's own UTC `upload_date` is not
+// believed (a nested key read by mistake, a broken record): the upload date is
+// used instead and the plan says so.
+const TIMESTAMP_TRUST_DAYS = 2;
+
+/**
+ * A video's air date in `tz`: its `release_timestamp`, else its `timestamp`
+ * (seconds since the epoch, as yt-dlp writes them), else its `upload_date`.
+ * Null when it has none of the three.
+ */
+export function airDateOf(
+ meta: { releaseTimestamp?: number | null; timestamp?: number | null; uploadDate?: string | null },
+ tz: string,
+): AirDate | null {
+ const upload = isoOfUploadDate(meta.uploadDate);
+ const candidates: [AirDateSource, number | null | undefined][] = [
+ ["release_timestamp", meta.releaseTimestamp],
+ ["timestamp", meta.timestamp],
+ ];
+ for (const [source, ts] of candidates) {
+ if (typeof ts !== "number" || !Number.isFinite(ts) || ts <= 0) continue;
+ const ms = ts * 1000;
+ const utc = new Date(ms).toISOString().slice(0, 10);
+ if (upload && Math.abs(daysBetween(upload, utc)) > TIMESTAMP_TRUST_DAYS) continue;
+ return { date: localDateOf(ms, tz), at: new Date(ms).toISOString(), source };
+ }
+ return upload ? { date: upload, at: null, source: "upload_date" } : null;
+}
+
+export type LookoutWindow = {
+ /** First day read, YYYY-MM-DD, inclusive. */
+ from: string;
+ /** Last day read, YYYY-MM-DD, inclusive. */
+ to: string;
+ days: number;
+ timeZone: string;
+};
+
+/**
+ * The `days` calendar days ending on `until` (default: today in `tz`), both
+ * ends included: days 7 on 11 Nov is 5–11 Nov.
+ */
+export function lookoutWindow(o: { days: number; timeZone: string; until?: string | null; now?: Date }): LookoutWindow {
+ const tz = resolveTimeZone(o.timeZone);
+ const to = o.until && isIsoDate(o.until) ? o.until : localDateOf((o.now ?? new Date()).getTime(), tz);
+ const days = Math.max(1, Math.round(o.days));
+ return { from: addDays(to, -(days - 1)), to, days, timeZone: tz };
+}
+
+export function inWindow(date: string, w: Pick<LookoutWindow, "from" | "to">): boolean {
+ return date >= w.from && date <= w.to;
+}
+
+// ─── One recording, read once ───
+
+export const LOOKOUT_SHINGLE_SIZE = DEFAULT_SHINGLE_SIZE;
+/** Duplicate uploads: transcripts at least this similar (Jaccard) are one recording. */
+export const TWIN_TEXT_THRESHOLD = DEFAULT_NEAR_THRESHOLD;
+/** Duplicate uploads with the same title: their transcripts still share at least this much (Jaccard), when both have text. */
+export const TWIN_TITLE_TEXT_FLOOR = 0.1;
+/** Duplicate uploads: runtimes within this fraction of the longer. */
+export const TWIN_DURATION_RATIO = DEFAULT_TITLE_DURATION_RATIO;
+/** A recording this long or longer is a stream other uploads may be cut from. */
+export const STREAM_MIN_SECONDS = 1800;
+/** A shorter upload with at least this share of its shingles in a stream is that stream's cut-down. */
+export const COVERED_THRESHOLD = 0.4;
+
+export type DedupeVideo = {
+ /** `<channel>/<video dir>` — unique in a plan. */
+ key: string;
+ title: string;
+ platform: string;
+ duration: number | null;
+ /** ISO instant or date the video aired, for the tie-break (earliest first). */
+ airAt: string;
+ /** Shingles of its cue text (`comparisonText` → `shingles`). */
+ shingles: ReadonlySet<string>;
+};
+
+export type FoldReason = "duplicate-upload" | "covered-by-stream";
+
+export type FoldedVideo = {
+ key: string;
+ reason: FoldReason;
+ /** The video it was compared with: the twin it matched, or the stream it is cut from. */
+ matched: string;
+ /** Jaccard (a duplicate upload) or the share of its shingles in the stream (a cut-down), 0–1. */
+ score: number;
+ /** A duplicate upload whose normalised title matched as well. */
+ titleMatch?: boolean;
+};
+
+export type RecordingGroup = {
+ /** The upload read for this recording. */
+ primary: string;
+ /** Every other upload of it, and every cut-down credited to it. */
+ folded: FoldedVideo[];
+};
+
+const round2 = (n: number) => Math.round(n * 100) / 100;
+
+// The upload read for a set of duplicates — and so the date the recording is
+// listed on: the FIRST on the air (a stream is dated by its start, not by the
+// copy posted the next morning), then the preferred platform (duplicates.ts'
+// order), then the longest, then the key.
+function better(a: DedupeVideo, b: DedupeVideo): boolean {
+ if (a.airAt !== b.airAt) return a.airAt < b.airAt;
+ const pa = platformRank(a.platform);
+ const pb = platformRank(b.platform);
+ if (pa !== pb) return pa < pb;
+ const da = a.duration ?? 0;
+ const db = b.duration ?? 0;
+ if (da !== db) return da > db;
+ return a.key < b.key;
+}
+
+/** |A∩B| / |A|: how much of `a` is in `b`. */
+function shareIn(a: ReadonlySet<string>, b: ReadonlySet<string>): number {
+ if (a.size === 0) return 0;
+ return intersectionSize(a as Set<string>, b as Set<string>) / a.size;
+}
+
+/**
+ * Fold `videos` into recordings: duplicate uploads first, then cut-downs of a
+ * stream. Every input appears exactly once — as a group's primary or as one of
+ * its folded videos. Groups come back longest primary first.
+ */
+export function foldRecordings(videos: readonly DedupeVideo[]): RecordingGroup[] {
+ const byKey = new Map(videos.map((v) => [v.key, v]));
+ const uf = new UnionFind();
+ const twinEdge = new Map<string, { score: number; titleMatch: boolean }>();
+ const titleKeys = new Map(videos.map((v) => [v.key, normalizeTitleKey(v.title)]));
+ for (const v of videos) uf.add(v.key);
+ for (let i = 0; i < videos.length; i++) {
+ for (let j = i + 1; j < videos.length; j++) {
+ const a = videos[i]!;
+ const b = videos[j]!;
+ if (!a.duration || !b.duration || !durationsCompatible(a.duration, b.duration, TWIN_DURATION_RATIO)) continue;
+ const ta = titleKeys.get(a.key)!;
+ const titleMatch = ta !== "" && ta === titleKeys.get(b.key);
+ const score = jaccard(a.shingles as Set<string>, b.shingles as Set<string>);
+ // A title is not a recording: a daily show keeps one title and much the
+ // same runtime. With both transcripts in hand a title match still needs
+ // some shared text; with one empty there is only the title to go on.
+ const titleTwin =
+ titleMatch && (a.shingles.size === 0 || b.shingles.size === 0 || score >= TWIN_TITLE_TEXT_FLOOR);
+ if (!titleTwin && score < TWIN_TEXT_THRESHOLD) continue;
+ uf.union(a.key, b.key);
+ twinEdge.set(`${a.key}\n${b.key}`, { score, titleMatch });
+ twinEdge.set(`${b.key}\n${a.key}`, { score, titleMatch });
+ }
+ }
+
+ type Group = { primary: DedupeVideo; members: DedupeVideo[]; folded: FoldedVideo[] };
+ const groups: Group[] = uf.groups().map((keys) => {
+ const members = keys.map((k) => byKey.get(k)!).sort((a, b) => (a.key < b.key ? -1 : 1));
+ const primary = members.reduce((best, v) => (better(v, best) ? v : best));
+ const folded: FoldedVideo[] = members
+ .filter((m) => m !== primary)
+ .map((m) => {
+ const edge = twinEdge.get(`${m.key}\n${primary.key}`);
+ const score = edge?.score ?? jaccard(m.shingles as Set<string>, primary.shingles as Set<string>);
+ return {
+ key: m.key,
+ reason: "duplicate-upload" as const,
+ matched: primary.key,
+ score: round2(score),
+ ...(normalizeTitleKey(m.title) === titleKeys.get(primary.key) ? { titleMatch: true } : {}),
+ };
+ });
+ return { primary, members, folded };
+ });
+
+ const isStream = (g: Group) => (g.primary.duration ?? 0) >= STREAM_MIN_SECONDS;
+ const streams = groups.filter(isStream).map((g) => {
+ // The stream's text is every upload of it: a cut-down posted to YouTube
+ // matches the YouTube copy of a stream better than the other platform's.
+ const all = new Set<string>();
+ for (const m of g.members) for (const s of m.shingles) all.add(s);
+ return { group: g, shingles: all };
+ });
+ const kept: Group[] = [];
+ for (const g of groups) {
+ if (isStream(g) || streams.length === 0) {
+ kept.push(g);
+ continue;
+ }
+ let best: { stream: (typeof streams)[number]; share: number; member: DedupeVideo } | null = null;
+ for (const stream of streams) {
+ for (const m of g.members) {
+ const share = shareIn(m.shingles, stream.shingles);
+ if (!best || share > best.share) best = { stream, share, member: m };
+ }
+ }
+ if (!best || best.share < COVERED_THRESHOLD) {
+ kept.push(g);
+ continue;
+ }
+ const target = best.stream.group;
+ for (const m of g.members) {
+ target.folded.push({
+ key: m.key,
+ reason: "covered-by-stream",
+ matched: target.primary.key,
+ score: round2(shareIn(m.shingles, best.stream.shingles)),
+ });
+ }
+ }
+ return kept
+ .sort((a, b) => (b.primary.duration ?? 0) - (a.primary.duration ?? 0) || (a.primary.key < b.primary.key ? -1 : 1))
+ .map((g) => ({
+ primary: g.primary.key,
+ folded: g.folded.sort((a, b) => (a.reason === b.reason ? (a.key < b.key ? -1 : 1) : a.reason === "duplicate-upload" ? -1 : 1)),
+ }));
+}
+
+// ─── The plan: what a lookout would read ───
+
+/** One video as a plan names it. */
+export type LookoutPlanVideo = {
+ channel: string;
+ /** Its directory under `channels/<channel>/data/`. */
+ video: string;
+ /** The record's id (a Rumble video's directory is its URL slug; its id is the embed id). */
+ id: string;
+ title: string;
+ platform: string;
+ airDate: string;
+ airAt: string | null;
+ dateSource: AirDateSource;
+ /** Seconds; null when neither the cues nor the metadata say. */
+ duration: number | null;
+ url: string | null;
+};
+
+export type LookoutPlanFolded = LookoutPlanVideo & Omit<FoldedVideo, "key">;
+
+export type LookoutPlanRead = LookoutPlanVideo & {
+ /** Characters of transcript text. */
+ chars: number;
+ /** Model-sized chunks (sweep-pipeline's CHUNK_CHARS) — one reading call each. */
+ chunks: number;
+ /** The other uploads of this recording and the cut-downs credited to it. */
+ folded: LookoutPlanFolded[];
+};
+
+export type LookoutSkipReason =
+ | "under-min-seconds"
+ | "no-transcript"
+ | "local-recording"
+ | "not-finished"
+ | "cap";
+
+export type LookoutPlanSkipped = LookoutPlanVideo & {
+ reason: LookoutSkipReason;
+ /** A cap skip carries the uploads folded into it, so nothing it stood for is lost from view. */
+ folded?: LookoutPlanFolded[];
+ chunks?: number;
+};
+
+export type LookoutPlan = {
+ version: 1;
+ lookout: { id: string; label: string };
+ channels: string[];
+ /** Channels named but not read, and why (a local library, a slug this archive does not hold, unreadable text). */
+ refused: { channel: string; reason: string }[];
+ window: LookoutWindow;
+ minSeconds: number;
+ maxVideos: number;
+ generatedAt: string;
+ counts: {
+ /** Video directories listed, across the channels read. */
+ scanned: number;
+ /** Of those, the ones changed since shortly before the window (directory ctime), whose files were read. */
+ examined: number;
+ /** Videos with a transcript whose air date is in the window. */
+ inWindow: number;
+ /** Videos in the window with no transcript yet (not read, listed). */
+ noTranscript: number;
+ underMinSeconds: number;
+ /** In the window, with a transcript, long enough — what is folded and capped. */
+ qualified: number;
+ duplicateUploads: number;
+ coveredByStream: number;
+ /** Recordings after folding. */
+ recordings: number;
+ read: number;
+ skippedForCap: number;
+ /** Other skips: local recordings, live or upcoming videos. */
+ otherSkipped: number;
+ /** In the window, dated by `upload_date` alone (no timestamp in the metadata). */
+ datedByUploadDate: number;
+ };
+ read: LookoutPlanRead[];
+ skipped: LookoutPlanSkipped[];
+ estimate: {
+ /** One reading call per chunk of every recording read (a video with fresh reading notes will need none: slice 2). */
+ readCalls: number;
+ /** Measured over the lookout's last runs; null before the first. */
+ secondsPerCall: number | null;
+ /** readCalls × secondsPerCall, rounded; null when not measured. Grouping calls (a few) are not in it. */
+ seconds: number | null;
+ basis: string;
+ };
+ warnings: string[];
+};
diff --git a/common/lib/lookoutNoChannelNames.test.ts b/common/lib/lookoutNoChannelNames.test.ts
@@ -0,0 +1,75 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/lookoutNoChannelNames.test.ts
+//
+// NO CHANNEL IS NAMED IN THE LOOKOUT'S CODE (lane/lookout, acceptance c). A
+// lookout is configured on the machine that runs it; the standing one is a
+// settings patch there, never a default, an example or a fixture here. This
+// test walks every file whose path names a lookout — the libs, the
+// controllers, the ops routes and their tests, and whatever later slices add
+// under those names — and fails on any word of the pilot lookout's channel
+// names. The words are kept as SHA-256 digests so the guard does not itself
+// spell what it forbids.
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const REPO = path.resolve(HERE, "..", "..");
+const ROOTS = ["common/lib", "common/controller", "common/bin", "common/jobs", "editor/app", "umtool/lib", "umtool/app", "umtool/bin"];
+
+// sha256 of each forbidden word (lowercase): the two distinctive words of the
+// pilot lookout's four channel slugs.
+const FORBIDDEN = new Set([
+ "7a0b56a32407bfffffb453b775850130b36277a20de9611f153c0d3bf3dfa153",
+ "877a89b30f7ffb2b5b079e4a84066c05c476a1dda97209fce21d3a4aefac3dfc",
+]);
+
+const sha = (w: string) => createHash("sha256").update(w).digest("hex");
+
+async function lookoutFiles(dir: string, under = false): Promise<string[]> {
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ const out: string[] = [];
+ for (const e of entries) {
+ if (e.name === "node_modules" || e.name.startsWith(".")) continue;
+ const p = path.join(dir, e.name);
+ const named = under || /lookout/i.test(e.name);
+ if (e.isDirectory()) out.push(...(await lookoutFiles(p, named)));
+ else if (named && /\.(ts|tsx|mjs|js|json|md)$/.test(e.name)) out.push(p);
+ }
+ return out;
+}
+
+test("the guard is live: its digests match words the repo's own docs use", async () => {
+ // A positive control, so a mistyped digest cannot silently disable the
+ // guard: the repo's instructions and the ops examples DO name these
+ // channels (they predate the lookout), and every digest must match there.
+ const docs = ["AGENTS.md", "plans/FACTS.md", "scripts/archilyzer-ops.mjs"];
+ const seen = new Set<string>();
+ for (const f of docs) {
+ for (const w of (await readFile(path.join(REPO, f), "utf8")).toLowerCase().match(/[a-z0-9]+/g) ?? []) {
+ const d = sha(w);
+ if (FORBIDDEN.has(d)) seen.add(d);
+ }
+ }
+ assert.deepEqual([...seen].sort(), [...FORBIDDEN].sort());
+});
+
+test("no lookout file names a channel of the pilot lookout", async () => {
+ const files = (await Promise.all(ROOTS.map((r) => lookoutFiles(path.join(REPO, r))))).flat();
+ assert.ok(files.length >= 6, `found the lookout's files (${files.length})`);
+ const hits: string[] = [];
+ for (const f of files) {
+ const words = new Set((await readFile(f, "utf8")).toLowerCase().match(/[a-z0-9]+/g) ?? []);
+ for (const w of words) if (FORBIDDEN.has(sha(w))) hits.push(path.relative(REPO, f));
+ }
+ assert.deepEqual(hits, []);
+});
diff --git a/common/lib/lookoutSettings.test.ts b/common/lib/lookoutSettings.test.ts
@@ -0,0 +1,78 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ DEFAULT_LOOKOUTS_SETTINGS,
+ lookoutById,
+ lookoutIdFrom,
+ sanitizeLookoutItem,
+ sanitizeLookouts,
+} from "./lookoutSettings";
+import { defaults, siteSettingsSchema } from "./settingsSchema";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/lookoutSettings.test.ts
+
+test("off and empty by default, in the schema too", () => {
+ assert.deepEqual(DEFAULT_LOOKOUTS_SETTINGS, { enabled: false, afterSync: false, items: [] });
+ assert.deepEqual(sanitizeLookouts(undefined), DEFAULT_LOOKOUTS_SETTINGS);
+ assert.deepEqual(defaults().lookouts, DEFAULT_LOOKOUTS_SETTINGS);
+ assert.deepEqual(siteSettingsSchema.parse({ lookouts: "nonsense" }).lookouts, DEFAULT_LOOKOUTS_SETTINGS);
+});
+
+test("an item gets every default it leaves out", () => {
+ assert.deepEqual(sanitizeLookoutItem({ id: "weekly", channels: ["example-news", "example-live"] }), {
+ id: "weekly",
+ label: "weekly",
+ channels: ["example-news", "example-live"],
+ days: 7,
+ prompt: "",
+ maxVideos: 40,
+ minSeconds: 90,
+ timeZone: "",
+ siteOrigin: "",
+ });
+});
+
+test("an item is coerced, never thrown on", () => {
+ const item = sanitizeLookoutItem({
+ label: " Example Week! ",
+ channels: ["example-news", "example-news", "", 7, "../escape", "ok.slug_1"],
+ days: 999,
+ maxVideos: "12",
+ minSeconds: -5,
+ timeZone: "Mars/Olympus",
+ siteOrigin: "https://example.pages.dev/some/path?q=1",
+ prompt: "x".repeat(5000),
+ });
+ assert.ok(item);
+ assert.equal(item.id, "example-week");
+ assert.equal(item.label, "Example Week!");
+ assert.deepEqual(item.channels, ["example-news", "ok.slug_1"]);
+ assert.equal(item.days, 60);
+ assert.equal(item.maxVideos, 12);
+ assert.equal(item.minSeconds, 0);
+ assert.equal(item.timeZone, "", "an unknown zone falls back to the machine's");
+ assert.equal(item.siteOrigin, "https://example.pages.dev");
+ assert.equal(item.prompt.length, 4000);
+ assert.equal(sanitizeLookoutItem({ timeZone: "America/Chicago", id: "a" })?.timeZone, "America/Chicago");
+ assert.equal(sanitizeLookoutItem({ siteOrigin: "ftp://x.example", id: "a" })?.siteOrigin, "");
+});
+
+test("an item with no usable id is dropped, and so is a second with the same id", () => {
+ const s = sanitizeLookouts({
+ enabled: true,
+ afterSync: "yes",
+ items: [{ channels: ["a"] }, { id: "one", channels: ["a"] }, { id: "one", channels: ["b"] }, "junk", { label: "Two" }],
+ });
+ assert.equal(s.enabled, true);
+ assert.equal(s.afterSync, false, "only true is true");
+ assert.deepEqual(s.items.map((i) => [i.id, i.channels]), [["one", ["a"]], ["two", []]]);
+ assert.equal(lookoutById(s, "two")?.label, "Two");
+ assert.equal(lookoutById(s, "three"), null);
+});
+
+test("lookoutIdFrom makes a slug", () => {
+ assert.equal(lookoutIdFrom("Café Weekly — News"), "cafe-weekly-news");
+ assert.equal(lookoutIdFrom("!!!"), "");
+ assert.equal(lookoutIdFrom("a".repeat(80)).length, 64);
+});
diff --git a/common/lib/lookoutSettings.ts b/common/lib/lookoutSettings.ts
@@ -0,0 +1,182 @@
+// settings.lookouts — saved lookouts (lane/lookout). A lookout is a saved set of
+// channels, a number of days back and an optional prompt; a run reads those
+// channels' recent transcripts and answers with video ideas. Pure: the types,
+// the defaults, the sanitizer settingsSchema.ts runs the block through, and the
+// per-field docs SETTINGS.md renders.
+//
+// OFF AND EMPTY BY DEFAULT, and no channel is named here or anywhere in code: a
+// lookout is configured on the machine that runs it (`pnpm ops settings`), so
+// adding one is a settings patch, never a code change.
+//
+// Slice 1 reads this for the selection only (controller/lookoutPlan.ts, the
+// `lookout-run` dry run); the model run, `afterSync` and the umtool page come in
+// later slices and read the same fields.
+
+import type { FieldDocs } from "./fieldDocs";
+
+export type LookoutItem = {
+ id: string;
+ label: string;
+ channels: string[];
+ days: number;
+ prompt: string;
+ maxVideos: number;
+ minSeconds: number;
+ timeZone: string;
+ siteOrigin: string;
+};
+
+export type LookoutsSettings = {
+ enabled: boolean;
+ afterSync: boolean;
+ items: LookoutItem[];
+};
+
+export const DEFAULT_LOOKOUTS_SETTINGS: LookoutsSettings = {
+ enabled: false,
+ afterSync: false,
+ items: [],
+};
+
+export const LOOKOUT_DEFAULT_DAYS = 7;
+export const LOOKOUT_MAX_DAYS = 60;
+export const LOOKOUT_DEFAULT_MAX_VIDEOS = 40;
+export const LOOKOUT_MAX_MAX_VIDEOS = 500;
+export const LOOKOUT_DEFAULT_MIN_SECONDS = 90;
+export const LOOKOUT_MAX_MIN_SECONDS = 3600;
+export const LOOKOUT_MAX_PROMPT_CHARS = 4000;
+
+// A lookout id is a path segment (`transcripts/.lookouts/<id>/`), so it is a
+// lowercase slug, nothing else.
+export const LOOKOUT_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
+// A channel slug as the channels tree names it (the citations' segment rule).
+const CHANNEL_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
+
+export const LOOKOUTS_SETTINGS_FIELD_DOCS: FieldDocs<LookoutsSettings> = {
+ enabled:
+ "The lookouts' master switch. Off: no lookout runs, by hand or after a sync; a dry run " +
+ "(`pnpm ops lookout-run --json '{\"id\":\"…\",\"dryRun\":true}'`) still lists what a lookout would read, " +
+ "and writes nothing. Default false.",
+ afterSync:
+ "Run each lookout after a sync of one of its channels finishes — at most once a day per lookout, never while " +
+ "render mode holds the machine. Not acted on before the after-sync slice lands. Default false.",
+ items:
+ "The saved lookouts, one entry each (`lookouts.items[]` below). The list is replaced whole by a settings " +
+ "patch. Default [] — no lookout.",
+};
+
+export const LOOKOUT_ITEM_FIELD_DOCS: FieldDocs<LookoutItem> = {
+ id:
+ "The lookout's id: a lowercase slug (`a-z`, `0-9`, `-`, at most 64), the name its runs and verdicts are kept " +
+ "under (`transcripts/.lookouts/<id>/`). Omitted: made from `label`. An entry with neither is dropped, and so " +
+ "is a second entry with an id already used.",
+ label: "What the lookout is called on its page. Omitted: the id.",
+ channels:
+ "The channel slugs it reads (`transcripts/channels/<slug>/`). A local media library channel, or a slug this " +
+ "archive does not hold (a channel only on a remote site), is refused by name when the lookout runs.",
+ days:
+ "How many days back it reads, today included, by AIR date in `timeZone` (`release_timestamp`, else " +
+ "`timestamp`, from the video's metadata — not yt-dlp's UTC `upload_date`). Clamped to [1, 60]; default 7.",
+ prompt:
+ "What the operator wants from the ideas, added to the grouping step only — the per-video reading is the same " +
+ "for every lookout. At most 4000 characters; default \"\".",
+ maxVideos:
+ "The most recordings one run reads, after duplicate uploads and stream cut-downs are folded in: the longest " +
+ "first, and every one left out listed as skipped for the cap. Clamped to [1, 500]; default 40.",
+ minSeconds:
+ "Videos shorter than this are not read (and are counted as skipped). Clamped to [0, 3600]; default 90.",
+ timeZone:
+ "The IANA time zone its days are counted in (\"America/New_York\"). \"\" = the machine's. An unknown zone is " +
+ "dropped to \"\". Default \"\".",
+ siteOrigin:
+ "The public site its links are built on (\"https://example.pages.dev\"), when the channels are published; " +
+ "\"\" = each video's source URL with its start second. Default \"\".",
+};
+
+function clampInt(value: unknown, fallback: number, min: number, max: number): number {
+ const n = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN;
+ if (!Number.isFinite(n)) return fallback;
+ return Math.min(max, Math.max(min, Math.round(n)));
+}
+
+/** Whether `tz` is an IANA zone this runtime knows. "" is not a zone (it means the machine's). */
+export function isKnownTimeZone(tz: string): boolean {
+ if (!tz) return false;
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone: tz });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** A lowercase slug made from free text: "My Lookout!" → "my-lookout". */
+export function lookoutIdFrom(text: string): string {
+ return text
+ .normalize("NFKD")
+ .replace(/[̀-ͯ]/g, "")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 64)
+ .replace(/-+$/, "");
+}
+
+function siteOriginOf(value: unknown): string {
+ if (typeof value !== "string" || !value.trim()) return "";
+ try {
+ const u = new URL(value.trim());
+ if (u.protocol !== "https:" && u.protocol !== "http:") return "";
+ return u.origin;
+ } catch {
+ return "";
+ }
+}
+
+/** One entry, coerced; null when it has no usable id. */
+export function sanitizeLookoutItem(value: unknown): LookoutItem | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const r = value as Record<string, unknown>;
+ const rawId = typeof r.id === "string" ? r.id.trim() : "";
+ const rawLabel = typeof r.label === "string" ? r.label.trim() : "";
+ const id = LOOKOUT_ID_RE.test(rawId) ? rawId : lookoutIdFrom(rawId || rawLabel);
+ if (!LOOKOUT_ID_RE.test(id)) return null;
+ const channels: string[] = [];
+ if (Array.isArray(r.channels)) {
+ for (const c of r.channels) {
+ if (typeof c !== "string") continue;
+ const slug = c.trim();
+ if (slug && slug !== ".." && CHANNEL_SLUG_RE.test(slug) && !channels.includes(slug)) channels.push(slug);
+ }
+ }
+ const tz = typeof r.timeZone === "string" ? r.timeZone.trim() : "";
+ const prompt = typeof r.prompt === "string" ? r.prompt.trim().slice(0, LOOKOUT_MAX_PROMPT_CHARS) : "";
+ return {
+ id,
+ label: rawLabel || id,
+ channels,
+ days: clampInt(r.days, LOOKOUT_DEFAULT_DAYS, 1, LOOKOUT_MAX_DAYS),
+ prompt,
+ maxVideos: clampInt(r.maxVideos, LOOKOUT_DEFAULT_MAX_VIDEOS, 1, LOOKOUT_MAX_MAX_VIDEOS),
+ minSeconds: clampInt(r.minSeconds, LOOKOUT_DEFAULT_MIN_SECONDS, 0, LOOKOUT_MAX_MIN_SECONDS),
+ timeZone: isKnownTimeZone(tz) ? tz : "",
+ siteOrigin: siteOriginOf(r.siteOrigin),
+ };
+}
+
+export function sanitizeLookouts(value: unknown): LookoutsSettings {
+ const r = (value && typeof value === "object" && !Array.isArray(value) ? value : {}) as Record<string, unknown>;
+ const items: LookoutItem[] = [];
+ if (Array.isArray(r.items)) {
+ for (const raw of r.items) {
+ const item = sanitizeLookoutItem(raw);
+ if (item && !items.some((i) => i.id === item.id)) items.push(item);
+ }
+ }
+ return { enabled: r.enabled === true, afterSync: r.afterSync === true, items };
+}
+
+/** The saved lookout with this id, or null. */
+export function lookoutById(settings: LookoutsSettings, id: string): LookoutItem | null {
+ return settings.items.find((i) => i.id === id) ?? null;
+}
diff --git a/common/lib/lookoutStore.test.ts b/common/lib/lookoutStore.test.ts
@@ -0,0 +1,167 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, readdir, rm, writeFile, mkdir } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import {
+ LookoutStoreError,
+ ideaKey,
+ listLookoutRunIds,
+ lookoutReadout,
+ lookoutRunFile,
+ lookoutVerdictsFile,
+ lookoutsRoot,
+ measuredSecondsPerCall,
+ newLookoutRunId,
+ readLookoutRun,
+ readLookoutVerdicts,
+ sanitizeLookoutVerdicts,
+ setLookoutVerdict,
+ writeLookoutRun,
+ type LookoutIdea,
+ type LookoutRun,
+} from "./lookoutStore";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/lookoutStore.test.ts
+
+async function corpus() {
+ const transcriptsDir = await mkdtemp(path.join(os.tmpdir(), "lookout-store-"));
+ return { transcriptsDir };
+}
+
+const M = (channel: string, video: string, start: number) => ({ channel, video, start });
+
+test("an idea's key is its story: order-free, 5-second grain, changed by a moment added", () => {
+ const a = ideaKey([M("example-news", "v1", 100), M("example-live", "v2", 2000)]);
+ assert.match(a, /^[0-9a-f]{16}$/);
+ assert.equal(ideaKey([M("example-live", "v2", 2001), M("example-news", "v1", 99)]), a);
+ assert.notEqual(ideaKey([M("example-news", "v1", 100), M("example-live", "v2", 2010)]), a);
+ assert.notEqual(ideaKey([M("example-news", "v1", 100), M("example-live", "v2", 2000), M("example-news", "v3", 5)]), a);
+});
+
+test("the store is a dot path under the corpus, and ids are checked before any path is made", async () => {
+ const p = await corpus();
+ try {
+ assert.equal(lookoutsRoot(p), path.join(p.transcriptsDir, ".lookouts"));
+ assert.equal(lookoutVerdictsFile(p, "weekly"), path.join(p.transcriptsDir, ".lookouts", "weekly", "verdicts.json"));
+ assert.throws(() => lookoutVerdictsFile(p, "../escape"), LookoutStoreError);
+ assert.throws(() => lookoutRunFile(p, "weekly", "../x"), LookoutStoreError);
+ assert.match(newLookoutRunId(new Date("2026-11-11T17:45:00.123Z")), /^20261111T174500Z-[0-9a-f]{4}$/);
+ } finally {
+ await rm(p.transcriptsDir, { recursive: true, force: true });
+ }
+});
+
+test("a verdict is set atomically, keeps the note it had, and two at once both land", async () => {
+ const p = await corpus();
+ try {
+ const k1 = ideaKey([M("example-news", "v1", 10), M("example-news", "v2", 20)]);
+ const k2 = ideaKey([M("example-news", "v3", 10), M("example-news", "v4", 20)]);
+ const now = new Date("2026-11-11T12:00:00Z");
+ await setLookoutVerdict(p, "weekly", { key: k1, verdict: "maybe", note: " check the date ", now });
+ const made = await setLookoutVerdict(p, "weekly", { key: k1, verdict: "make", project: "shorts-2026-11/x", now });
+ assert.deepEqual(made, { verdict: "make", at: now.toISOString(), note: "check the date", project: "shorts-2026-11/x" });
+ await Promise.all([
+ setLookoutVerdict(p, "weekly", { key: k2, verdict: "no", now }),
+ setLookoutVerdict(p, "weekly", { key: k1, verdict: "make", note: "", now }),
+ ]);
+ const v = await readLookoutVerdicts(p, "weekly");
+ assert.equal(v.ideas[k2]?.verdict, "no");
+ assert.equal(v.ideas[k1]?.note, undefined, "an empty note clears it");
+ assert.equal(v.ideas[k1]?.project, "shorts-2026-11/x");
+ // No temp file left beside it.
+ assert.deepEqual(await readdir(path.dirname(lookoutVerdictsFile(p, "weekly"))), ["verdicts.json"]);
+ await assert.rejects(setLookoutVerdict(p, "weekly", { key: "nope", verdict: "make" }), LookoutStoreError);
+ await assert.rejects(
+ setLookoutVerdict(p, "weekly", { key: k1, verdict: "yes" as never }),
+ LookoutStoreError,
+ );
+ } finally {
+ await rm(p.transcriptsDir, { recursive: true, force: true });
+ }
+});
+
+test("a hand-damaged verdicts file reads as what is valid in it", async () => {
+ const k = ideaKey([M("a", "b", 0)]);
+ assert.deepEqual(
+ sanitizeLookoutVerdicts({ ideas: { [k]: { verdict: "make", at: "x" }, bad: { verdict: "make", at: "x" }, [k.replace(/^./, "f")]: { verdict: "meh", at: "x" } } }),
+ { version: 1, ideas: { [k]: { verdict: "make", at: "x" } } },
+ );
+ const p = await corpus();
+ try {
+ await mkdir(path.dirname(lookoutVerdictsFile(p, "weekly")), { recursive: true });
+ await writeFile(lookoutVerdictsFile(p, "weekly"), "{ not json");
+ assert.deepEqual(await readLookoutVerdicts(p, "weekly"), { version: 1, ideas: {} });
+ // ...and is never written over as if it were empty.
+ await assert.rejects(setLookoutVerdict(p, "weekly", { key: k, verdict: "make" }), /unparseable.*not written/);
+ assert.equal(await readFile(lookoutVerdictsFile(p, "weekly"), "utf8"), "{ not json");
+ } finally {
+ await rm(p.transcriptsDir, { recursive: true, force: true });
+ }
+});
+
+function idea(key: string): LookoutIdea {
+ return {
+ id: key.slice(0, 6),
+ key,
+ workingTitle: "t",
+ angle: "a",
+ whyNow: "w",
+ kind: "reversal",
+ estimatedLengthSec: 60,
+ confidence: "high",
+ confidenceWhy: "c",
+ moments: [],
+ caveats: [],
+ sensitive: false,
+ };
+}
+
+function run(runId: string, ideas: LookoutIdea[], calls = 0, seconds = 0): LookoutRun {
+ return {
+ version: 1,
+ lookoutId: "weekly",
+ runId,
+ startedAt: "2026-11-11T12:00:00.000Z",
+ endedAt: "2026-11-11T12:10:00.000Z",
+ status: "done",
+ window: { from: "2026-11-05", to: "2026-11-11", days: 7, timeZone: "UTC" },
+ model: "local-model",
+ calls,
+ seconds,
+ selection: null,
+ ideas,
+ };
+}
+
+test("runs: listed newest first, the latest summarised, unruled ideas counted, seconds per call measured", async () => {
+ const p = await corpus();
+ try {
+ assert.deepEqual(await lookoutReadout(p, "weekly"), {
+ lastRun: null,
+ runs: 0,
+ unruled: 0,
+ verdicts: { make: 0, maybe: 0, no: 0 },
+ });
+ assert.equal(await measuredSecondsPerCall(p, "weekly"), null);
+ const k1 = ideaKey([M("a", "b", 0), M("a", "c", 0)]);
+ const k2 = ideaKey([M("a", "d", 0), M("a", "e", 0)]);
+ await writeLookoutRun(p, run("20261110T120000Z-aaaa", [idea(k1)], 100, 400));
+ await writeLookoutRun(p, run("20261111T120000Z-bbbb", [idea(k1), idea(k2)], 50, 100));
+ await setLookoutVerdict(p, "weekly", { key: k1, verdict: "no" });
+ assert.deepEqual(await listLookoutRunIds(p, "weekly"), ["20261111T120000Z-bbbb", "20261110T120000Z-aaaa"]);
+ const r = await lookoutReadout(p, "weekly");
+ assert.equal(r.runs, 2);
+ assert.equal(r.lastRun?.runId, "20261111T120000Z-bbbb");
+ assert.equal(r.lastRun?.ideas, 2);
+ assert.equal(r.unruled, 1, "the story ruled in an earlier run keeps its verdict");
+ assert.deepEqual(r.verdicts, { make: 0, maybe: 0, no: 1 });
+ assert.deepEqual(await measuredSecondsPerCall(p, "weekly"), { secondsPerCall: 500 / 150, runs: 2, calls: 150 });
+ assert.equal(await readLookoutRun(p, "weekly", "20261109T120000Z-cccc"), null);
+ const text = await readFile(lookoutRunFile(p, "weekly", "20261111T120000Z-bbbb"), "utf8");
+ assert.equal(JSON.parse(text).ideas.length, 2);
+ } finally {
+ await rm(p.transcriptsDir, { recursive: true, force: true });
+ }
+});
diff --git a/common/lib/lookoutStore.ts b/common/lib/lookoutStore.ts
@@ -0,0 +1,371 @@
+// THE LOOKOUT STORE — a lookout's runs, ideas and verdicts on disk, and the one
+// writer of each (lane/lookout). SERVER-ONLY (node:fs).
+//
+// transcripts/.lookouts/<lookoutId>/runs/<runId>.json one run: window, selection, calls, ideas
+// transcripts/.lookouts/<lookoutId>/runs/<runId>.trace.jsonl its trace (slice 2)
+// transcripts/.lookouts/<lookoutId>/verdicts.json the operator's Make / Maybe / No per idea
+//
+// A DOT PATH, like the corpus root's other runtime state (.x-runs, .jobs,
+// .speakers-run.json): it is never a channel, a site or a report, so nothing
+// that composes, indexes, exports or serves the corpus walks into it, and the
+// corpus repo's own .gitignore question does not arise for a name nobody
+// enumerates. Nothing here is published (the lane's rule): a run's ideas carry
+// quotes from transcripts and the operator's notes on them.
+//
+// ONE WRITER PER FILE, atomic (jsonFile-server), in the manner of
+// curatedTagsStore: a verdict is a read-modify-write of the whole
+// verdicts.json under the file's lock, so two marks never interleave. A run
+// file is written whole by the job that made it and never edited after.
+//
+// A VERDICT IS KEYED BY THE IDEA'S STORY, not by the run: `ideaKey` hashes the
+// idea's moments (channel, video, start rounded to 5 s), so the same story
+// found by a later run keeps the verdict it was given.
+
+import { createHash, randomBytes } from "node:crypto";
+import { readdir } from "node:fs/promises";
+import path from "node:path";
+import type { Paths } from "./paths";
+import { LOOKOUT_ID_RE } from "./lookoutSettings";
+import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server";
+
+export const LOOKOUTS_DIRNAME = ".lookouts";
+export const LOOKOUT_VERDICTS_FILENAME = "verdicts.json";
+export const LOOKOUT_STORE_VERSION = 1;
+
+// `20261111T174500Z-1a2b`: sorts by time, safe as a file name.
+export const LOOKOUT_RUN_ID_RE = /^\d{8}T\d{6}Z-[0-9a-f]{4}$/;
+
+export class LookoutStoreError extends Error {}
+
+function assertLookoutId(id: string): void {
+ if (!LOOKOUT_ID_RE.test(id)) throw new LookoutStoreError(`"${id}" is not a lookout id (a lowercase slug)`);
+}
+
+function assertRunId(runId: string): void {
+ if (!LOOKOUT_RUN_ID_RE.test(runId)) throw new LookoutStoreError(`"${runId}" is not a lookout run id`);
+}
+
+export function lookoutsRoot(paths: Pick<Paths, "transcriptsDir">): string {
+ return path.join(paths.transcriptsDir, LOOKOUTS_DIRNAME);
+}
+
+export function lookoutDir(paths: Pick<Paths, "transcriptsDir">, id: string): string {
+ assertLookoutId(id);
+ return path.join(lookoutsRoot(paths), id);
+}
+
+export function lookoutRunFile(paths: Pick<Paths, "transcriptsDir">, id: string, runId: string): string {
+ assertRunId(runId);
+ return path.join(lookoutDir(paths, id), "runs", `${runId}.json`);
+}
+
+export function lookoutTraceFile(paths: Pick<Paths, "transcriptsDir">, id: string, runId: string): string {
+ assertRunId(runId);
+ return path.join(lookoutDir(paths, id), "runs", `${runId}.trace.jsonl`);
+}
+
+export function lookoutVerdictsFile(paths: Pick<Paths, "transcriptsDir">, id: string): string {
+ return path.join(lookoutDir(paths, id), LOOKOUT_VERDICTS_FILENAME);
+}
+
+export function newLookoutRunId(now: Date = new Date()): string {
+ const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
+ return `${stamp}-${randomBytes(2).toString("hex")}`;
+}
+
+// ─── Ideas ───
+
+/** One dated, verbatim moment of an idea, located by code in its video's cues. */
+export type LookoutMoment = {
+ channel: string;
+ /** The video's directory under `channels/<channel>/data/`. */
+ video: string;
+ /** Its air date, YYYY-MM-DD in the lookout's zone. */
+ date: string;
+ start: number;
+ end: number;
+ quote: string;
+ link?: string;
+ title?: string;
+};
+
+export type LookoutVerdictValue = "make" | "maybe" | "no";
+
+/** An idea as a run stores it: the pilot's shape plus `key` and `sensitive`. */
+export type LookoutIdea = {
+ id: string;
+ key: string;
+ workingTitle: string;
+ angle: string;
+ whyNow: string;
+ kind: string;
+ estimatedLengthSec: number;
+ confidence: "high" | "medium" | "low";
+ confidenceWhy: string;
+ moments: LookoutMoment[];
+ caveats: string[];
+ sensitive: boolean;
+};
+
+/** Seconds rounded to the nearest 5, the grain a story's key is cut at. */
+const grain = (s: number) => Math.round(s / 5) * 5;
+
+/**
+ * The idea's story key: a hash of its sorted moments (channel, video, start
+ * rounded to 5 s). The same moments in any order give the same key; a moment
+ * nudged by a second or two gives the same key; a moment added or removed
+ * gives another.
+ */
+export function ideaKey(moments: readonly Pick<LookoutMoment, "channel" | "video" | "start">[]): string {
+ const parts = [...new Set(moments.map((m) => `${m.channel}/${m.video}@${grain(m.start)}`))].sort();
+ return createHash("sha1").update(parts.join("\n")).digest("hex").slice(0, 16);
+}
+
+// ─── Runs ───
+
+export type LookoutRunStatus = "done" | "partial" | "failed";
+
+/**
+ * A run as stored. Slice 1 defines the shape and reads it; the job that writes
+ * one (and fills `selection`, `calls`, `ideas`) is slice 2's.
+ */
+export type LookoutRun = {
+ version: number;
+ lookoutId: string;
+ runId: string;
+ startedAt: string;
+ endedAt: string | null;
+ status: LookoutRunStatus;
+ window: { from: string; to: string; days: number; timeZone: string };
+ model: string | null;
+ /** Model calls made. */
+ calls: number;
+ /** Wall seconds the model calls took, summed. */
+ seconds: number;
+ /** The selection as the dry run lists it (controller/lookoutPlan.ts LookoutPlan), read and skipped and why. */
+ selection: unknown;
+ ideas: LookoutIdea[];
+ /** What was dropped and why (an unlocatable quote, an invented id, a one-moment idea), counted. */
+ dropped?: Record<string, number>;
+ note?: string;
+};
+
+export type LookoutRunSummary = {
+ runId: string;
+ startedAt: string;
+ endedAt: string | null;
+ status: LookoutRunStatus;
+ window: LookoutRun["window"];
+ model: string | null;
+ calls: number;
+ seconds: number;
+ ideas: number;
+};
+
+function isObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === "object" && v !== null && !Array.isArray(v);
+}
+
+/** Write a run whole (its job is the only writer, once). */
+export async function writeLookoutRun(paths: Pick<Paths, "transcriptsDir">, run: LookoutRun): Promise<string> {
+ const file = lookoutRunFile(paths, run.lookoutId, run.runId);
+ await writeJsonAtomic(file, run, { mkdir: true });
+ return file;
+}
+
+/** One run, or null when it is absent or not a run. */
+export async function readLookoutRun(
+ paths: Pick<Paths, "transcriptsDir">,
+ id: string,
+ runId: string,
+): Promise<LookoutRun | null> {
+ const read = await readJsonFile(lookoutRunFile(paths, id, runId));
+ if (!read.ok || !isObject(read.value)) return null;
+ const v = read.value;
+ if (v.lookoutId !== id || v.runId !== runId || !Array.isArray(v.ideas)) return null;
+ return v as unknown as LookoutRun;
+}
+
+/** The lookout's run ids, newest first. */
+export async function listLookoutRunIds(paths: Pick<Paths, "transcriptsDir">, id: string): Promise<string[]> {
+ let names: string[];
+ try {
+ names = await readdir(path.join(lookoutDir(paths, id), "runs"));
+ } catch {
+ return [];
+ }
+ return names
+ .filter((n) => n.endsWith(".json"))
+ .map((n) => n.slice(0, -".json".length))
+ .filter((n) => LOOKOUT_RUN_ID_RE.test(n))
+ .sort()
+ .reverse();
+}
+
+export function summarizeLookoutRun(run: LookoutRun): LookoutRunSummary {
+ return {
+ runId: run.runId,
+ startedAt: run.startedAt,
+ endedAt: run.endedAt,
+ status: run.status,
+ window: run.window,
+ model: run.model,
+ calls: run.calls,
+ seconds: run.seconds,
+ ideas: run.ideas.length,
+ };
+}
+
+/**
+ * Seconds per model call measured over the lookout's latest runs that made
+ * calls (at most `recent`), or null when none has. What a dry run's estimate
+ * is priced from.
+ */
+export async function measuredSecondsPerCall(
+ paths: Pick<Paths, "transcriptsDir">,
+ id: string,
+ recent = 3,
+): Promise<{ secondsPerCall: number; runs: number; calls: number } | null> {
+ let calls = 0;
+ let seconds = 0;
+ let runs = 0;
+ for (const runId of await listLookoutRunIds(paths, id)) {
+ if (runs >= recent) break;
+ const run = await readLookoutRun(paths, id, runId);
+ if (!run || !(run.calls > 0) || !(run.seconds > 0)) continue;
+ calls += run.calls;
+ seconds += run.seconds;
+ runs++;
+ }
+ return calls > 0 ? { secondsPerCall: seconds / calls, runs, calls } : null;
+}
+
+// ─── Verdicts ───
+
+export type LookoutVerdict = {
+ verdict: LookoutVerdictValue;
+ /** ISO 8601, when it was given. */
+ at: string;
+ note?: string;
+ /** The Shorts project "Make" opened, when it did. */
+ project?: string;
+};
+
+export type LookoutVerdicts = {
+ version: number;
+ /** Keyed by the idea's story key (`ideaKey`). */
+ ideas: Record<string, LookoutVerdict>;
+};
+
+const IDEA_KEY_RE = /^[0-9a-f]{16}$/;
+const VERDICTS: readonly LookoutVerdictValue[] = ["make", "maybe", "no"];
+
+export function isLookoutVerdict(v: unknown): v is LookoutVerdictValue {
+ return typeof v === "string" && (VERDICTS as readonly string[]).includes(v);
+}
+
+export function isIdeaKey(v: unknown): v is string {
+ return typeof v === "string" && IDEA_KEY_RE.test(v);
+}
+
+export function emptyLookoutVerdicts(): LookoutVerdicts {
+ return { version: LOOKOUT_STORE_VERSION, ideas: {} };
+}
+
+/** A verdicts file coerced: an ill-typed entry is dropped, never thrown on. */
+export function sanitizeLookoutVerdicts(value: unknown): LookoutVerdicts {
+ const out = emptyLookoutVerdicts();
+ const ideas = isObject(value) ? value.ideas : null;
+ if (!isObject(ideas)) return out;
+ for (const [key, raw] of Object.entries(ideas)) {
+ if (!isIdeaKey(key) || !isObject(raw) || !isLookoutVerdict(raw.verdict) || typeof raw.at !== "string") continue;
+ const v: LookoutVerdict = { verdict: raw.verdict, at: raw.at };
+ if (typeof raw.note === "string" && raw.note.trim()) v.note = raw.note.trim();
+ if (typeof raw.project === "string" && raw.project.trim()) v.project = raw.project.trim();
+ out.ideas[key] = v;
+ }
+ return out;
+}
+
+export async function readLookoutVerdicts(
+ paths: Pick<Paths, "transcriptsDir">,
+ id: string,
+): Promise<LookoutVerdicts> {
+ const read = await readJsonFile(lookoutVerdictsFile(paths, id));
+ return read.ok ? sanitizeLookoutVerdicts(read.value) : emptyLookoutVerdicts();
+}
+
+export type SetVerdictInput = {
+ key: string;
+ verdict: LookoutVerdictValue;
+ note?: string;
+ project?: string;
+ now?: Date;
+};
+
+/**
+ * THE writer of verdicts.json: one idea's verdict set (replacing the one it
+ * had), under the file's lock, written atomically. A note or project not sent
+ * is kept from the verdict before, so "Make" recording its project does not
+ * erase the operator's note. Refused when verdicts.json is there and is not
+ * readable JSON — it is never overwritten as if it were empty.
+ */
+export async function setLookoutVerdict(
+ paths: Pick<Paths, "transcriptsDir">,
+ id: string,
+ input: SetVerdictInput,
+): Promise<LookoutVerdict> {
+ if (!isIdeaKey(input.key)) throw new LookoutStoreError(`"${input.key}" is not an idea key`);
+ if (!isLookoutVerdict(input.verdict)) throw new LookoutStoreError(`verdict is one of ${VERDICTS.join(", ")}`);
+ const file = lookoutVerdictsFile(paths, id);
+ return withJsonFileLock(file, async () => {
+ // A file that is there and cannot be read is NOT an empty one: writing over
+ // it would drop every verdict it holds for the one being set.
+ const read = await readJsonFile(file);
+ if (!read.ok && read.reason !== "absent") {
+ throw new LookoutStoreError(
+ `${file} is ${read.reason} — the verdict was not written; mend the file or move it aside first`,
+ );
+ }
+ const current = read.ok ? sanitizeLookoutVerdicts(read.value) : emptyLookoutVerdicts();
+ const before = current.ideas[input.key];
+ const v: LookoutVerdict = { verdict: input.verdict, at: (input.now ?? new Date()).toISOString() };
+ const note = input.note !== undefined ? input.note.trim() : before?.note;
+ if (note) v.note = note;
+ const project = input.project !== undefined ? input.project.trim() : before?.project;
+ if (project) v.project = project;
+ current.ideas[input.key] = v;
+ await writeJsonAtomic(file, current, { mkdir: true });
+ return v;
+ });
+}
+
+// ─── The readout (`pnpm ops get lookouts`) ───
+
+export type LookoutReadout = {
+ lastRun: LookoutRunSummary | null;
+ runs: number;
+ /** Ideas in the latest run with no verdict yet. */
+ unruled: number;
+ verdicts: Record<LookoutVerdictValue, number>;
+};
+
+/** What the store holds for one lookout: its runs, the latest one, and how many of its ideas wait for a verdict. */
+export async function lookoutReadout(paths: Pick<Paths, "transcriptsDir">, id: string): Promise<LookoutReadout> {
+ const runIds = await listLookoutRunIds(paths, id);
+ const verdicts = await readLookoutVerdicts(paths, id);
+ const counts: Record<LookoutVerdictValue, number> = { make: 0, maybe: 0, no: 0 };
+ for (const v of Object.values(verdicts.ideas)) counts[v.verdict]++;
+ let latest: LookoutRun | null = null;
+ for (const runId of runIds) {
+ latest = await readLookoutRun(paths, id, runId);
+ if (latest) break;
+ }
+ const unruled = latest ? latest.ideas.filter((i) => !verdicts.ideas[i.key]).length : 0;
+ return {
+ lastRun: latest ? summarizeLookoutRun(latest) : null,
+ runs: runIds.length,
+ unruled,
+ verdicts: counts,
+ };
+}
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -15,6 +15,8 @@ import {
ARCHIVES_SETTINGS_FIELD_DOCS,
CLIPS_SETTINGS_FIELD_DOCS,
JOBS_SETTINGS_FIELD_DOCS,
+ LOOKOUTS_SETTINGS_FIELD_DOCS,
+ LOOKOUT_ITEM_FIELD_DOCS,
SERVICE_COOKIES_SETTINGS_FIELD_DOCS,
VOICE_CONVERT_SETTINGS_FIELD_DOCS,
VOICE_ENHANCE_SETTINGS_FIELD_DOCS,
@@ -360,6 +362,14 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
defaults: fromObject(d.serviceCookies),
},
],
+ lookouts: [
+ {
+ path: "lookouts",
+ docs: LOOKOUTS_SETTINGS_FIELD_DOCS,
+ defaults: fromObject(d.lookouts),
+ },
+ { path: "lookouts.items[]", docs: LOOKOUT_ITEM_FIELD_DOCS },
+ ],
};
}
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -37,6 +37,7 @@ import type { RemoteArchive } from "./remoteArchives";
import type { ClipsSettings } from "./clipSettings";
import type { JobsSettings } from "./jobsSettings";
import type { ServiceCookiesSettings } from "./serviceCookieSettings";
+import type { LookoutsSettings } from "./lookoutSettings";
import type { VoiceSettings } from "./voiceSettings";
import type { GenerationSettings } from "./generationSettings";
import type {
@@ -135,6 +136,8 @@ type PreSchemaSiteSettings = {
jobs: JobsSettings;
// The cookie refresh alerts' proactive timer (2026-10-31).
serviceCookies: ServiceCookiesSettings;
+ // Saved lookouts (lane/lookout).
+ lookouts: LookoutsSettings;
};
// Bracketed so the conditional does not distribute (see commit 8c43231).
@@ -191,6 +194,7 @@ test("SiteSettings keeps its 47 fields, in file order", () => {
"clips",
"jobs",
"serviceCookies",
+ "lookouts",
]);
// A parsed object carries every key, in that order — writeSettings writes
// exactly this, so the order is the on-disk order.
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -85,6 +85,7 @@ import { sanitizeArchives, type ArchivesSettings } from "./archives/settings";
import { sanitizeRemoteArchives, type RemoteArchive } from "./remoteArchives";
import { sanitizeClips, type ClipsSettings } from "./clipSettings";
import { sanitizeJobs, type JobsSettings } from "./jobsSettings";
+import { sanitizeLookouts, type LookoutsSettings } from "./lookoutSettings";
import { sanitizeServiceCookies, type ServiceCookiesSettings } from "./serviceCookieSettings";
import { sanitizeGeneration, type GenerationSettings } from "./generationSettings";
export {
@@ -113,6 +114,7 @@ export { ARCHIVES_SETTINGS_FIELD_DOCS, type ArchivesSettings } from "./archives/
export { REMOTE_ARCHIVE_FIELD_DOCS, type RemoteArchive } from "./remoteArchives";
export { CLIPS_SETTINGS_FIELD_DOCS, type ClipsSettings } from "./clipSettings";
export { JOBS_SETTINGS_FIELD_DOCS, type JobsSettings } from "./jobsSettings";
+export { LOOKOUTS_SETTINGS_FIELD_DOCS, LOOKOUT_ITEM_FIELD_DOCS, type LookoutsSettings, type LookoutItem } from "./lookoutSettings";
export { SERVICE_COOKIES_SETTINGS_FIELD_DOCS, type ServiceCookiesSettings } from "./serviceCookieSettings";
import {
DEFAULT_COOKIE_MODE,
@@ -2076,6 +2078,9 @@ export const siteSettingsSchema = z.object({
serviceCookies: settingsField((v): ServiceCookiesSettings => sanitizeServiceCookies(v)).describe(
"The cookie refresh alerts' PROACTIVE timer (plans/cookie-refresh-alerts.md): how often the editor rechecks raised alerts, probes Rumble's clearance with no alert up, and re-reads X's cookie jar age, by itself — so the dashboard banner goes up before a sync or a download fails. See ServiceCookiesSettings and common/controller/serviceCookieTimer.ts.",
),
+ lookouts: settingsField((v): LookoutsSettings => sanitizeLookouts(v)).describe(
+ "Saved lookouts (lane/lookout): each names channels, a number of days back and an optional prompt, and a run reads those channels' recent transcripts — by air date, duplicate uploads and stream cut-downs folded in — and answers with video ideas. OFF and empty by default; nothing a lookout writes is published. `pnpm ops get lookouts` is the readout, `pnpm ops lookout-run --json '{\"id\":\"…\",\"dryRun\":true}'` lists what one would read. See LookoutsSettings and common/lib/lookoutSettings.ts.",
+ ),
});
export type SiteSettings = z.infer<typeof siteSettingsSchema>;
diff --git a/common/lib/voiceApps.ts b/common/lib/voiceApps.ts
@@ -53,8 +53,19 @@ export type VoiceSetup =
importName: string;
code: { repo: string; commit: string };
files: readonly VoiceModelFile[];
+ // Files the engine runs without, in named groups: fetched only when
+ // setup is asked for the group (`--with <id>`), never counted against
+ // "installed" — an install made before a group existed keeps working.
+ optional?: readonly VoiceFileGroup[];
};
+export type VoiceFileGroup = {
+ id: string;
+ // What the group is for, as setup says it.
+ label: string;
+ files: readonly VoiceModelFile[];
+};
+
// A downloaded file, verified by size and sha256 like a TTS model file. `name`
// may hold a subdirectory (`whisper-small/model.safetensors`).
export type VoiceModelFile = TtsModelFile & { executable?: boolean };
@@ -63,6 +74,22 @@ export type VoiceParamSpec =
| { kind: "number"; min: number; max: number; default: number; doc: string }
| { kind: "boolean"; default: boolean; doc: string };
+// THE PITCH A CONVERSION LANDS ON (operator, 11 Nov: both converters threw the
+// read's intonation away — inputs with a median f0 of 128 to 237 Hz all came
+// out at 196-199 Hz, a 152-321 Hz range as 165-240 Hz).
+// target the stock voice's own pitch: the converter is given none of the
+// input's (every engine; what there was before).
+// source the input's f0 as it was read: raise the voice and the output
+// rises with it.
+// contour the input's f0 curve moved as a whole so its median sits on the
+// stock voice's: every rise and fall kept, the register the target's.
+// `semitones` then moves a followed curve (source, contour) up or down.
+export type VoicePitch = "target" | "source" | "contour";
+export const VOICE_PITCH_MODES: readonly VoicePitch[] = ["target", "source", "contour"];
+export const VOICE_SEMITONES_MAX = 12;
+export type VoicePitchChoice = { pitch: VoicePitch; semitones: number };
+export const DEFAULT_VOICE_PITCH: VoicePitchChoice = { pitch: "target", semitones: 0 };
+
export type VoiceBuildInput = {
input: string;
output: string;
@@ -74,6 +101,8 @@ export type VoiceBuildInput = {
// The stock target's reference clip and openvoice's embedding cache (convert).
targetRef?: string;
targetSe?: string;
+ // A followed pitch (an engine with `pitch`); absent = target.
+ pitch?: VoicePitchChoice;
bins: { ffmpegBin: string; voiceModelsDir: string };
};
@@ -93,6 +122,11 @@ export type VoiceEngine = {
// plus swapped — rnnoise 112 MB, deepfilternet 111 MB, openvoice 1625 MB,
// seed-vc 2865 MB; no GPU memory, they are CPU engines) plus a margin.
defaultEstimateMB: number;
+ // A convert engine that can FOLLOW the input's pitch (source, contour): the
+ // optional file group that mode runs on, and the memory ITS run declares
+ // (another, bigger model) — kept in settings.voice.heavyEstimateMB under
+ // `estimateKey`. An engine without it has one pitch: the target's.
+ pitch?: { group: string; estimateKey: string; defaultEstimateMB: number };
// Args to paths.voiceBin (scripts/voice.mjs).
build: (input: VoiceBuildInput) => string[];
};
@@ -232,6 +266,13 @@ const openvoice: VoiceEngine = {
],
};
+// The f0 model's run, declared to the heavy slot: its peak measured 2026-11-11
+// (RSS plus swap of the wrapper and python, sampled twice a second) — 3706 MB
+// over 6.9 s reads, 5781 MB over a 34 s one, whose first window is a full one
+// (30 s less the reference: the 44.1 kHz vocoder's activations grow with the
+// window, and no take makes a longer one) — plus a margin.
+const SEEDVC_F0_ESTIMATE_MB = 6500;
+
const SEEDVC_HF = "https://huggingface.co/Plachta/Seed-VC/resolve/257283f9f41585055e8f858fba4fd044e5caed6e";
const WHISPER_HF = "https://huggingface.co/openai/whisper-small/resolve/973afd24965f72e36ca33b3055d56a652f456b4d";
const BIGVGAN_HF = "https://huggingface.co/nvidia/bigvgan_v2_22khz_80band_256x/resolve/633ff708ed5b74903e86ff1298cf4a98e921c513";
@@ -288,6 +329,52 @@ export const SEEDVC_FILES: readonly VoiceModelFile[] = [
},
];
+// The f0-conditioned model (upstream's `inference.py --f0-condition`): a 44.1
+// kHz DiT, its 128-band BigVGAN, and RMVPE, the pitch tracker whose curve
+// conditions it. Optional (`voice setup --engine seed-vc --with f0`, 1.49 GB):
+// `pitch: source | contour` runs on these, `target` never touches them.
+const RMVPE_HF = "https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d";
+const BIGVGAN_44K_HF = "https://huggingface.co/nvidia/bigvgan_v2_44khz_128band_512x/resolve/95a9d1dcb12906c03edd938d77b9333d6ded7dfb";
+
+export const SEEDVC_F0_FILES: readonly VoiceModelFile[] = [
+ {
+ name: "DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2.pth",
+ url: `${SEEDVC_HF}/DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2.pth`,
+ bytes: 820_865_494,
+ sha256: "42aef93ffe65857c840d270252fa040f7ba04514945ec460f3ac1ac2a96de684",
+ },
+ {
+ name: "config_dit_mel_seed_uvit_whisper_base_f0_44k.yml",
+ url: `${SEEDVC_HF}/config_dit_mel_seed_uvit_whisper_base_f0_44k.yml`,
+ bytes: 2_408,
+ sha256: "ff86f343b08c2def405f075022eeb10dafba23c4eda36d151010f4ca6d7a1a0a",
+ },
+ {
+ name: "rmvpe.pt",
+ url: `${RMVPE_HF}/rmvpe.pt`,
+ bytes: 181_184_272,
+ sha256: "6d62215f4306e3ca278246188607209f09af3dc77ed4232efdd069798c4ec193",
+ },
+ {
+ name: "bigvgan-44k/bigvgan_generator.pt",
+ url: `${BIGVGAN_44K_HF}/bigvgan_generator.pt`,
+ bytes: 489_041_291,
+ sha256: "d9fe7ec6bd0b44ed9d66973d5012d8181c1570b01e5c72df51973e241dccd357",
+ },
+ {
+ name: "bigvgan-44k/config.json",
+ url: `${BIGVGAN_44K_HF}/config.json`,
+ bytes: 1_403,
+ sha256: "65b7f487bfaf15256056a75f6667ef5f640214c981922a111927873705ea4ddb",
+ },
+];
+
+export const SEEDVC_F0_GROUP: VoiceFileGroup = {
+ id: "f0",
+ label: "the f0-conditioned 44.1 kHz model, for a conversion that follows the input's pitch (pitch: source | contour)",
+ files: SEEDVC_F0_FILES,
+};
+
// Seed-VC v1, its 22 kHz speech model (Whisper-small content features, a
// diffusion transformer, BigVGAN v2): zero-shot, the stronger timbre match,
// several times slower than OpenVoice on the CPU. GPL-3.0 code, run as a
@@ -312,6 +399,7 @@ const seedVc: VoiceEngine = {
importName: "transformers",
code: { repo: "https://github.com/Plachtaa/seed-vc", commit: "51383efd921027683c89e5348211d93ff12ac2a8" },
files: SEEDVC_FILES,
+ optional: [SEEDVC_F0_GROUP],
},
params: {
steps: { kind: "number", min: 1, max: 100, default: 10, doc: "diffusion steps: each is one pass of the model over every window, so the time grows with them (upstream: 4-10 fast, 25-30 cleaner; 10 by the 2026-11-03 bake-off)" },
@@ -319,12 +407,14 @@ const seedVc: VoiceEngine = {
refSeconds: { kind: "number", min: 3, max: 25, default: 10, doc: "seconds of the reference the model is prompted with (each window is 30 s less this: less is faster)" },
},
defaultEstimateMB: 3500,
+ pitch: { group: SEEDVC_F0_GROUP.id, estimateKey: "seed-vc-f0", defaultEstimateMB: SEEDVC_F0_ESTIMATE_MB },
build: (i) => [
...common("convert", "seed-vc", i),
"--python", voiceVenvPython(i.installDir),
"--code", voiceCodeDir(i.installDir),
"--install", i.installDir,
"--target-ref", i.targetRef ?? "",
+ ...(i.pitch && i.pitch.pitch !== "target" ? ["--pitch", i.pitch.pitch, "--semitones", String(i.pitch.semitones)] : []),
],
};
@@ -355,6 +445,58 @@ export function voiceInstallDir(home: string, engine: Pick<VoiceEngine, "id">):
type Check<T> = { ok: true; value: T } | { ok: false; error: string };
/**
+ * The pitch a conversion lands on: the request's `pitch` / `semitones` over the
+ * defaults (settings.voice.convert). An engine with one pitch refuses a request
+ * for another (the defaults are not a request: they are for the engines that
+ * can); `semitones` asked of the target's own pitch is refused, since nothing
+ * is followed to move. A request that names a followed `pitch` and no
+ * `semitones` takes the DEFAULT semitones (settings.voice.convert.semitones),
+ * whichever pitch the settings name — say `"semitones": 0` for none. Pure.
+ */
+export function resolveVoicePitch(
+ engine: Pick<VoiceEngine, "id" | "label" | "pitch">,
+ given: { pitch?: unknown; semitones?: unknown },
+ defaults: VoicePitchChoice = DEFAULT_VOICE_PITCH,
+): Check<VoicePitchChoice> {
+ if (given.pitch !== undefined && !VOICE_PITCH_MODES.includes(given.pitch as VoicePitch)) {
+ return { ok: false, error: `"pitch" is one of ${VOICE_PITCH_MODES.join(", ")} (got ${JSON.stringify(given.pitch)})` };
+ }
+ if (given.semitones !== undefined) {
+ const n = given.semitones;
+ if (typeof n !== "number" || !Number.isFinite(n) || Math.abs(n) > VOICE_SEMITONES_MAX) {
+ return { ok: false, error: `"semitones" is a number from -${VOICE_SEMITONES_MAX} to ${VOICE_SEMITONES_MAX} (got ${JSON.stringify(n)})` };
+ }
+ }
+ const askedPitch = given.pitch as VoicePitch | undefined;
+ const askedSemitones = given.semitones as number | undefined;
+ if (!engine.pitch) {
+ if ((askedPitch && askedPitch !== "target") || askedSemitones) {
+ const can = Object.values(VOICE_ENGINES).filter((e) => e.pitch).map((e) => e.id);
+ return {
+ ok: false,
+ error: `${engine.label} has no pitch control — it lands every read on the target's own pitch; "pitch" and "semitones" are ${can.join(", ")}'s (engine: "${can[0]}")`,
+ };
+ }
+ return { ok: true, value: { pitch: "target", semitones: 0 } };
+ }
+ const pitch = askedPitch ?? defaults.pitch;
+ if (pitch === "target") {
+ if (askedSemitones) {
+ return { ok: false, error: `"semitones" moves a followed pitch — give "pitch": "source" or "contour" with it (pitch is "target": the stock voice's own)` };
+ }
+ return { ok: true, value: { pitch, semitones: 0 } };
+ }
+ return { ok: true, value: { pitch, semitones: askedSemitones ?? defaults.semitones } };
+}
+
+/** How a result, a take or a page says a pitch choice: "contour +2 st", "source", "" for the target's own. */
+export function describeVoicePitch(p: Partial<VoicePitchChoice> | undefined): string {
+ if (!p?.pitch || p.pitch === "target") return "";
+ const n = p.semitones ?? 0;
+ return n ? `${p.pitch} ${n > 0 ? "+" : "−"}${Math.abs(n)} st` : p.pitch;
+}
+
+/**
* An engine's knobs from a body's `params`: each key one the engine has, each
* value of its kind and in its range; the rest from the defaults. Pure.
*/
@@ -445,8 +587,8 @@ export function voiceConvertDisclosure(engine: Pick<VoiceEngine, "label">, targe
}
// A client-safe view (no functions).
-export type VoiceEngineDescriptor = { id: string; op: VoiceOp; label: string; license: string; params: Record<string, VoiceParamSpec> };
+export type VoiceEngineDescriptor = { id: string; op: VoiceOp; label: string; license: string; params: Record<string, VoiceParamSpec>; pitch: boolean };
export function listVoiceEngines(): VoiceEngineDescriptor[] {
- return Object.values(VOICE_ENGINES).map((e) => ({ id: e.id, op: e.op, label: e.label, license: e.license, params: { ...e.params } }));
+ return Object.values(VOICE_ENGINES).map((e) => ({ id: e.id, op: e.op, label: e.label, license: e.license, params: { ...e.params }, pitch: Boolean(e.pitch) }));
}
diff --git a/common/lib/voiceInstall.ts b/common/lib/voiceInstall.ts
@@ -7,18 +7,51 @@
// the pinned checkout's marker, each file at its pinned size (an executable
// one executable); setup's `--check` goes further and imports the package and
// reads the checkout's commit. Read-only: never creates anything.
+//
+// An engine's OPTIONAL file groups (seed-vc's `f0`: the model a followed pitch
+// runs on) are reported beside, never counted: `installed` is the required
+// files alone, so an install made before a group existed is still installed.
import fs from "node:fs";
import path from "node:path";
-import { voiceCodeDir, voiceInstallDir, voiceVenvPython, type VoiceEngine } from "./voiceApps";
+import { voiceCodeDir, voiceInstallDir, voiceVenvPython, type VoiceEngine, type VoiceModelFile } from "./voiceApps";
export type VoiceInstallState = {
engine: string;
dir: string;
installed: boolean;
missing: string[];
+ // Each optional group: there whole, or what of it is missing.
+ optional: VoiceGroupState[];
};
+export type VoiceGroupState = { id: string; label: string; installed: boolean; missing: string[] };
+
+function missingFiles(dir: string, files: readonly VoiceModelFile[]): string[] {
+ const missing: string[] = [];
+ for (const f of files) {
+ const p = path.join(dir, f.name);
+ let st: fs.Stats | null = null;
+ try {
+ st = fs.statSync(p);
+ } catch {
+ st = null;
+ }
+ if (!st) missing.push(f.name);
+ else if (st.size !== f.bytes) missing.push(`${f.name} (${st.size} bytes, expected ${f.bytes})`);
+ else if (f.executable && (st.mode & 0o111) === 0) missing.push(`${f.name} (not executable)`);
+ }
+ return missing;
+}
+
+/** One optional group of an engine's install, or undefined when the engine has none by that id. */
+export function voiceGroupState(engine: VoiceEngine, group: string, opts: { home: string }): VoiceGroupState | undefined {
+ const g = engine.setup.kind === "python-venv" ? engine.setup.optional?.find((x) => x.id === group) : undefined;
+ if (!g) return undefined;
+ const missing = missingFiles(voiceInstallDir(opts.home, engine), g.files);
+ return { id: g.id, label: g.label, installed: missing.length === 0, missing };
+}
+
// The file a finished checkout leaves: the commit it is at.
export const VOICE_CODE_MARKER = ".archilyzer-commit";
@@ -30,7 +63,7 @@ export function voiceInstallState(
if (setup.kind === "bundled") {
const model = path.join(opts.voiceModelsDir, "sh.rnnn");
const ok = fs.existsSync(model);
- return { engine: engine.id, dir: opts.voiceModelsDir, installed: ok, missing: ok ? [] : [`${model} (shipped in the repo)`] };
+ return { engine: engine.id, dir: opts.voiceModelsDir, installed: ok, missing: ok ? [] : [`${model} (shipped in the repo)`], optional: [] };
}
const dir = voiceInstallDir(opts.home, engine);
const missing: string[] = [];
@@ -47,17 +80,7 @@ export function voiceInstallState(
missing.push(at ? `the checkout of ${setup.code.repo} is at ${at.slice(0, 10)}, pinned ${setup.code.commit.slice(0, 10)}` : `the checkout of ${setup.code.repo} (${voiceCodeDir(dir)})`);
}
}
- for (const f of setup.files) {
- const p = path.join(dir, f.name);
- let st: fs.Stats | null = null;
- try {
- st = fs.statSync(p);
- } catch {
- st = null;
- }
- if (!st) missing.push(f.name);
- else if (st.size !== f.bytes) missing.push(`${f.name} (${st.size} bytes, expected ${f.bytes})`);
- else if (f.executable && (st.mode & 0o111) === 0) missing.push(`${f.name} (not executable)`);
- }
- return { engine: engine.id, dir, installed: missing.length === 0, missing };
+ missing.push(...missingFiles(dir, setup.files));
+ const optional = (setup.kind === "python-venv" ? setup.optional ?? [] : []).map((g) => voiceGroupState(engine, g.id, opts)!);
+ return { engine: engine.id, dir, installed: missing.length === 0, missing, optional };
}
diff --git a/common/lib/voiceSettings.test.ts b/common/lib/voiceSettings.test.ts
@@ -1,7 +1,7 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DEFAULT_VOICE_SETTINGS, resolveVoiceHome, sanitizeVoice } from "./voiceSettings";
-import { NO_CLONING, VOICE_ENGINES, listVoiceEngines, parseStockTarget, resolveVoiceParams, voiceEngineIds } from "./voiceApps";
+import { NO_CLONING, VOICE_ENGINES, describeVoicePitch, listVoiceEngines, parseStockTarget, resolveVoiceParams, voiceEngineIds } from "./voiceApps";
// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/voiceSettings.test.ts
@@ -25,7 +25,16 @@ test("settings.voice: defaults, and every field falls back rather than throws",
assert.equal(s.heavyEstimateMB["seed-vc"], 4200);
assert.equal(s.heavyEstimateMB.openvoice, 0);
assert.equal("nope" in s.heavyEstimateMB, false);
- assert.deepEqual(Object.keys(s.heavyEstimateMB).sort(), Object.keys(VOICE_ENGINES).sort());
+ // Every engine, and the f0 run of the one that can follow a pitch.
+ assert.deepEqual(Object.keys(s.heavyEstimateMB).sort(), [...Object.keys(VOICE_ENGINES), "seed-vc-f0"].sort());
+ assert.equal(s.heavyEstimateMB["seed-vc-f0"], VOICE_ENGINES["seed-vc"].pitch!.defaultEstimateMB);
+ assert.equal(sanitizeVoice({ heavyEstimateMB: { "seed-vc-f0": 5000 } }).heavyEstimateMB["seed-vc-f0"], 5000);
+ // The pitch a conversion lands on: the target's own unless said, the semitones clamped.
+ assert.deepEqual([s.convert.pitch, s.convert.semitones], ["target", 0]);
+ const p = sanitizeVoice({ convert: { pitch: "contour", semitones: 40 } }).convert;
+ assert.deepEqual([p.pitch, p.semitones], ["contour", 12]);
+ const q = sanitizeVoice({ convert: { pitch: "higher", semitones: "2" } }).convert;
+ assert.deepEqual([q.pitch, q.semitones], ["target", 0]);
const ok = sanitizeVoice({ home: "~/voice", convert: { engine: "seed-vc", target: "kokoro:bm_george" }, enhance: { engine: "rnnoise" } });
assert.equal(ok.convert.engine, "seed-vc");
assert.equal(ok.convert.target, "kokoro:bm_george");
@@ -62,7 +71,24 @@ test("the registry: two engines per op, every knob has a default in range", () =
}
assert.ok(e.defaultEstimateMB > 0, e.id);
if (e.setup.kind !== "bundled") for (const f of e.setup.files) assert.match(f.sha256, /^[0-9a-f]{64}$/, f.name);
+ // An optional group: pinned by revision, size and sha256 like the rest, and no name of the required set.
+ if (e.setup.kind === "python-venv") {
+ const required = new Set(e.setup.files.map((f) => f.name));
+ for (const g of e.setup.optional ?? []) {
+ for (const f of g.files) {
+ assert.match(f.sha256, /^[0-9a-f]{64}$/, f.name);
+ assert.match(f.url, /\/resolve\/[0-9a-f]{40}\//, f.name);
+ assert.ok(f.bytes > 0 && !required.has(f.name), f.name);
+ }
+ }
+ if (e.pitch) assert.ok(e.setup.optional?.some((g) => g.id === e.pitch!.group), e.id);
+ }
+ assert.equal(Boolean(e.pitch), e.id === "seed-vc", e.id);
}
+ assert.equal(describeVoicePitch({ pitch: "target", semitones: 0 }), "");
+ assert.equal(describeVoicePitch({ pitch: "source", semitones: 0 }), "source");
+ assert.equal(describeVoicePitch({ pitch: "contour", semitones: 2 }), "contour +2 st");
+ assert.equal(describeVoicePitch({ pitch: "source", semitones: -1.5 }), "source −1.5 st");
assert.equal(listVoiceEngines().length, 4);
assert.equal(resolveVoiceParams(VOICE_ENGINES.rnnoise, []).ok, false);
});
diff --git a/common/lib/voiceSettings.ts b/common/lib/voiceSettings.ts
@@ -14,13 +14,17 @@ import {
DEFAULT_VOICE_ENGINE,
DEFAULT_VOICE_TARGET,
VOICE_ENGINES,
+ DEFAULT_VOICE_PITCH,
+ VOICE_PITCH_MODES,
+ VOICE_SEMITONES_MAX,
getVoiceEngine,
parseStockTarget,
type VoiceOp,
+ type VoicePitch,
} from "./voiceApps";
export type VoiceEnhanceSettings = { engine: string };
-export type VoiceConvertSettings = { engine: string; target: string };
+export type VoiceConvertSettings = { engine: string; target: string; pitch: VoicePitch; semitones: number };
export type VoiceSettings = {
home: string;
@@ -31,15 +35,20 @@ export type VoiceSettings = {
heavyEstimateMB: Record<string, number>;
};
+// An engine's own estimate, and — for one that can follow the input's pitch on
+// another model — that run's, under the engine's `pitch.estimateKey`.
export const DEFAULT_VOICE_HEAVY_ESTIMATES: Record<string, number> = Object.fromEntries(
- Object.values(VOICE_ENGINES).map((e) => [e.id, e.defaultEstimateMB]),
+ Object.values(VOICE_ENGINES).flatMap((e) => [
+ [e.id, e.defaultEstimateMB] as const,
+ ...(e.pitch ? [[e.pitch.estimateKey, e.pitch.defaultEstimateMB] as const] : []),
+ ]),
);
export const DEFAULT_VOICE_SETTINGS: VoiceSettings = {
home: "",
threads: 4,
enhance: { engine: DEFAULT_VOICE_ENGINE.enhance },
- convert: { engine: DEFAULT_VOICE_ENGINE.convert, target: DEFAULT_VOICE_TARGET },
+ convert: { engine: DEFAULT_VOICE_ENGINE.convert, target: DEFAULT_VOICE_TARGET, ...DEFAULT_VOICE_PITCH },
heavyEstimateMB: DEFAULT_VOICE_HEAVY_ESTIMATES,
};
@@ -51,11 +60,13 @@ export const VOICE_SETTINGS_FIELD_DOCS: FieldDocs<VoiceSettings> = {
"(`<home>/targets/`). Blank = `~/.local/share/archilyzer/voice`. Absolute, or `~/`-relative.",
threads: "CPU threads a torch engine (openvoice, seed-vc) may use. 1–16.",
enhance: "The enhance op's default engine. See VoiceEnhanceSettings (`voice.enhance` below).",
- convert: "The convert op's default engine and target. See VoiceConvertSettings (`voice.convert` below).",
+ convert: "The convert op's default engine, target and pitch. See VoiceConvertSettings (`voice.convert` below).",
heavyEstimateMB:
"Per engine id: the memory (MB) its job is admitted to the machine's heavy slot with " +
"(`queue-lock --heavy --estimate`) — it runs only when that much is free above the floor. " +
- "The defaults are the 2026-11-03 bake-off's measured peaks plus a margin. An engine left out " +
+ "The defaults are the 2026-11-03 bake-off's measured peaks plus a margin; `seed-vc-f0` is seed-vc's " +
+ "run when it follows the input's pitch (`pitch: source | contour` — another, bigger model; measured " +
+ "2026-11-11 over a take long enough to fill a 30 s window: 5.8 GB). An engine left out " +
"takes its default; 0 declares nothing (the job then runs ALONE in the slot).",
};
@@ -78,6 +89,17 @@ export const VOICE_CONVERT_SETTINGS_FIELD_DOCS: FieldDocs<VoiceConvertSettings>
"`<tts engine>:<stock voice>` (`orpheus:zac`, `orpheus:leah`, `kokoro:am_michael`, …). Never a " +
"file or a recording — no real person's voice is a target. Its reference clip is synthesized " +
"once through the `tts` op and kept under `home`. Anything else falls back to `orpheus:zac`.",
+ pitch:
+ "The pitch a conversion lands on when the request names none — for an engine that can follow the " +
+ "input's (seed-vc, with its optional f0 model: `archilyzer voice setup --engine seed-vc --with f0`; " +
+ "openvoice always lands on the target's). `target`: the stock voice's own pitch — the read's " +
+ "intonation is flattened to it (what there was before). `source`: the pitch the take was read at — " +
+ "raise your voice and the result rises. `contour`: the read's rises and falls, moved as a whole so " +
+ "their median sits on the stock voice's. Anything else falls back to `target`.",
+ semitones:
+ "Semitones a FOLLOWED pitch (`source`, `contour`) is moved by when the request names none: -12 to 12, " +
+ "0 = as followed. Ignored for `target`. It applies to a request that names its own `pitch` too: " +
+ "`{\"pitch\": \"source\"}` with no `semitones` is moved by this many — send `\"semitones\": 0` for none.",
};
// "" (the default), an absolute path, or a `~/` one; anything else is "".
@@ -109,7 +131,15 @@ export function sanitizeVoice(value: unknown): VoiceSettings {
home: dirSetting(r.home),
threads: Math.min(16, Math.max(1, threads)),
enhance: { engine: engineFor("enhance", en.engine) },
- convert: { engine: engineFor("convert", cv.engine), target: target.ok ? target.value.id : DEFAULT_VOICE_TARGET },
+ convert: {
+ engine: engineFor("convert", cv.engine),
+ target: target.ok ? target.value.id : DEFAULT_VOICE_TARGET,
+ pitch: VOICE_PITCH_MODES.includes(cv.pitch as VoicePitch) ? (cv.pitch as VoicePitch) : DEFAULT_VOICE_PITCH.pitch,
+ semitones:
+ typeof cv.semitones === "number" && Number.isFinite(cv.semitones)
+ ? Math.min(VOICE_SEMITONES_MAX, Math.max(-VOICE_SEMITONES_MAX, Math.round(cv.semitones * 100) / 100))
+ : DEFAULT_VOICE_PITCH.semitones,
+ },
heavyEstimateMB,
};
}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,8 @@
# Changelog
## [Unreleased]
+- **Lookouts: a saved set of channels and days, and a dry run that lists what it would read.** A lookout (lane/lookout) will read its channels' recent transcripts and answer with video ideas; this first part has no model. `settings.lookouts` holds the lookouts (off and empty by default; nothing in code names a channel), and `pnpm ops lookout-run --json '{"id":"…","dryRun":true}'` lists the week it would read: every video by its AIR date in the lookout's time zone (a stream that starts at 8:20 pm in New York is 3 Nov, not the 4 Nov of its UTC upload date), a recording uploaded twice read once with the other upload named beside it, a stream's cut-downs credited to the stream, the longest 40 read and every one left out listed with why. Over the pilot's week, read-only, it found all 6 of the pilot's duplicate uploads and all 18 of its stream cut-downs. `pnpm ops get lookouts` is the readout. Runs and verdicts will live in `transcripts/.lookouts/`, never published.
+- **A converted read can follow your pitch.** Converting a recorded read to a stock voice threw the voice acting away. On 11 Nov, reads with a median pitch of 128, 212, 225 and 237 Hz all came out at 196–199 Hz, and a 152–321 Hz range came out as 165–240 Hz: both converters speak at the stock voice's own pitch. `pnpm ops voice-convert` now takes `"pitch"`: `target` (as before), `source` (the pitch you read at: raise your voice and the result rises) or `contour` (your rises and falls, moved as a whole to the stock voice's register), and `"semitones"` (-12 to 12) moves a followed pitch. The same read that came out at 197 Hz now comes out at 211 Hz with a 148–314 Hz range, against 212 Hz and 152–321 Hz read. `source` and `contour` are seed-vc's, on its f0-conditioned model: optional files, fetched by `archilyzer voice setup --engine seed-vc --with f0` (1.49 GB). An install without them converts as before, and a followed pitch is refused naming that command; openvoice refuses a pitch it cannot follow. It takes about 1.7 times as long, and more memory (5.8 GB at its peak on a take of 20 s or more). `settings.voice.convert.pitch` and `.semitones` are the defaults (`target`, 0). In umtool a character keeps its pitch in the cast (`umtool cast set <id> --convert-pitch contour --convert-semitones 2`, shown on Voices), and `--pitch` / `--semitones` on `posts narrate … --recording` or `--derive <n> --op convert` set it for one read; the post bench's **run AI on take** has the same two controls for a convert on seed-vc, starting from the character's. The disclosure line is unchanged.
- **The dashboard says when a media drive is not answering, slow, or not mounted.** A stalled external drive used to show only on `/storage` and in channel badges, so the editor looked broken with nothing on its front page saying why. The dashboard now opens with one card per storage location in trouble: **not answering** (an alert: pages and polls skip the drive, and its channels' jobs wait until it answers), **answering slowly** (everything still runs, just late), or **not mounted** (only when some channel's media is on it). Each card links to `/storage` and to that location's channels. On `/storage` each location has a **Drive** line that says when the drive last answered and how long it took (for example "answering — 12 ms (a read in the editor), last at 11:42"), and a **slow** chip appears next to Available when two reads in a row on it take half the 3-second limit or more (one long read is not enough). `pnpm ops get storage` reports the same for each location under `rows[].drive`: `state` (`ok`, `slow`, `stalled` or `unmounted`), `since`, `lastOkAt`, `latencyMs`, the cause and the one-line text.
- **A transcription or backfill run waits while its channel's media drive is not answering.** Before, a run that started while the drive answered kept going after the drive stalled. Each next video asked the stalled drive for its audio, waited about 30 seconds and failed. Now the run pauses at the next video and says so in its log ("Holding: the media drive "…" is not answering (since 11:35) — no new transcription starts until it answers again"), then resumes by itself when the drive answers. If it has held for 5 minutes, the run checks the drive itself from a separate process, and it logs that it is still holding every 10 minutes. A run also follows a channel that is moved to another drive while it runs. A video that is refused because the drive is not answering is skipped, not added to the channel's failed-transcriptions list, and is transcribed on a later run. A downloaded video is also not moved into a saved-video store on a drive that is not answering. It stays in the video's folder, and a later pass stores it.
- **The drive watch no longer overwrites a tier you change while it is pausing channels.** The five-minute storage watch, which pauses the channels on a drive that went away and restores them when it comes back, could save its change in the middle of yours and undo it. It now waits for the same settings lock that the channel-priority save uses. The editor's `dev` script also gives Node 16 file-access threads, as `start`, the systemd unit and the container already do.
diff --git a/editor/app/api/ops/_lookouts.test.ts b/editor/app/api/ops/_lookouts.test.ts
@@ -0,0 +1,92 @@
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_lookouts.test.ts"
+//
+// `pnpm ops get lookouts` and `pnpm ops lookout-run` (the dry run, the only
+// one there is yet), against the route handlers over a temp corpus. Every
+// channel and lookout here is invented. Never the live editor's settings.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, readdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { callGet, callPost, setupOpsCorpus } from "./_testCorpus";
+
+const corpus = await setupOpsCorpus(null);
+const { GET } = await import("./lookouts/route");
+const { POST } = await import("./lookout-run/route");
+test.after(() => corpus.cleanup());
+
+const LOOKOUTS = {
+ enabled: false,
+ afterSync: false,
+ items: [{ id: "example-week", label: "Example week", channels: ["example-news", "no-such-channel"], days: 3, timeZone: "America/New_York" }],
+};
+
+async function video(slug: string, dir: string, title: string, uploadDate: string, timestamp: number, seconds: number) {
+ const d = path.join(corpus.transcripts, "channels", slug, "data", dir);
+ await mkdir(d, { recursive: true });
+ await writeFile(path.join(d, "metadata.info.json"), JSON.stringify({ id: dir, title, duration: seconds, upload_date: uploadDate, timestamp }));
+ const cues = Array.from({ length: 40 }, (_, i) => ({ start: i * (seconds / 40), end: (i + 1) * (seconds / 40), text: `${title} line ${i} of ${dir}` }));
+ await writeFile(
+ path.join(d, "transcript.cues.json"),
+ JSON.stringify({ version: 2, id: dir, title, uploadDate, duration: seconds, platform: "youtube", webpageUrl: `https://example.invalid/${dir}`, cues }),
+ );
+}
+
+test("get lookouts: the saved lookouts and what the store holds for each; nothing configured is an empty list", async () => {
+ const empty = await callGet(GET!, "http://localhost/api/ops/lookouts");
+ assert.equal(empty.status, 200, JSON.stringify(empty.body));
+ assert.deepEqual(empty.body.lookouts, []);
+ assert.equal(empty.body.enabled, false);
+
+ await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS });
+ const r = await callGet(GET!, "http://localhost/api/ops/lookouts");
+ assert.equal(r.status, 200, JSON.stringify(r.body));
+ const [one] = r.body.lookouts as Record<string, unknown>[];
+ assert.equal(one!.id, "example-week");
+ assert.equal(one!.maxVideos, 40, "the defaults the settings filled");
+ assert.equal(one!.lastRun, null);
+ assert.equal(one!.runs, 0);
+ assert.equal(one!.unruled, 0);
+ assert.equal((await callGet(GET!, "http://localhost/api/ops/lookouts?id=nope")).status, 404);
+ assert.equal((await callGet(GET!, "http://localhost/api/ops/lookouts?lookout=x")).status, 400);
+});
+
+test("lookout-run: the dry run lists what would be read, on air dates, and writes nothing", async () => {
+ await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS });
+ await corpus.writeChannelConfig("example-news", {});
+ // 2026-11-04T01:20:53Z is the evening of 3 Nov in New York.
+ await video("example-news", "Evening0001", "Evening Show", "20261104", 1793755253, 1200);
+ await video("example-news", "Short000001", "A Short", "20261104", 1793790000, 45);
+ const before = await readdir(corpus.transcripts);
+ const r = await callPost(POST!, { id: "example-week", dryRun: true, until: "2026-11-05" });
+ assert.equal(r.status, 200, JSON.stringify(r.body));
+ const plan = r.body.plan as {
+ window: { from: string; to: string };
+ read: { video: string; airDate: string }[];
+ skipped: { video: string; reason: string }[];
+ refused: { channel: string }[];
+ };
+ assert.deepEqual(plan.window, { from: "2026-11-03", to: "2026-11-05", days: 3, timeZone: "America/New_York" });
+ assert.deepEqual(plan.read.map((v) => [v.video, v.airDate]), [["Evening0001", "2026-11-03"]]);
+ assert.deepEqual(plan.skipped.map((v) => [v.video, v.reason]), [["Short000001", "under-min-seconds"]]);
+ assert.deepEqual(plan.refused.map((x) => x.channel), ["no-such-channel"]);
+ assert.deepEqual(await readdir(corpus.transcripts), before, "no store, no job, nothing written");
+ assert.deepEqual(await corpus.listJobIds(), []);
+});
+
+test("lookout-run refuses before reading anything: no dryRun, an unknown lookout or key, bad overrides", async () => {
+ await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS });
+ const run = await callPost(POST!, { id: "example-week" });
+ assert.equal(run.status, 400);
+ assert.match(String(run.body.error), /dryRun/);
+ assert.equal((await callPost(POST!, { id: "example-week", dryRun: false })).status, 400);
+ assert.equal((await callPost(POST!, { id: "nope", dryRun: true })).status, 404);
+ assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, model: "x" })).status, 400);
+ assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, days: 99 })).status, 400);
+ assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, maxVideos: 0 })).status, 400);
+ assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, until: "11/05/2026" })).status, 400);
+ await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: { items: [{ id: "empty", channels: [] }] } });
+ const none = await callPost(POST!, { id: "empty", dryRun: true });
+ assert.equal(none.status, 400);
+ assert.match(String(none.body.error), /names no channels/);
+});
diff --git a/editor/app/api/ops/lookout-run/route.ts b/editor/app/api/ops/lookout-run/route.ts
@@ -0,0 +1,56 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { isIsoDate } from "yt-dlp-transcript-common/lib/lookout";
+import { LOOKOUT_MAX_DAYS, LOOKOUT_MAX_MAX_VIDEOS, lookoutById } from "yt-dlp-transcript-common/lib/lookoutSettings";
+import { LookoutPlanRefusal, planLookout } from "yt-dlp-transcript-common/controller/lookoutPlan";
+import { OpsInputError, ops, opsFail, optBool, optPositiveInt, optString, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { id, dryRun: true, days?, maxVideos?, until? } -> { ok: true, plan }
+//
+// What a saved lookout (settings.lookouts.items, SETTINGS.md) would read
+// (common/controller/lookoutPlan.ts): every video of its channels whose AIR
+// date — `release_timestamp`, else `timestamp`, in its time zone — falls in
+// the window; duplicate uploads and a stream's cut-downs folded into one
+// recording; the longest `maxVideos` read and the rest listed as skipped for
+// the cap, with why for every video left out; the reading calls and, once a
+// run has been measured, the seconds they would take. `days` and `maxVideos`
+// override the lookout's for this answer; `until` (YYYY-MM-DD) ends the window
+// on another day than today. A local media library channel, or a slug this
+// archive does not hold, is named in `refused`. Reads text only and writes
+// nothing; synchronous, no job, no model, no network.
+//
+// Only the dry run exists in this build: without `dryRun: true` the request is
+// refused, never run.
+export async function POST(request: Request) {
+ return ops(request, ["id", "dryRun", "days", "maxVideos", "until"], async (body) => {
+ const id = reqString(body, "id");
+ if (optBool(body, "dryRun") !== true) {
+ throw new OpsInputError(
+ 'a lookout run reads with a model, which this build does not do yet — send "dryRun": true to list what it would read',
+ );
+ }
+ const days = optPositiveInt(body, "days");
+ if (days !== undefined && days > LOOKOUT_MAX_DAYS) throw new OpsInputError(`"days" is at most ${LOOKOUT_MAX_DAYS}`);
+ const maxVideos = optPositiveInt(body, "maxVideos");
+ if (maxVideos !== undefined && maxVideos > LOOKOUT_MAX_MAX_VIDEOS) {
+ throw new OpsInputError(`"maxVideos" is at most ${LOOKOUT_MAX_MAX_VIDEOS}`);
+ }
+ const until = optString(body, "until");
+ if (until !== undefined && !isIsoDate(until)) throw new OpsInputError('"until" is a date, YYYY-MM-DD');
+ const lookouts = getSettings().lookouts;
+ const item = lookoutById(lookouts, id);
+ if (!item) {
+ return opsFail(`no lookout "${id}" — settings.lookouts.items names ${lookouts.items.map((i) => i.id).join(", ") || "none"}`, 404);
+ }
+ try {
+ const plan = await planLookout(getPaths(), item, { days, maxVideos, until });
+ return NextResponse.json({ ok: true, plan });
+ } catch (err) {
+ if (err instanceof LookoutPlanRefusal) throw new OpsInputError(err.message);
+ throw err;
+ }
+ });
+}
diff --git a/editor/app/api/ops/lookouts/route.ts b/editor/app/api/ops/lookouts/route.ts
@@ -0,0 +1,29 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { lookoutReadout } from "yt-dlp-transcript-common/lib/lookoutStore";
+import { opsFail } from "../_lib";
+import { readRoute } from "../_read";
+
+export const dynamic = "force-dynamic";
+
+// GET /api/ops/lookouts[?id=<lookout>] — `pnpm ops get lookouts`
+//
+// The saved lookouts (settings.lookouts, SETTINGS.md) and what the store holds
+// for each (common/lib/lookoutStore.ts, `transcripts/.lookouts/<id>/`): its
+// runs, the latest one summarised (when, window, model, calls, seconds,
+// ideas), how many of that run's ideas have no verdict yet, and the verdicts
+// given. Reads settings and the store only — never a channel's videos, so it
+// is cheap to poll; what a lookout would read is `lookout-run` with dryRun.
+export async function GET(request: Request) {
+ return readRoute(request, ["id"], async (q) => {
+ const { enabled, afterSync, items } = getSettings().lookouts;
+ const id = q.get("id");
+ const chosen = id === null ? items : items.filter((i) => i.id === id);
+ if (id !== null && chosen.length === 0) {
+ return opsFail(`no lookout "${id}" — settings.lookouts.items names ${items.map((i) => i.id).join(", ") || "none"}`, 404);
+ }
+ const paths = getPaths();
+ const lookouts = await Promise.all(chosen.map(async (item) => ({ ...item, ...(await lookoutReadout(paths, item.id)) })));
+ return { enabled, afterSync, lookouts };
+ });
+}
diff --git a/editor/app/api/ops/voice-convert/route.ts b/editor/app/api/ops/voice-convert/route.ts
@@ -7,7 +7,7 @@ import { jobResponse, ops } from "../_lib";
export const dynamic = "force-dynamic";
-// POST { file, out, voice?, engine?, params?, parts? } -> { ok: true, jobId }
+// POST { file, out, voice?, engine?, pitch?, semitones?, params?, parts? } -> { ok: true, jobId }
//
// Keep a recording's PERFORMANCE — its timing, pitch contour and emphasis —
// and give it a STOCK synthetic voice's timbre, as a job on /jobs
@@ -22,7 +22,12 @@ export const dynamic = "force-dynamic";
// `engine` is `openvoice` (OpenVoice v2's converter) or `seed-vc` (Seed-VC v1),
// default settings.voice.convert.engine — `archilyzer voice setup --engine
// <id>` installs one; `file`/`path`, `out`, `params` and `parts` as for
-// voice-enhance. umtool's derived takes (`umtool posts narrate … --derive <n>
+// voice-enhance. `pitch` says where the result's pitch comes from — `target`
+// (the stock voice's own: the read's intonation is flattened to it), `source`
+// (the pitch the take was read at) or `contour` (the read's rises and falls at
+// the stock voice's register) — and `semitones` (-12 to 12) moves a followed
+// one; defaults settings.voice.convert. source and contour are seed-vc's, on
+// its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`). umtool's derived takes (`umtool posts narrate … --derive <n>
// --op convert`) are the caller.
//
// The job's log ends with `@@voice-result {json}` — voice-enhance's shape plus
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -211,6 +211,9 @@
// pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'
// pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'
// pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'
+// pnpm ops get lookouts
+// pnpm ops lookout-run --json '{"id":"example-week","dryRun":true}'
+// pnpm ops lookout-run --json '{"id":"example-week","dryRun":true,"days":3,"until":"2026-11-10"}'
//
// --file reads the BODY from a JSON file, which is how a big one gets sent: a
// four-thousand-id tag-videos body is written by a script, not typed by a model
@@ -318,6 +321,9 @@ const GETTERS = {
cleanup: (slug) => `/api/ops/cleanup/${encodeURIComponent(slug)}`,
// The speakers readout: waiting, freed this run, rate, days left, per channel.
speakers: () => "/api/ops/speakers",
+ // The saved lookouts (settings.lookouts) and what the store holds for each:
+ // the latest run, how many of its ideas wait for a verdict.
+ lookouts: (id) => (id ? `/api/ops/lookouts?id=${encodeURIComponent(id)}` : "/api/ops/lookouts"),
// What a channel holds, by date, and its gaps (release 19 A9): each video
// dated by its recorded date when the channel has a title rule, else upload.
coverage: (slug) => `/api/ops/coverage?slug=${encodeURIComponent(slug)}`,
@@ -371,6 +377,7 @@ const GET_ARG_OPTIONAL = new Set([
"generation-usage",
"render-mode",
"speakers",
+ "lookouts",
]);
// The flags each noun takes beyond the shared ones; any other is refused.
@@ -569,7 +576,8 @@ const ACTIONS = [
"tts",
// Run an engine over a speech RECORDING ({file, out, engine?, params?,
// parts?}; convert also takes voice — a stock synthetic voice
- // `<tts engine>:<voice>`, never a recording), as a job on the `voice` queue
+ // `<tts engine>:<voice>`, never a recording — and pitch / semitones, the
+ // pitch the result lands on), as a job on the `voice` queue
// behind the heavy slot. With --wait the result JSON is what stdout carries.
"voice-enhance",
"voice-convert",
@@ -715,6 +723,11 @@ const ACTIONS = [
// X's queue, the jar checked before each ({channels: [...], limit?} or
// {resume: <run id>}); a stale jar defers the rest.
"x-run",
+ // What a saved lookout would read ({id, dryRun: true, days?, maxVideos?,
+ // until?}): its channels' videos by air date, duplicate uploads and stream
+ // cut-downs folded in, the cap. Synchronous; no job, nothing written. Only
+ // the dry run exists yet.
+ "lookout-run",
];
// The log line a transcribe job ends with: this marker, then the result as
@@ -1094,6 +1107,7 @@ export function usage() {
" pnpm ops get x-run [<run id>]",
" pnpm ops get cleanup <slug>",
" pnpm ops get speakers",
+ " pnpm ops get lookouts [<id>]",
" pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]",
" pnpm ops get transcript <videoId> [--slug <slug>]",
" pnpm ops get coverage <slug>",
@@ -1189,6 +1203,11 @@ export function usage() {
" noFingerprintPossible (diarized, audio already gone), per channel with",
" corpus-disk channels first; and the lane: armed, held, the operations",
" it dispatches, its order, cleanAfterCapture and requireVoiceprints.",
+ "get lookouts [<id>] is the saved lookouts (settings.lookouts, SETTINGS.md):",
+ " each one's channels, days, cap and zone, its runs (transcripts/.lookouts/",
+ " <id>/), the latest run (when, window, model, calls, seconds, ideas), how",
+ " many of that run's ideas have no verdict yet, and the verdicts given.",
+ " Reads settings and the store only, never a channel's videos.",
"get cleanup <slug> is one channel's /cleanup row: what each sweep would",
" reclaim (they overlap — never add them), what holds the rest, and the",
" failed-transcriptions count. measured: false means unknown, not zero.",
@@ -1274,6 +1293,20 @@ export function usage() {
' "speakers": "work" (the deck\'s Work through speakers: arm, lift the hold,',
' start a run) | "pause" (hold; stays armed).',
"",
+ 'lookout-run lists what a saved lookout (settings.lookouts) would read:',
+ ' {"id", "dryRun": true, "days"?, "maxVideos"?, "until"?: "YYYY-MM-DD"}.',
+ " Every video of its channels whose AIR date (release_timestamp, else",
+ " timestamp, in the lookout's timeZone — not the UTC upload_date) falls in",
+ " the window; a duplicate upload of one recording, and a stream's cut-down,",
+ " folded into it (each named, with why and its score); the longest",
+ " maxVideos recordings read and the rest listed as skipped for the cap;",
+ " under minSeconds and no transcript yet listed too. A local media library",
+ " channel or a slug this archive does not hold is named in \"refused\".",
+ " Answers {plan: {window, counts, read, skipped, refused, estimate}}:",
+ " readCalls is one per transcript chunk, priced once a run has been",
+ " measured. Synchronous, reads text only, writes nothing; without",
+ ' "dryRun": true it is refused (the model run is not in this build).',
+ "",
'render-mode gives a render the operator is waiting for the machine:',
' {"on": true, "for"?: "90m" | <minutes>, "note"?} opens a window (default',
' 2h) in which every other heavy job — e2e suites, next builds, the publish',
@@ -2034,8 +2067,17 @@ export function usage() {
" kokoro:am_michael, ...; settings.voice.convert.target); a file, a path or a",
" recording is REFUSED as a target (no real person's voice) — and \"engine\"",
" (openvoice | seed-vc, each installed by `archilyzer voice setup --engine <id>`).",
+ ' "pitch" is where the result\'s pitch comes from (settings.voice.convert.pitch):',
+ ' "target" — the stock voice\'s own, the read\'s intonation flattened to it;',
+ ' "source" — the pitch the take was read at (raise your voice and it rises);',
+ ' "contour" — the read\'s rises and falls, moved as a whole to the stock voice\'s',
+ ' register. "semitones" (-12 to 12) then moves a followed pitch; left out, a',
+ " followed pitch takes settings.voice.convert.semitones (0 unless set). source and",
+ " contour are seed-vc's, on its optional f0 model (`archilyzer voice setup",
+ " --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them.",
" The target's reference is synthesized once through the tts op and kept. The",
- " result adds target, voice, synthetic: true and the disclosure line.",
+ " result adds target, voice, pitch (semitones and f0 — the medians heard and the",
+ " move applied — when followed), synthetic: true and the disclosure line.",
"",
'web-search searches the web (DuckDuckGo\'s HTML page) and answers the',
' results: {"query", "n"?: 6 (at most 20)} -> {results: [{title, url,',
diff --git a/scripts/voice.mjs b/scripts/voice.mjs
@@ -15,7 +15,9 @@
// its delay compensated (-D) so the timing holds.
// convert openvoice OpenVoice v2's tone-colour converter
// (scripts/voice_openvoice.py, torch on the CPU).
-// seed-vc Seed-VC v1's 22 kHz speech model
+// seed-vc Seed-VC v1's 22 kHz speech model, or with
+// --pitch source|contour its 44.1 kHz f0-conditioned
+// one, whose output follows the input's pitch
// (scripts/voice_seedvc.py, torch on the CPU).
// A convert engine is given --target-ref: a STOCK voice's reference clip,
// made by our own TTS engines (the controller refuses anything else).
@@ -27,7 +29,8 @@
// limiter, which would move the timing): to --lufs for enhance, to the
// input's own loudness for convert, either capped at -1 dBTP. Moved into
// place atomically. On stdout, one JSON line: {op, engine, sampleRate,
-// seconds, samples, engineMs, gainDb, inputLufs, outputLufs, more?}.
+// seconds, samples, engineMs, gainDb, inputLufs, outputLufs, more?}, and for
+// a followed pitch {pitch, semitones, f0: {targetHz, sourceHz, shiftSemitones}}.
//
// SCRATCH lives beside --output (`<output>.voice-<pid>/`), never in the OS
// temp dir (a RAM tmpfs on this machine), and is removed on every way out.
@@ -45,6 +48,10 @@
// --code <dir> the engine's pinned checkout [openvoice, seed-vc]
// --target-ref <wav> the stock target's reference clip [convert]
// --target-se <pt> where openvoice caches the target's embedding
+// --pitch <mode> target (default: the stock voice's own pitch), source
+// (the input's pitch) or contour (the input's intonation
+// at the stock voice's register) [seed-vc]
+// --semitones <n> moves a followed pitch, -12 to 12 [seed-vc, with --pitch source|contour]
// --model <f> the rnnoise model [rnnoise]
// --threads <n> CPU threads for torch (default 4)
// --lufs <x> enhance's level when params has no `lufs` (default -20)
@@ -101,6 +108,14 @@ if (!Array.isArray(extra) || !extra.every((x) => x && typeof x.input === "string
}
const ffmpeg = arg("--ffmpeg", process.env.FFMPEG_BIN ?? "ffmpeg");
const threads = String(Math.max(1, Number(arg("--threads", "4")) || 4));
+// The pitch a conversion lands on (seed-vc; scripts/voice_seedvc.py's header).
+const PITCH_MODES = ["target", "source", "contour"];
+const pitch = arg("--pitch", "target");
+const semitones = Number(arg("--semitones", "0"));
+if (!PITCH_MODES.includes(pitch)) fail(`--pitch is one of ${PITCH_MODES.join(", ")} (got '${pitch}')`);
+if (!Number.isFinite(semitones) || semitones < -12 || semitones > 12) fail(`--semitones is a number from -12 to 12 (got '${arg("--semitones", "")}')`);
+if (pitch !== "target" && kind !== "seed-vc") fail(`--pitch ${pitch} is seed-vc's: ${kind} has no pitch control`);
+if (semitones !== 0 && pitch === "target") fail("--semitones moves a followed pitch: it needs --pitch source or contour");
const lufs = typeof params.lufs === "number" ? params.lufs : Number(arg("--lufs", "-20"));
const out = path.resolve(output);
@@ -247,13 +262,27 @@ async function convertAll(items) {
"--threads", threads,
], { env });
} else {
- await run(python, [
+ const { stdout } = await run(python, [
path.join(import.meta.dirname, "voice_seedvc.py"),
"--code", code,
- "--dit", path.join(install, "DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth"),
- "--config", path.join(install, "config_dit_mel_seed_uvit_whisper_small_wavenet.yml"),
+ // A followed pitch is the f0-conditioned model's (44.1 kHz, its own
+ // vocoder, RMVPE): the optional files `voice setup --engine seed-vc
+ // --with f0` fetches (common/lib/voiceApps.ts SEEDVC_F0_FILES).
+ ...(pitch === "target"
+ ? [
+ "--dit", path.join(install, "DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth"),
+ "--config", path.join(install, "config_dit_mel_seed_uvit_whisper_small_wavenet.yml"),
+ "--bigvgan", path.join(install, "bigvgan"),
+ ]
+ : [
+ "--dit", path.join(install, "DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2.pth"),
+ "--config", path.join(install, "config_dit_mel_seed_uvit_whisper_base_f0_44k.yml"),
+ "--bigvgan", path.join(install, "bigvgan-44k"),
+ "--rmvpe", path.join(install, "rmvpe.pt"),
+ "--pitch", pitch,
+ "--semitones", String(semitones),
+ ]),
"--whisper", path.join(install, "whisper-small"),
- "--bigvgan", path.join(install, "bigvgan"),
"--campplus", path.join(install, "campplus_cn_common.bin"),
"--batch", batch, "--target-ref", ref,
"--steps", String(Math.round(Math.min(100, Math.max(1, num(params.steps, 10))))),
@@ -261,7 +290,15 @@ async function convertAll(items) {
"--ref-seconds", String(Math.min(25, Math.max(3, num(params.refSeconds, 10)))),
"--threads", threads,
], { env });
+ // A followed pitch: what the tracker heard and how far the curve was moved.
+ try {
+ const said = JSON.parse(stdout.trim().split("\n").pop() ?? "{}");
+ if (pitch !== "target" && said.f0 && typeof said.f0 === "object") return { pitch, semitones, f0: said.f0 };
+ } catch {
+ /* the result line is the wrapper's own */
+ }
}
+ return {};
}
// One static gain (enhance to --lufs, convert to the input's own loudness;
@@ -302,8 +339,9 @@ try {
const items = [];
for (const [k, item] of [{ input, output }, ...extra].entries()) items.push(await prepare(item, k));
const started = Date.now();
+ const engineSaid = {};
if (op === "enhance") for (const it of items) await enhanceOne(it);
- else await convertAll(items);
+ else Object.assign(engineSaid, await convertAll(items));
const engineMs = Date.now() - started;
const done = [];
for (const it of items) done.push(await finish(it));
@@ -319,6 +357,7 @@ try {
gainDb: first.gainDb,
inputLufs: first.inputLufs,
outputLufs: first.outputLufs,
+ ...engineSaid,
...(rest.length ? { more: rest } : {}),
};
process.stdout.write(JSON.stringify(result) + "\n");
diff --git a/scripts/voice.test.mjs b/scripts/voice.test.mjs
@@ -31,6 +31,13 @@ test("the argv is checked before anything runs", () => {
assert.match(run(["--op", "enhance", "--engine-kind", "seed-vc"]).stderr, /--engine-kind for enhance is one of rnnoise, deepfilternet/);
assert.match(run(["--op", "enhance", "--engine-kind", "rnnoise"]).stderr, /--input and --output are required/);
assert.match(run(["--op", "enhance", "--engine-kind", "rnnoise", "--input", "/a", "--output", "/b", "--params", "{"]).stderr, /--params must be JSON/);
+ // The pitch a conversion lands on is seed-vc's to follow, and semitones move a followed one.
+ const conv = (kind, ...more) => run(["--op", "convert", "--engine-kind", kind, "--input", "/a", "--output", "/b", ...more]);
+ assert.match(conv("seed-vc", "--pitch", "higher").stderr, /--pitch is one of target, source, contour \(got 'higher'\)/);
+ assert.match(conv("seed-vc", "--pitch", "source", "--semitones", "13").stderr, /--semitones is a number from -12 to 12 \(got '13'\)/);
+ assert.match(conv("seed-vc", "--semitones", "2").stderr, /--semitones moves a followed pitch: it needs --pitch source or contour/);
+ assert.match(conv("openvoice", "--pitch", "contour").stderr, /--pitch contour is seed-vc's: openvoice has no pitch control/);
+ for (const r of [conv("seed-vc", "--pitch", "higher"), conv("openvoice", "--pitch", "contour")]) assert.equal(r.status, 2);
});
test("rnnoise: 48 kHz mono, the input's exact length, aligned, the same every run", { skip: !ffmpeg && "ffmpeg absent" }, () => {
@@ -90,3 +97,43 @@ test("--more runs further files the same way, in the same run", { skip: !ffmpeg
assert.equal(readFileSync(outB).readUInt32LE(40), 48000);
assert.match(run(["--op", "enhance", "--engine-kind", "rnnoise", "--input", a, "--output", "/x.wav", "--more", '[{"input":1}]']).stderr, /--more is a list of \{input, output\}/);
});
+
+// scripts/voice_seedvc.py's contour shift over a batch (a take and its parts): measured once, on the first file with
+// a voiced frame. The function is stdlib-only (torch and the model are imported inside main).
+let python = true;
+try {
+ execFileSync("python3", ["-c", "import math"], { stdio: "ignore" });
+} catch {
+ python = false;
+}
+
+test("seed-vc's contour shift: set by the first file with a voiced frame, never locked at 0 by a silent one", { skip: !python && "python3 absent" }, () => {
+ const code = `
+import json, math, sys
+sys.path.insert(0, ${JSON.stringify(import.meta.dirname)})
+from voice_seedvc import pitch_move
+ref, src = math.log(200.0), math.log(100.0)
+out = {}
+# A silent first file: nothing measured, a factor of the semitones alone.
+m, hz, f = pitch_move(None, None, None, ref, "contour", 0)
+out["silent"] = [m, hz, f]
+# The next, voiced: an octave up to the reference's median, and it is kept.
+m, hz, f = pitch_move(m, hz, src, ref, "contour", 0)
+out["voiced"] = [round(m, 6), hz, round(f, 6)]
+m2, hz2, f2 = pitch_move(m, hz, math.log(150.0), ref, "contour", 0)
+out["later"] = [round(m2, 6), hz2, round(f2, 6)]
+# Source: no move, the semitones alone; contour with semitones: both.
+out["source"] = [round(x, 6) if isinstance(x, float) else x for x in pitch_move(None, None, src, ref, "source", 12)]
+out["both"] = round(pitch_move(None, None, src, ref, "contour", -12)[2], 6)
+# A silent file after the move is set does not unset it.
+out["after"] = round(pitch_move(m, hz, None, ref, "contour", 0)[0], 6)
+print(json.dumps(out))
+`;
+ const out = JSON.parse(execFileSync("python3", ["-c", code], { encoding: "utf8", env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" } }));
+ assert.deepEqual(out.silent, [null, null, 1]);
+ assert.deepEqual(out.voiced, [0.693147, 100, 2]);
+ assert.deepEqual(out.later, [0.693147, 100, 2]);
+ assert.deepEqual(out.source, [0, 100, 2]);
+ assert.equal(out.both, 1);
+ assert.equal(out.after, 0.693147);
+});
diff --git a/scripts/voice_seedvc.py b/scripts/voice_seedvc.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-# SEED-VC (v1, the 22 kHz speech model), files in, files out — run by
+# SEED-VC (v1: the 22 kHz speech model, or the 44.1 kHz f0-conditioned one), files in, files out — run by
# scripts/voice.mjs (--engine-kind seed-vc) in the venv `archilyzer voice
# setup --engine seed-vc` built. Never run by hand: the editor's
# `voice-convert` op is the way in (common/controller/voiceFile.ts).
@@ -17,19 +17,56 @@
# quantizer this model does not use; it is stubbed rather than installed (it
# pulls in a training stack).
#
+# PITCH (--pitch). The 22 kHz model is given no pitch at all: it speaks every
+# input at the TARGET's own pitch and narrows the range (measured 2026-11-11:
+# inputs with a median f0 of 128 to 237 Hz all came out at 196-199 Hz) — the
+# read's intonation is thrown away. `--pitch target` is that, unchanged. The
+# other two run upstream's f0-conditioned model (`inference.py --f0-condition`:
+# 44.1 kHz, a 128-band BigVGAN, RMVPE as the pitch tracker — voice.mjs passes
+# those files as --dit/--config/--bigvgan and --rmvpe): the input's f0 curve
+# conditions the content, so the output's pitch FOLLOWS the read.
+# source the input's f0 as it is: the output is at the pitch it was read at.
+# contour the input's curve moved, as a whole, so its median lands on the
+# target reference's median (upstream's --auto-f0-adjust): every rise
+# and fall is kept, the register is the stock voice's.
+# --semitones then moves the followed curve up or down (2^(n/12)). In a batch
+# the contour's move is measured ONCE, on the first file (the take), and used
+# for the rest (its parts): a part must sit where it sits in the whole. A file
+# with no voiced frame (silence, a breath) has no median to measure: it leaves
+# the move unset, and the first file that has one sets it.
+#
# Several files (--batch) are converted one after another, the model and the
# target's features made once.
#
-# stdout: one JSON line {engine, sampleRate, seconds, files, engineMs}.
+# stdout: one JSON line {engine, sampleRate, seconds, files, engineMs, pitch,
+# semitones, f0?: {targetHz, sourceHz, shiftSemitones}} — f0 is the medians
+# RMVPE heard in the reference and the first file, and the whole move applied.
import argparse
import json
+import math
import os
import sys
import time
import types
+def pitch_move(move, source_hz, median, ref_median, pitch, semitones):
+ """The followed curve's factor for one file, and the batch's state after it.
+
+ `move` is the batch's shift in log-f0 (None: not measured yet), `median` this
+ file's median log-f0 (None: no voiced frame), `ref_median` the reference's.
+ The shift is measured ONCE, on the first file with a voiced frame — contour:
+ the reference's median less the file's; source: 0 — and a file before it
+ (unvoiced: nothing in it is multiplied anyway) leaves it unset rather than
+ locking it at 0. Returns (move, source_hz, factor).
+ """
+ if move is None and median is not None:
+ source_hz = round(math.exp(median), 1)
+ move = (ref_median - median) if pitch == "contour" and ref_median is not None else 0.0
+ return move, source_hz, math.exp(move or 0.0) * 2 ** (semitones / 12)
+
+
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--code", required=True, help="the seed-vc checkout")
@@ -46,11 +83,22 @@ def main() -> int:
ap.add_argument("--cfg-rate", type=float, default=0.7)
ap.add_argument("--ref-seconds", type=float, default=10.0,
help="how much of the reference prompts the model: each window is 30 s less this, so less is faster")
+ ap.add_argument("--pitch", choices=["target", "source", "contour"], default="target",
+ help="target: the stock voice's own pitch (the 22 kHz model); source / contour: the input's f0 conditions the 44.1 kHz f0 model")
+ ap.add_argument("--semitones", type=float, default=0.0, help="moves the followed f0 (source, contour); -12 to 12")
+ ap.add_argument("--rmvpe", default="", help="rmvpe.pt, the pitch tracker (source, contour)")
ap.add_argument("--threads", type=int, default=4)
a = ap.parse_args()
items = json.load(open(a.batch)) if a.batch else [{"input": a.input, "output": a.output}]
if not items or not all(i.get("input") and i.get("output") for i in items):
ap.error("--input and --output, or --batch")
+ follow = a.pitch != "target"
+ if follow and not a.rmvpe:
+ ap.error("--pitch source|contour needs --rmvpe")
+ if not follow and a.semitones != 0:
+ ap.error("--semitones moves a followed pitch: it needs --pitch source or contour")
+ if not -12 <= a.semitones <= 12:
+ ap.error("--semitones is between -12 and 12")
os.environ.setdefault("HF_HUB_OFFLINE", "1")
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
@@ -106,6 +154,34 @@ def main() -> int:
whisper.eval()
feat = AutoFeatureExtractor.from_pretrained(a.whisper, local_files_only=True)
+ # The pitch tracker (source, contour): f0 in Hz per 10 ms of 16 kHz audio,
+ # 0 where unvoiced. A long input goes in 30 s pieces, each heard with a
+ # second of context either side — RMVPE over half an hour at once is GBs.
+ f0_of = None
+ if follow:
+ from modules.rmvpe import RMVPE
+
+ rmvpe = RMVPE(a.rmvpe, is_half=False, device=device)
+ PIECE, CTX, HOP16 = 16000 * 30, 16000, 160
+
+ def f0_of(w16):
+ w16 = w16.squeeze(0).cpu().numpy()
+ n = len(w16)
+ if n <= PIECE + 2 * CTX:
+ return rmvpe.infer_from_audio(w16, thred=0.03)
+ out, at = [], 0
+ while at < n:
+ lo, end = max(0, at - CTX), min(n, at + PIECE)
+ f = rmvpe.infer_from_audio(w16[lo : min(n, end + CTX)], thred=0.03)
+ first = (at - lo) // HOP16
+ out.append(f[first:] if end == n else f[first : first + (end - at) // HOP16])
+ at = end
+ return np.concatenate(out)
+
+ def median_log(f0):
+ v = f0[f0 > 1]
+ return float(np.median(np.log(v))) if len(v) else None
+
def semantic(w16):
inputs = feat([w16.squeeze(0).cpu().numpy()], return_tensors="pt", return_attention_mask=True, sampling_rate=16000)
x = whisper._mask_input_features(inputs.input_features, attention_mask=inputs.attention_mask)
@@ -148,8 +224,23 @@ def main() -> int:
fb = torchaudio.compliance.kaldi.fbank(ref16, num_mel_bins=80, dither=0, sample_frequency=16000)
fb = fb - fb.mean(dim=0, keepdim=True)
style = campplus(fb.unsqueeze(0))
- prompt, *_ = model.length_regulator(s_ori, ylens=target2_len, n_quantizers=3, f0=None)
+ f0_ref = f0_of(ref16) if follow else None
+ prompt, *_ = model.length_regulator(s_ori, ylens=target2_len, n_quantizers=3,
+ f0=torch.from_numpy(f0_ref)[None] if follow else None)
window = max_context - mel2.size(2)
+ ref_median = median_log(f0_ref) if follow else None
+ # What was heard and done, for the result line; `move` is the contour's
+ # shift in log-f0, measured on the first file that has a voiced frame and
+ # kept for the rest (None until then: a file with none has nothing to move).
+ heard = {"move": None, "sourceHz": None}
+
+ def followed_f0(src16):
+ f0 = f0_of(src16)
+ heard["move"], heard["sourceHz"], factor = pitch_move(heard["move"], heard["sourceHz"], median_log(f0), ref_median, a.pitch, a.semitones)
+ voiced = f0 > 1
+ out = f0.copy()
+ out[voiced] = f0[voiced] * factor
+ return torch.from_numpy(out.astype(np.float32))[None]
def convert(src):
with torch.no_grad():
@@ -172,7 +263,8 @@ def main() -> int:
s_alt = torch.cat(parts, dim=1)
mel = to_mel(source)
# The input's own frame count: the timing is the input's.
- cond, *_ = model.length_regulator(s_alt, ylens=torch.LongTensor([mel.size(2)]), n_quantizers=3, f0=None)
+ cond, *_ = model.length_regulator(s_alt, ylens=torch.LongTensor([mel.size(2)]), n_quantizers=3,
+ f0=followed_f0(src16) if follow else None)
done, chunks, prev = 0, [], None
while done < cond.size(1):
c = cond[:, done : done + window]
@@ -208,6 +300,13 @@ def main() -> int:
"seconds": round(total, 3),
"files": len(items),
"engineMs": int((time.time() - t0) * 1000),
+ "pitch": a.pitch,
+ "semitones": a.semitones,
+ **({"f0": {
+ "targetHz": round(float(np.exp(ref_median)), 1) if ref_median is not None else None,
+ "sourceHz": heard["sourceHz"],
+ "shiftSemitones": round(12 * (heard["move"] or 0.0) / float(np.log(2)) + a.semitones, 2),
+ }} if follow else {}),
}))
return 0
diff --git a/settings.json.example b/settings.json.example
@@ -269,13 +269,16 @@
},
"convert": {
"engine": "openvoice",
- "target": "orpheus:zac"
+ "target": "orpheus:zac",
+ "pitch": "target",
+ "semitones": 0
},
"heavyEstimateMB": {
"deepfilternet": 400,
"rnnoise": 300,
"openvoice": 2000,
- "seed-vc": 3500
+ "seed-vc": 3500,
+ "seed-vc-f0": 6500
}
},
"generation": {
@@ -371,5 +374,10 @@
"probeServices": [
"rumble"
]
+ },
+ "lookouts": {
+ "enabled": false,
+ "afterSync": false,
+ "items": []
}
}
diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts
@@ -21,6 +21,9 @@ import { fitPostItem } from "@/lib/report/postFit.mjs";
import { itemReadVoice } from "@/lib/report/readVoice.mjs";
import { projectRedaction } from "@/lib/report/postRedaction.mjs";
import { spokenRead } from "umtool-report-to-video/post-redact";
+import { characterOf, convertTargetOf, narratorOf } from "umtool-report-to-video/cast";
+import { castForProject } from "@/lib/report/castStore.mjs";
+import { derivePitchOf, deriveRefusalOf, stepPitchOf } from "@/lib/report/derivePitch.mjs";
export const dynamic = "force-dynamic";
@@ -41,10 +44,15 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?.
// POST {project, op: "take", id, note?, voice?, engine?, speed?, script?}
// a new take asked of the EDITOR's tts op (a job)
// POST {project, op: "fit", id, linger?} the attachment's best part for the read (posts fit)
-// POST {project, op: "derive", id, from, op2: enhance|convert, engine?, voice?}
+// GET ?project&id&convert=1 what a convert of this post defaults to: its author's character in
+// the cast (else the narrator) and that character's convert
+// target -- {character, convert: {engine, voice, pitch?, semitones?}}
+// POST {project, op: "derive", id, from, op2: enhance|convert, engine?, voice?, pitch?, semitones?}
// a NEW take made from take `from` by the editor's voice op
-// (a job; kept by GET ?job&derive=<from>); `installed: false`
-// when the editor has no engine for it
+// (a job; kept by GET ?job&derive=<from>[&pitch&semitones]);
+// `installed: false` when the editor has no engine for it. A
+// convert's `pitch` (target | source | contour) and `semitones`
+// are the pitch the read lands on (lib/report/derivePitch.mjs)
// POST {project, op: "delete", id, take} a take out of the list, its file to .trash/ (soft)
// POST {project, op: "reread", id, without?, dropParts?, dropUrls?} the picked take RE-JOINED without a piece
// POST {project, op: "reread", id, tempo: "4-16=1.35", stretch?} its parts RE-TIMED (no TTS); {…, yell: true, yellGain?, yellStyle?}: its caps raised
@@ -77,6 +85,14 @@ export async function GET(request: Request) {
const render = (m.render ?? {}) as Record<string, unknown>;
const id = q.get("id");
const job = q.get("job");
+ if (id && !job && q.get("convert") !== null) {
+ // What a convert of this post defaults to (`posts narrate --recording`'s rule: the author's character, else the narrator).
+ const e = postsOf(m).find((x) => x.id === id);
+ if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 });
+ const { cast } = await castForProject(r.project.dir);
+ const c = characterOf(cast, String((e as { handle?: unknown }).handle ?? "")) ?? narratorOf(cast);
+ return Response.json({ character: c ? { id: c.id, name: c.name } : null, convert: c ? convertTargetOf(c) : null }, { headers: noStore });
+ }
if (id && job) {
// A GET that WRITES the manifest (a job followed to done): the proxy passes reads, so an <img> on another site
// could ask it; refused cross-site here (lib/report/sameOrigin.mjs).
@@ -109,13 +125,16 @@ export async function GET(request: Request) {
if (!from) return Response.json({ state: "failed", error: `no take ${derive}` }, { headers: noStore });
const op = String(q.get("op") ?? "");
// The editor's defaults, when the ask named none (its `@@voice-result` line).
- const vr = resultLine<{ engine?: string; voice?: string }>(st.tail, "@@voice-result ") ?? {};
+ const vr = resultLine<{ engine?: string; voice?: string; pitch?: string; semitones?: number }>(st.tail, "@@voice-result ") ?? {};
+ // The pitch it landed on, as the editor ran it (else as it was asked); the target's own is not recorded.
+ const asked = derivePitchOf({ pitch: q.get("pitch"), semitones: q.get("semitones") });
+ const pitched = op === "convert" ? stepPitchOf(asked.ok ? asked.value : {}, vr) : {};
const engine = q.get("engine") ?? vr.engine ?? null;
const voice = op === "convert" ? (q.get("voice") ?? vr.voice ?? null) : null;
const partsRel = rel.replace(/\.wav$/, ".parts");
const derived = {
file: rel, engine: "derived", voice: (voice ? voice.split(":").pop() : null) ?? from.voice ?? "?", seconds: meas.seconds, source: { kind: "take", from: takeIdOf(from) },
- steps: [{ op, ...(engine ? { engine } : {}), ...(voice ? { voice } : {}), ranAt: new Date().toISOString(), job }],
+ steps: [{ op, ...(engine ? { engine } : {}), ...(voice ? { voice } : {}), ...pitched, ranAt: new Date().toISOString(), job }],
script: from.script ?? script, at: new Date().toISOString(), jobId: job, ...(Number.isFinite(meas.lufs) ? { lufs: meas.lufs } : {}),
...(Array.isArray(from.parts) ? { parts: from.parts.map((p) => ({ ...p, file: `${partsRel}/p${String(p.n).padStart(2, "0")}.wav` })) } : {}),
};
@@ -250,6 +269,9 @@ async function postHere(request: Request) {
if (!(POST_DERIVE_OPS as readonly string[]).includes(op)) return Response.json({ error: `op2 is one of ${POST_DERIVE_OPS.join(", ")}` }, { status: 400 });
const engine = body.engine ? String(body.engine) : null;
const voice = body.voice ? String(body.voice) : null;
+ // A convert's pitch (target | source | contour) and semitones, checked here; the editor refuses what its engine cannot do.
+ const pitched = derivePitchOf({ pitch: body.pitch, semitones: body.semitones }, op);
+ if (!pitched.ok) return Response.json({ error: pitched.error }, { status: 400 });
const pid = postIdOf(e);
const dir = path.join(r.project.dir, ...takesDirOf(pid).split("/"));
await mkdir(dir, { recursive: true });
@@ -261,15 +283,15 @@ async function postHere(request: Request) {
: null;
try {
// `voice` is the convert op's stock target; enhance takes none.
- const jobId = await startJob(POST_DERIVE_ROUTES[op as keyof typeof POST_DERIVE_ROUTES], { file: abs(t.file), out: abs(rel), ...(engine ? { engine } : {}), ...(voice && op === "convert" ? { voice } : {}), ...(parts ? { parts } : {}) });
- return Response.json({ ok: true, jobId, file: rel, from, op: op, engine, voice }, { headers: noStore });
+ const jobId = await startJob(POST_DERIVE_ROUTES[op as keyof typeof POST_DERIVE_ROUTES], { file: abs(t.file), out: abs(rel), ...(engine ? { engine } : {}), ...(voice && op === "convert" ? { voice } : {}), ...pitched.value, ...(parts ? { parts } : {}) });
+ return Response.json({ ok: true, jobId, file: rel, from, op: op, engine, voice, ...pitched.value }, { headers: noStore });
} catch (err) {
const status = (err as { status?: number }).status ?? 502;
const msg = err instanceof Error ? err.message : String(err);
// The editor has no engine for it (an older editor has no route; a newer one names the setup to run): say so, plainly, with its words.
- if (status === 404 || /not installed|no engine|unknown|not found|404/i.test(msg)) {
- return Response.json({ ok: false, installed: false, error: `the editor has no ${op} engine installed (not installed: ${msg.replace(/^the editor refused it: /, "")})` }, { status: 200, headers: noStore });
- }
+ // A missing optional model (`… --with f0`) is passed through in the editor's words (derivePitch.mjs deriveRefusalOf).
+ const refusal = deriveRefusalOf(op, status, msg);
+ if (refusal) return Response.json({ ok: false, ...refusal }, { status: 200, headers: noStore });
return Response.json({ error: msg }, { status });
}
}
diff --git a/umtool/app/api/report/voices/route.ts b/umtool/app/api/report/voices/route.ts
@@ -32,7 +32,7 @@ export const dynamic = "force-dynamic";
// POST { project, op: "use", who, voice, scope: "project" | "cast" } umtool cast use <p> <who> <voice> [--everywhere]
// POST { project, op: "reread", who } QUEUED: one `posts narrate … --take [--thread …]` step per item
// whose picked read says them in another voice (the argv built here)
-// POST { project, op: "cast-rm", id } | { op: "cast-undo" } | { op: "cast-set", id, convertEngine?, narrator? }
+// POST { project, op: "cast-rm", id } | { op: "cast-undo" } | { op: "cast-set", id, convertEngine?, convertPitch?, convertSemitones?, narrator? }
// POST multipart { project, op: "recording", item, as?, clean?, convert?, file } a JOB: posts narrate <p> <item>
// --recording <file> (kept, cleaned, converted to a STOCK voice)
const headers = { "cache-control": "no-store" };
@@ -169,6 +169,9 @@ export async function POST(request: Request) {
if (op === "cast-set") {
const args = ["set", s("id")];
if (s("convertEngine")) args.push("--convert-engine", s("convertEngine"));
+ // The pitch a converted read lands on (castCli.mjs refuses what makes no sense).
+ if (s("convertPitch")) args.push("--convert-pitch", s("convertPitch"));
+ if (typeof b.convertSemitones === "number" || s("convertSemitones")) args.push("--convert-semitones", String(b.convertSemitones ?? s("convertSemitones")));
if (b.narrator === true || s("narrator") === "on") args.push("--narrator");
if (b.narrator === false || s("narrator") === "off") args.push("--no-narrator");
if (s("name")) args.push("--name", s("name"));
diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx
@@ -7,6 +7,7 @@ import Waveform from "@/components/Waveform";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { postBenchHref } from "@/lib/hrefs";
+import { CAST_CONVERT_ENGINES, CAST_CONVERT_PITCH, CAST_PITCH_ENGINES, CAST_SEMITONES_MAX, convertPitchLabel } from "umtool-report-to-video/cast";
import { POST_DERIVE_OPS, POST_NARRATION_DEFAULTS, mixPhaseAt, pickedTake, postNarrationKnobs, scriptParts, takeIdOf, takeSourceOf } from "umtool-report-to-video/post-narration";
import { projectFileMedia } from "./bench/benchMedia";
import { usePeaks } from "./bench/usePeaks";
@@ -37,7 +38,15 @@ import PostAttachmentLane from "./PostAttachmentLane";
// `umtool posts narrate` runs; the bench takes the entry it returns.
// ---------------------------------------------------------------------------
-type Step = { op: string; engine?: string; voice?: string };
+// A derived take's step. A convert's `pitch` / `semitones`: the pitch the converted read lands on (knobs.md, "The
+// pitch a converted read lands on") -- absent for the stock voice's own.
+type Step = { op: string; engine?: string; voice?: string; pitch?: string; semitones?: number };
+// The engines whose convert can FOLLOW the read's pitch (cast.mjs CAST_PITCH_ENGINES), and the modes in plain words.
+const PITCH_WORDS: Record<string, string> = {
+ target: "the stock voice's own pitch",
+ source: "follow my pitch",
+ contour: "my intonation, at the voice's register",
+};
type Take = { file: string; engine?: string; voice?: string; seconds: number; note?: string; script?: string; label?: string; source?: { kind: string; from?: string; voice?: string; engine?: string }; steps?: Step[]; parts?: Array<{ n: number; para?: number; text?: string; start: number; seconds: number; file?: string }>; words?: Array<{ w: string; start: number; end: number }> };
type Narration = { script?: string; takes?: Take[]; pick?: number; approved?: boolean; off?: boolean; window?: { media: number; start: number; end: number; score?: number; reason?: string } } & Record<string, unknown>;
type Entry = Record<string, unknown> & { id: string; narration?: Narration; media?: Array<Record<string, unknown> & { src: string; kind: string; seconds?: number; start?: number; end?: number }> };
@@ -212,20 +221,20 @@ export default function PostNarrationPanel({
// ---- a re-take with direction (the editor's tts op) --------------------------
const [dir, setDir] = useState({ note: "", voice: "", speed: "" });
- const [job, setJob] = useState<{ id: string; file: string; note: string; script: string; state: string; error?: string; polls?: number; derive?: { from: number; op: string; engine?: string | null; voice?: string | null } } | null>(null);
+ const [job, setJob] = useState<{ id: string; file: string; note: string; script: string; state: string; error?: string; polls?: number; derive?: { from: number; op: string; engine?: string | null; voice?: string | null; pitch?: string | null; semitones?: number | null } } | null>(null);
// Derived takes still to make after a re-record ("re-run the chain"), from the new take.
const [chain, setChain] = useState<Array<{ from: number; step: Step }>>([]);
const [rerunChain, setRerunChain] = useState(true);
const [notInstalled, setNotInstalled] = useState<string | null>(null);
const derive = async (from: number, step: Step) => {
setNotInstalled(null);
- const j = (await post({ op: "derive", from, op2: step.op, engine: step.engine || undefined, voice: step.voice || undefined })) as ({ jobId?: string; file?: string; installed?: boolean; error?: string } & Record<string, unknown>) | null;
+ const j = (await post({ op: "derive", from, op2: step.op, engine: step.engine || undefined, voice: step.voice || undefined, ...(step.op === "convert" && step.pitch ? { pitch: step.pitch, ...(typeof step.semitones === "number" ? { semitones: step.semitones } : {}) } : {}) })) as ({ jobId?: string; file?: string; installed?: boolean; error?: string } & Record<string, unknown>) | null;
if (j && j.installed === false) {
setNotInstalled(j.error ?? `the editor has no ${step.op} engine yet`);
setChain([]);
return;
}
- if (j?.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: "", script, state: "running", derive: { from, op: step.op, engine: step.engine ?? null, voice: step.voice ?? null } });
+ if (j?.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: "", script, state: "running", derive: { from, op: step.op, engine: step.engine ?? null, voice: step.voice ?? null, pitch: step.pitch ?? null, semitones: step.semitones ?? null } });
};
const retake = async () => {
const j = await post({ op: "take", note: dir.note || undefined, voice: dir.voice || undefined, speed: dir.speed ? Number(dir.speed) : undefined, script });
@@ -236,7 +245,7 @@ export default function PostNarrationPanel({
const t = setTimeout(async () => {
const q = new URLSearchParams({
project, id: entry.id, job: job.id, file: job.file, script: job.script, ...(job.note ? { note: job.note } : {}),
- ...(job.derive ? { derive: String(job.derive.from), op: job.derive.op, ...(job.derive.engine ? { engine: job.derive.engine } : {}), ...(job.derive.voice ? { voice: job.derive.voice } : {}) } : {}),
+ ...(job.derive ? { derive: String(job.derive.from), op: job.derive.op, ...(job.derive.engine ? { engine: job.derive.engine } : {}), ...(job.derive.voice ? { voice: job.derive.voice } : {}), ...(job.derive.pitch ? { pitch: job.derive.pitch } : {}), ...(typeof job.derive.semitones === "number" ? { semitones: String(job.derive.semitones) } : {}) } : {}),
});
const r = await fetch(`/api/report/post-narration?${q}`, { cache: "no-store" });
const j = (await r.json().catch(() => ({}))) as { state?: string; error?: string; entry?: Entry; token?: string };
@@ -279,7 +288,47 @@ export default function PostNarrationPanel({
roots.forEach((i) => walk(i, 0));
return { rows: out, kids };
}, [takes]);
- const [deriveDraft, setDeriveDraft] = useState<{ op: string; engine: string; voice: string }>({ op: "enhance", engine: "", voice: "" });
+ const [deriveDraft, setDeriveDraft] = useState<{ op: string; engine: string; voice: string; pitch: string; semitones: string }>({ op: "enhance", engine: "", voice: "", pitch: "target", semitones: "" });
+ // What a convert of THIS post defaults to: its author's character in the cast (else the narrator) -- the engine, the
+ // stock voice and the pitch every recording made that character's lands on (`umtool cast set <id> --convert-pitch …`).
+ const [castConvert, setCastConvert] = useState<{ name: string; engine?: string | null; voice?: string | null; pitch?: string; semitones?: number } | null>(null);
+ useEffect(() => {
+ let live = true;
+ setCastConvert(null);
+ fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&convert=1`, { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j: { character?: { name: string } | null; convert?: { engine?: string | null; voice?: string | null; pitch?: string; semitones?: number } | null } | null) => {
+ if (live && j?.character && j.convert) setCastConvert({ name: j.character.name, ...j.convert });
+ })
+ .catch(() => {});
+ return () => {
+ live = false;
+ };
+ }, [project, entry.id]);
+ // Choosing the op: a convert starts from the character's entry (its engine and voice only where the field is
+ // empty); an enhance drops a convert engine left in the field.
+ const chooseDeriveOp = (op: string) =>
+ setDeriveDraft((d) =>
+ op !== "convert"
+ ? { ...d, op, engine: (CAST_CONVERT_ENGINES as readonly string[]).includes(d.engine.trim()) ? "" : d.engine }
+ : {
+ op,
+ engine: d.engine || castConvert?.engine || "",
+ voice: d.voice || castConvert?.voice || "",
+ pitch: castConvert?.pitch ?? "target",
+ semitones: castConvert?.semitones ? String(castConvert.semitones) : "",
+ },
+ );
+ // The pitch controls are an engine's that can follow one; without it the convert lands on the stock voice's own.
+ const derivePitched = deriveDraft.op === "convert" && (CAST_PITCH_ENGINES as readonly string[]).includes(deriveDraft.engine.trim());
+ const deriveSemitones = Number(deriveDraft.semitones || 0);
+ const deriveSemitonesBad = derivePitched && deriveDraft.pitch !== "target" && !(Number.isFinite(deriveSemitones) && Math.abs(deriveSemitones) <= CAST_SEMITONES_MAX);
+ const deriveStep = (): Step => ({
+ op: deriveDraft.op,
+ ...(deriveDraft.engine.trim() ? { engine: deriveDraft.engine.trim() } : {}),
+ ...(deriveDraft.op === "convert" && deriveDraft.voice.trim() ? { voice: deriveDraft.voice.trim() } : {}),
+ ...(derivePitched ? { pitch: deriveDraft.pitch, ...(deriveDraft.pitch !== "target" ? { semitones: deriveSemitones } : {}) } : {}),
+ });
// ---- the lanes ------------------------------------------------------------------
// One lane per timed attachment (a video, a GIF), its in and out the bench's draft (onTrim).
@@ -589,7 +638,7 @@ export default function PostNarrationPanel({
<div className="flex flex-wrap items-center gap-2">
<span className="font-mono">{depth ? "└ " : ""}#{i + 1}</span>
<span>
- {src.kind === "recorded" ? `recorded · ${src.voice ?? t.voice ?? "?"}` : src.kind === "take" ? `${step?.op ?? "derived"}${step?.engine ? ` · ${step.engine}` : ""}${step?.voice ? ` → ${step.voice}` : ""}` : `${t.engine ?? "?"} · ${t.voice ?? "?"}`}
+ {src.kind === "recorded" ? `recorded · ${src.voice ?? t.voice ?? "?"}` : src.kind === "take" ? `${step?.op ?? "derived"}${step?.engine ? ` · ${step.engine}` : ""}${step?.voice ? ` → ${step.voice}` : ""}${convertPitchLabel(step) ? ` · pitch: ${convertPitchLabel(step)}` : ""}` : `${t.engine ?? "?"} · ${t.voice ?? "?"}`}
</span>
<span className="tabular-nums">{Number(t.seconds).toFixed(1)} s</span>
{/* eslint-disable-next-line jsx-a11y/media-has-caption */}
@@ -642,7 +691,7 @@ export default function PostNarrationPanel({
{picked && (
<div className="flex flex-wrap items-center gap-1.5" data-post-derive="">
<span className="micro">run AI on take #{picked.index + 1}</span>
- <select value={deriveDraft.op} onChange={(e) => setDeriveDraft({ ...deriveDraft, op: e.target.value })} data-post-derive-op="">
+ <select value={deriveDraft.op} onChange={(e) => chooseDeriveOp(e.target.value)} data-post-derive-op="">
{POST_DERIVE_OPS.map((o) => (
<option key={o} value={o}>
{o === "enhance" ? "enhance (denoise, level)" : "convert (to a stock synthetic voice)"}
@@ -653,7 +702,30 @@ export default function PostNarrationPanel({
{deriveDraft.op === "convert" && (
<input value={deriveDraft.voice} onChange={(e) => setDeriveDraft({ ...deriveDraft, voice: e.target.value })} placeholder="stock voice" className="w-24 rounded border border-seam bg-ground px-1 py-0.5" data-post-derive-voice="" />
)}
- <button type="button" className={btn} disabled={job?.state === "running"} onClick={() => void derive(picked.index, { op: deriveDraft.op, ...(deriveDraft.engine ? { engine: deriveDraft.engine } : {}), ...(deriveDraft.voice ? { voice: deriveDraft.voice } : {}) })} data-post-derive-run="">
+ {derivePitched && (
+ <label className="flex items-center gap-1" title="where the converted read's pitch comes from: the stock voice's own (your intonation is flattened to it), the pitch you read at, or your rises and falls moved to the stock voice's register">
+ <span className="micro">pitch</span>
+ <select value={deriveDraft.pitch} onChange={(e) => setDeriveDraft({ ...deriveDraft, pitch: e.target.value })} aria-label="the pitch the converted read lands on" data-post-derive-pitch="">
+ {CAST_CONVERT_PITCH.map((p) => (
+ <option key={p} value={p}>
+ {PITCH_WORDS[p] ?? p}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ {derivePitched && deriveDraft.pitch !== "target" && (
+ <label className="flex items-center gap-1" title={`moves the followed pitch up or down, in semitones (-${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX}); 0: as followed`}>
+ <input type="number" min={-CAST_SEMITONES_MAX} max={CAST_SEMITONES_MAX} step={0.5} value={deriveDraft.semitones} onChange={(e) => setDeriveDraft({ ...deriveDraft, semitones: e.target.value })} placeholder="0" aria-label="semitones the followed pitch is moved by" aria-invalid={deriveSemitonesBad || undefined} className="w-14 rounded border border-seam bg-ground px-1 py-0.5" data-post-derive-semitones="" />
+ <span className="micro">semitones</span>
+ </label>
+ )}
+ {deriveDraft.op === "convert" && castConvert && (
+ <span className="micro text-text-2" data-post-derive-cast="">
+ {castConvert.name}'s in the cast: {[castConvert.engine, castConvert.voice, convertPitchLabel(castConvert) ? `pitch ${convertPitchLabel(castConvert)}` : null].filter(Boolean).join(" · ")}
+ </span>
+ )}
+ <button type="button" className={btn} disabled={job?.state === "running" || deriveSemitonesBad} onClick={() => void derive(picked.index, deriveStep())} data-post-derive-run="">
Run → a new take
</button>
{notInstalled && (
diff --git a/umtool/components/projects/VoicesPanel.tsx b/umtool/components/projects/VoicesPanel.tsx
@@ -26,13 +26,24 @@ type Voice = { engine: string; voice: string; spec: string; from: string };
type Drift = { id: string; handle: string; role: string; reads: string; want: string; from: string | null; kind: string; thread: boolean };
type Character = {
key: string; name: string; handles: string[];
- character: { id: string; name: string; voice: string; convert?: { engine?: string; voice?: string }; note?: string; narrator?: boolean } | null;
+ character: { id: string; name: string; voice: string; convert?: Convert; note?: string; narrator?: boolean } | null;
items: number; context: number; itemIds: string[]; contextIds: string[];
voice: Voice; contextVoice?: Voice; weight: string;
reads: { id: string; role: string; spec: string; kind: string }[];
drift: Drift[]; speaker: string | null; lines: { item: string; text: string; own: boolean }[];
};
-type CastChar = { id: string; name: string; handles?: string[]; voice: string; convert?: { engine?: string; voice?: string }; speakers?: string[]; note?: string; narrator?: boolean };
+// What a recording of the character is made into: the stock voice, the engine, and the pitch the converted read
+// lands on (`umtool cast set <id> --convert-pitch source|contour|target --convert-semitones n`).
+type Convert = { engine?: string; voice?: string; pitch?: "target" | "source" | "contour"; semitones?: number };
+type CastChar = { id: string; name: string; handles?: string[]; voice: string; convert?: Convert; speakers?: string[]; note?: string; narrator?: boolean };
+
+/** A convert entry's pitch in words — "follows your pitch", "your intonation at the voice's register +2 st" — "" for the stock voice's own. */
+function pitchWords(cv?: Convert): string {
+ if (!cv?.pitch || cv.pitch === "target") return "";
+ const n = Number(cv.semitones) || 0;
+ const st = n ? ` ${n > 0 ? "+" : "−"}${Math.abs(n)} st` : "";
+ return cv.pitch === "source" ? `follows your pitch${st}` : `your intonation at the voice's register${st}`;
+}
type Engine = { id: string; label: string; voices: string[]; defaultVoice: string; weight: string };
type View = {
project: string; castFile: string | null; castError?: string; map: Record<string, string>;
@@ -527,7 +538,7 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
<option value="">as: the post's author (else the narrator)</option>
{view.cast.map((c) => (
<option key={c.id} value={c.id}>
- as {c.name} ({pretty(c.convert?.voice ?? c.voice)})
+ as {c.name} ({pretty(c.convert?.voice ?? c.voice)}{pitchWords(c.convert) ? `, ${pitchWords(c.convert)}` : ""})
</option>
))}
</select>
@@ -580,6 +591,11 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
<td className={cn(cell, "font-mono")}>{pretty(c.voice)}</td>
<td className={cn(cell, "text-[11px] text-text-2")}>
{c.convert ? `a recording → ${pretty(c.convert.voice ?? c.voice)}${c.convert.engine ? ` (${c.convert.engine})` : ""}` : ""}
+ {pitchWords(c.convert) && (
+ <span data-cast-pitch={c.id} title={`the pitch a converted read lands on: ${c.convert?.pitch}${c.convert?.semitones ? `, ${c.convert.semitones} semitones` : ""} — umtool cast set ${c.id} --convert-pitch target|source|contour --convert-semitones <n>`}>
+ {` · pitch: ${pitchWords(c.convert)}`}
+ </span>
+ )}
{c.speakers?.length ? ` · real voice: ${c.speakers.join(", ")}` : ""}
{c.note ? ` · ${c.note}` : ""}
</td>
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -22,7 +22,7 @@ Inbox cannot disagree about what is wrong with one.
| `check [<project>] [--json]` | **exit 1 on anything blocking** — including an `out/`, `clips/` or `share-*/` link whose drive is not there (`storage-unreachable`) |
| `links <project> --embed-ids [--clips a,b] [--dry-run] [--json]` | the **published embed id**: every clip citing a Rumble URL-slug folder the archive does not serve gets `siteVideo` (the folder's `metadata.info.json` id, shareLine.mjs `siteVideoFor`), a citeUrl naming the folder moved with it; no network, one write, one undo point. The Cut tab's Project › Rumble cites ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) |
| `links <project> [--json] [--fix]` | do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`, and a Rumble folder id (the URL slug) as the embed id the site serves (the clip gets `siteVideo`); **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on)) |
-| `cast [ls] \| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--narrator] \| set <id> … \| rm <id> \| undo [--json]` | **THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write |
+| `cast [ls] \| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--convert-pitch target\|source\|contour] [--convert-semitones n] [--narrator] \| set <id> … \| rm <id> \| undo [--json]` | **THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write. A character's `convert` entry is what a recording of them is made into: the stock voice, the engine, and the **pitch** the converted read lands on (`--convert-pitch`: `target` the stock voice's own, `source` the pitch it was read at, `contour` the read's rises and falls at the stock voice's register; `--convert-semitones` -12…12 moves a followed one; `set` lays the flags given over the entry). A followed pitch on an engine that has none, or semitones with nothing followed: **exit 1** |
| `cast project <project> [--json]` · `cast use <project> <character\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]` | a project's characters (each voice now, where it comes from, its stale reads), the voice for this project or everywhere, and the re-reads that asks for |
| `cast audition <character\|@handle> --voices a,b,… [--project <p>] [--text "…" \| --item <id> \| --line <n> \| --stock] [--no-score \| --score-only] [--json] [--progress ndjson]` | **AN AUDITION**: one line read by 2-6 stock voices through the editor's tts op, levelled to -20 LUFS in `<p>/narration/auditions/` (cached), scored for closeness to the character's real voice (`speakers.json`; TitaNet, local) |
| `speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]` · `--set 'Name=<clip>,<channel>/<id>,channel:<slug>'` · `--remove <name>` · `--list` | which of the project's **named voices** (`speakers.json`) each clip is: TitaNet-small, local, against each voice's robust centroid → `<project>/speaker-check.json` (merged); the walk's **Speaker:** badge and **Check speaker** ([report-video.md](report-video.md#the-speaker-check-on-the-walk-which-of-several-voices)) |
@@ -133,7 +133,7 @@ Inbox cannot disagree about what is wrong with one.
| `posts narrate <project> <item> --take --thread [--parents 0\|all\|none\|<n>] [--skip-parent <id\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--note "…"] [--force] [--no-hold] [--dry-run] [--json]` | a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the project's voice map, `posts voices`; his own: the narrator's), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2** |
| `posts say <project> [ls] [--item <id>]` · `add <word\|phrase> "<spoken>" [--case] [--item <id>] [--note "…"]` · `remove <word\|n> [--item <id>]` · `try "<text>" [--item <id>]` · `stale` `[--json]` | **THE PRONUNCIATION LEXICON** ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)): `narration/lexicon.json` in the project, a word or phrase said differently in EVERY synthesized read (a script's `--take`, each piece of a thread read, the bench's re-take); the scripts and cards keep their words. Whole words, without case unless `--case`, a phrase across any spaces, regex characters literal; `--item` for one item's reads (it wins over the project's). A masked slur and a redacted word are never replaced. `add` of a word already listed changes what is said. `try` prints what a voice would be asked to say. `stale` lists every picked read that still says an entry the old way, with the command that re-reads it. A bad entry or an unknown item: **exit 2** |
| `posts voices <project> [ls] \| set <handle\|*> <voice> \| remove <handle\|*> [--json]` | **THE VOICE MAP** (`narration/voices.json`): the stock voice a thread read gives each author (`*`: everyone it does not name; default `leo` on Orpheus); `ls` lists the map and every author the cut's items carry with the voice each would get. A bad handle or voice: **exit 2** |
-| `posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--label l]` | **a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked |
+| `posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--pitch target\|source\|contour] [--semitones n] [--label l]` · `<item> --derive <n> --op convert [--engine e] [--voice v] [--pitch …] [--semitones n]` | **a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked. **`--pitch`** is the pitch the converted read lands on ([knobs.md](knobs.md#the-pitch-a-converted-read-lands-on)): `target` the stock voice's own (the read's intonation flattened to it), `source` the pitch it was read at, `contour` the read's rises and falls moved to the stock voice's register; `--semitones` (-12…12) moves a followed one. Default: the character's `convert` entry, else the editor's `settings.voice.convert`. `source` and `contour` are seed-vc's, with its f0 model (`archilyzer voice setup --engine seed-vc --with f0`); what the editor cannot do it refuses in a sentence (**exit 1**); a value outside these, or a pitch on `--op enhance`: **exit 1** |
| `posts fx <project> <item> add caption --match "…" --text "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\|above\|side]` · `add clock [--rewind auto\|on\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]` | a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**) |
| `posts clock <project> [on\|off\|default] [--zone <IANA zone>] [--json]` | the cut's **clock** default (`render.posts.clock`, `updatePostClock`); bare, which items show it and their times |
| `posts fx <project> <item> add slam --text "不動心" [--match "…" \| --at s] [--whole \| --per-glyph] [--gap s] [--hold s] [--from-scale x] [--color #rrggbb] [--outline #rrggbb] [--outline-width px] [--place over-match\|center] [--size px] [--face jp\|sc\|tc\|kr] [--sfx trailer-hit\|off] [--volume x] [--swell \| --no-swell] [--bar "…" [--bar-style dark\|gold\|plain]]` · `set <n> [those flags; --bar off clears it]` | a post item's **slam** ([report-video.md](report-video.md#a-slam), [knobs.md](knobs.md#a-slam-a-trailer-style-title-slam-over-a-word-as-it-is-read)): a corny trailer title slam -- each glyph huge, shrinking onto the card just above the matched words' line and HITTING (a flash, dust, the frame's punch, a trailer hit's boom: the teaser's generator, `trailer-hits.mjs`), gold with a black outline; the hits spread evenly over the words' spoken span (`--gap` spaces them, `--at` moves the first), held `--hold` s; `--bar` lands the glyphs on a translation bar (rising in at the first hit, faded with them); a caption up with it waits for it. Through `updatePostFx`, refused in the build's words (**exit 1**); a slam's knob on another effect, or another's on a slam (**exit 2**) |
@@ -170,8 +170,8 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `still <project> <clip> --at N [--take TAKE]` | one frame of a clip's fetched window at a source second, into shots/ | form · *project* |
| `still <project> ls` | the pictures in the project's shots/ | form · *project* |
| `cast ls` | the characters' voices across projects | form · *corpus* |
-| `cast add <id> --name NAME --voice VOICE [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--note NOTE] [--narrator]` | a character: name, stock voice, handles | form · *corpus* |
-| `cast set <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--note NOTE] [--add-handle ADD-HANDLE] [--remove-handle REMOVE-HANDLE] [--no-convert] [--narrator] [--no-narrator]` | change a character | form · *corpus* |
+| `cast add <id> --name NAME --voice VOICE [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--convert-pitch target\|source\|contour] [--convert-semitones N] [--note NOTE] [--narrator]` | a character: name, stock voice, handles | form · *corpus* |
+| `cast set <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--convert-pitch target\|source\|contour] [--convert-semitones N] [--note NOTE] [--add-handle ADD-HANDLE] [--remove-handle REMOVE-HANDLE] [--no-convert] [--narrator] [--no-narrator]` | change a character | form · *corpus* |
| `cast rm <id>` | a character out of the cast (an undo point) | form · *corpus* |
| `cast undo` | the cast as it was before its last write | form · *corpus* |
| `cast project <project>` | the project's characters, their voices and drift | form · *project* |
@@ -349,7 +349,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `posts set <project> <post> key=value…` | the Posts table's writer: thread, hide, attach, crop | form · *draft* |
| `posts reel <project> --channel CHANNEL… [--since SINCE] [--until UNTIL] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after AFTER] [--dry-run]` | post items from posts channels, in one write | form · *draft* |
| `posts set-item <project> <item> key=value… [--in-take IN-TAKE]` | a post item's knobs | form · *draft* |
-| `posts narrate <project> [<item>] [key=value…] [--script SCRIPT] [--take] [--note NOTE] [--voice VOICE] [--engine ENGINE] [--speed N] [--pick N] [--approve] [--unapprove] [--off] [--on] [--thread] [--parents PARENTS] [--words] [--import] [--list] [--all] [--draft-scripts] [--limit N] [--force] [--recording RECORDING] [--as AS] [--dry-run] [--in-take IN-TAKE]` | a post item's narration: script, takes, pick, approve, mix | form · queued · *draft* |
+| `posts narrate <project> [<item>] [key=value…] [--script SCRIPT] [--take] [--note NOTE] [--voice VOICE] [--engine ENGINE] [--speed N] [--pick N] [--approve] [--unapprove] [--off] [--on] [--thread] [--parents PARENTS] [--words] [--import] [--list] [--all] [--draft-scripts] [--limit N] [--force] [--recording RECORDING] [--as AS] [--pitch target\|source\|contour] [--semitones N] [--dry-run] [--in-take IN-TAKE]` | a post item's narration: script, takes, pick, approve, mix | form · queued · *draft* |
| `posts say <project> ls\|add\|remove\|try\|stale [<word>] [<spoken>] [--case] [--item ITEM] [--note NOTE]` | the pronunciation lexicon | form · *draft* |
| `posts voices <project> ls\|set\|remove [<handle>] [<voice>]` | the voice map a thread read uses | form · *draft* |
| `posts fit <project> [<items>…] [--all] [--linger N] [--dry-run]` | narrated posts' videos cut to their best part | form · queued · *draft* |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -1168,7 +1168,7 @@ the shape, the mix, recordings, parts, the best part). One writer for a post's n
| a recorded take — your own read, part by part, kept as `take-<n>.recorded-<label>.wav`, picked | post bench, **record your read**: the mic, the level, **Record** (R) / **Stop** (S) / **Redo part** / **Next part**, **Keep** / **Discard**, **voice** (the label, default `operator`) | — | `POST` multipart `{project, id, label, script?, part[], text[], para[]}` |
| a synthesized take — the editor's tts op, with direction | post bench, **Re-take with direction** (a note, a voice) | `umtool posts narrate <p> <item> --take [--note "…"] [--voice v] [--engine e] [--speed s]` · every missing one: `--all --take` | `op: "take"` → `{jobId, file}` · `GET ?project&id&job&file` keeps it when done |
| a THREAD READ — the post it answers (or every ancestor), the post it quotes, the linked posts and his words, each in its author's voice, parts cached, one take picked ([below](#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)) | — | `umtool posts narrate <p> <item> --take --thread [--parents 0\|all] [--skip-parent <id>]… [--voice-for <handle>=<voice>]… [--dry-run] [--json]` | — |
-| a derived take — a take run through the editor's `enhance` or `convert` (a stock synthetic voice: `zac`, `leah`, `orpheus:zac`, never a recording) into a NEW take, the original kept; enhance engines `deepfilternet` · `rnnoise`, convert `openvoice` · `seed-vc` (unnamed: the editor's settings.voice, recorded on the take); "not installed" until `archilyzer voice setup --engine <id>` | post bench, **run AI on take #n** (the op, an engine, a stock voice) → **Run → a new take**; a derived take's **Re-run**; a recording's **Re-record** with **then re-run the chain** | `umtool posts narrate <p> <item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` | `op: "derive", from, op2, engine?, voice?` → `{jobId, file}` (or `{installed: false}`) · `GET ?project&id&job&file&derive=<from>&op=…` keeps it |
+| a derived take — a take run through the editor's `enhance` or `convert` (a stock synthetic voice: `zac`, `leah`, `orpheus:zac`, never a recording) into a NEW take, the original kept; enhance engines `deepfilternet` · `rnnoise`, convert `openvoice` · `seed-vc` (unnamed: the editor's settings.voice, recorded on the take); "not installed" until `archilyzer voice setup --engine <id>`; a convert's **pitch** ([below](#the-pitch-a-converted-read-lands-on)) | post bench, **run AI on take #n** (the op, an engine, a stock voice; for a convert on `seed-vc`, **pitch** and **semitones**) → **Run → a new take**; a derived take's **Re-run**; a recording's **Re-record** with **then re-run the chain** | `umtool posts narrate <p> <item> --derive <n> --op enhance\|convert [--engine e] [--voice v] [--pitch target\|source\|contour] [--semitones n]` | `op: "derive", from, op2, engine?, voice?, pitch?, semitones?` → `{jobId, file}` (or `{installed: false}`) · `GET ?project&id&job&file&derive=<from>&op=…` keeps it |
| delete a take (soft: its file to the post's `.trash/`) | post bench, the take's **Delete** | `--delete <n>` | `op: "delete", take` (an index) |
| `narration.pick` — the take that plays | post bench, the take's **Pick** | `--pick <n>` (1 = the first, as `--list` shows) | `patch: {pick}` (an index) |
| `narration.approved` — the picked take on this script, approved (a new script or pick takes it away) | post bench, **approved** | `--approve` · `--unapprove` | `patch: {approved: true \| null}` |
@@ -1320,7 +1320,8 @@ different ones to compare … and try to maintain consistent voices for differen
`castWrite` -- a token, an undo point a write, a broken file never overwritten): the CHARACTERS that recur across
projects -- `{id, name, handles, voice, convert?, speakers?, avatar?, note?, narrator?}`. `voice` is a STOCK voice
with its engine (`kokoro:am_michael`, `orpheus:zac`); `convert` the voice (and engine, openvoice | seed-vc) a
-recording of them is converted to (default: `voice`); `speakers` the names their REAL voice goes by in a project's
+recording of them is converted to (default: `voice`) and the **pitch** that converted read lands on (`pitch`,
+`semitones`: [below](#the-pitch-a-converted-read-lands-on)); `speakers` the names their REAL voice goes by in a project's
`speakers.json` -- a reference to compare a candidate with, never a target (the editor's convert op refuses a file;
the cast holds no path). One character may be the `narrator` (a recording's default character).
@@ -1349,12 +1350,12 @@ voice-convert) to the character's stock voice -- each a new take, the last picke
| Knob | In umtool | From a terminal | Route |
|---|---|---|---|
-| the cast -- `<reports>/.umtool/cast.json` | **Voices** (`/projects/<p>/voices`, from the Cut tab's Reads and voices): **the cast** list, ✕ removes, **Undo the last cast change**; an audition's **Use everywhere** adds or changes a character | `umtool cast ls` · `add <id> --name … --voice kokoro:am_michael --handles a,b [--speakers Jeremy] [--convert-engine seed-vc] [--convert-voice …] [--narrator]` · `set <id> …` (`--add-handle`, `--remove-handle`, `--no-convert`) · `rm <id>` · `undo` | `POST /api/report/voices {op: "cast-rm" \| "cast-undo" \| "cast-set"}` |
+| the cast -- `<reports>/.umtool/cast.json` | **Voices** (`/projects/<p>/voices`, from the Cut tab's Reads and voices): **the cast** list, ✕ removes, **Undo the last cast change**; an audition's **Use everywhere** adds or changes a character | `umtool cast ls` · `add <id> --name … --voice kokoro:am_michael --handles a,b [--speakers Jeremy] [--convert-engine seed-vc] [--convert-voice …] [--convert-pitch source\|contour\|target] [--convert-semitones n] [--narrator]` · `set <id> …` (`--add-handle`, `--remove-handle`, `--no-convert`) · `rm <id>` · `undo` | `POST /api/report/voices {op: "cast-rm" \| "cast-undo" \| "cast-set"}` |
| a project's characters -- each one's voice now and where it comes from, its reads, its drift, its real voice | **Voices**: the characters table | `umtool cast project <p> [--json]` | `GET /api/report/voices?project` |
| an audition | **Voices** → a character's **Audition**: the line, the candidates (engine, voice, Add), **Render** (a job: the editor's tts, then the closeness through the heavy slot), each played at one loudness, **▶ Play each in turn** (the real voice first) | `umtool cast audition <character\|@handle> --project <p> --voices kokoro:am_michael,kokoro:am_onyx,orpheus:zac [--text "…" \| --item <id> \| --line <n> \| --stock] [--no-score \| --score-only] [--json]` | `POST /api/report/voices {op: "audition", who, voices, text?, item?}` |
| the voice a character reads in -- this project, or everywhere | an audition's **Use for this project** / **Use everywhere** | `umtool cast use <p> <character\|@handle> <voice> [--everywhere]` (the project's own override goes with `--everywhere`) | `POST … {op: "use", who, voice, scope}` |
| the re-reads a voice change asks for | the confirm under the audition: the items, **Queue N re-reads** (steps of the queue: /jobs; each a new take, picked, awaiting approval) | `umtool cast reread <p> <character> [--dry-run]` | `POST … {op: "reread", who}` |
-| a recording made a character's read | **Voices** → *a recording*: the item, as whom, drop a file, clean / convert, **Import** (a job) | `umtool posts narrate <p> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert]` | `POST … multipart {op: "recording", item, as?, file}` |
+| a recording made a character's read | **Voices** → *a recording*: the item, as whom, drop a file, clean / convert, **Import** (a job) | `umtool posts narrate <p> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--pitch …] [--semitones n]` | `POST … multipart {op: "recording", item, as?, file}` |
```sh
umtool cast add thequartering --name TheQuartering --voice kokoro:am_michael --handles thequartering --speakers Jeremy
@@ -1365,6 +1366,37 @@ umtool cast reread quartering-diet thequartering # each stale read m
umtool posts narrate quartering-diet <item> --recording my-read.wav --as thequartering
```
+### The pitch a converted read lands on
+
+A converter given no pitch speaks every read at the STOCK voice's own: measured 11 Nov, reads with a median pitch of
+128 to 237 Hz all came out at 196-199 Hz and a 152-321 Hz range came out as 165-240 Hz -- raising your voice for a
+character, and most of your intonation, was thrown away. A convert's **pitch** says where the result's pitch comes
+from (the editor's `voice-convert`: `pitch`, `semitones`):
+
+- **`target`** -- the stock voice's own pitch, as before. Either engine; the default until a character or
+ `settings.voice.convert.pitch` says otherwise.
+- **`source`** -- the pitch you read at, as you read it: raise your voice and the result rises, drop it and it drops.
+ For a read ACTED at the character's pitch.
+- **`contour`** -- your rises and falls, moved as a whole so their median sits on the stock voice's median: read in
+ your ordinary voice, and the character speaks in its own register with your intonation.
+- **`semitones`** (-12 to 12) then moves a followed pitch (`source`, `contour`) up or down. With `target` it is
+ refused: nothing is followed to move. A convert that names a followed pitch and no semitones takes
+ `settings.voice.convert.semitones` (0 unless set).
+
+`source` and `contour` are **seed-vc's**, on its f0-conditioned model -- optional files, `archilyzer voice setup
+--engine seed-vc --with f0` (1.49 GB); it takes about 1.7 times as long as seed-vc at the target's pitch. openvoice has one
+pitch and refuses another; a followed pitch without the f0 files is refused naming that command. A parted take's
+`contour` is measured once, on the whole take, and used for every part.
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| a character's convert pitch -- `convert.pitch`, `convert.semitones` in the cast: what every recording made that character's lands on | **Voices**: the cast row says it ("pitch: follows your pitch +2 st"), and the recording form's *as …* choice | `umtool cast set <id> --convert-engine seed-vc --convert-pitch source\|contour\|target [--convert-semitones n]` (the flags given are laid over the entry; `--no-convert` clears it) | `POST /api/report/voices {op: "cast-set", id, convertPitch?, convertSemitones?}` |
+| one read's pitch -- this conversion only, over the character's | post bench, **run AI on take #n** → *convert*, engine `seed-vc`: **pitch** (the stock voice's own pitch · follow my pitch · my intonation, at the voice's register) and **semitones**, starting from the post author's character in the cast (else the narrator), which the row names; a converted take's row says its pitch, and **Re-run** keeps it | `umtool posts narrate <p> <item> --recording <file> [--as <character>] --pitch source\|contour\|target [--semitones n]` · `--derive <n> --op convert --engine seed-vc [--voice v] --pitch … [--semitones n]` | `POST /api/report/post-narration {op: "derive", …, pitch?, semitones?}` · `GET …?project&id&convert=1` (the character's default) · the editor's `POST /api/ops/voice-convert {…, pitch?, semitones?}` |
+| the default for every conversion that names none | — | `settings.voice.convert.pitch`, `.semitones` ([SETTINGS.md](../../SETTINGS.md)) | — |
+
+A converted take's step keeps the pitch it was run at (`steps: [{op: "convert", engine, voice, pitch, semitones}]`),
+so `--list` and a re-run say it; the target's own pitch is not recorded.
+
## A caption (a chip explaining a phrase as it is read)
`fx: [{kind: "caption", match, text, …}]` on a post item ([report-video.md](report-video.md#a-caption): the shape,
@@ -2368,6 +2400,7 @@ The diet he names as a rubber stamp in a corner of the footage box (`render.chro
| `deck.diet.overlap` | 0–0.8, the share of each older tag hidden behind the one in front · default 0 (side by side, the slam and the dim). Above 0 the tags FAN sideways the way the goal stack's notes pile: the newest in front at the left, landing from above like a goal note, each older one a place to the right behind it with its own small turn, keeping its colours (the depth is the overlap and the shadow), showing its regime word and date in the strip beside the one in front; the one past `tags` slides off the back. The fan is narrower by what hides. An older tag's word and date need 110 design px of it, so it is refused past 0.5 (0.63 with `days`) | `umtool look <p> deck.diet.overlap=0.5` |
| `deck.diet.days` | `true` · `false`: the front tag's running count of days on its diet (to the in-record date at the playhead, the streak chain's "Day N"), in a column of its own -- the tag 300 design px wide · default `false` | `umtool look <p> deck.diet.days=true` |
| `deck.diet.colors`, `.labels` | `{<regime>: #hex}` · `{<regime>: words ≤40}` · default the regimes' inks and names | `umtool look <p> deck.diet.labels='{"glp1":"Ozempic"}'` |
+| `deck.diet.flash` | bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): with `form: "tags"`: the new front tag lights, in its ink, at a new diet or new words for it -- never the running day count, never the first tag; the stamp form does not flash; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away | `umtool look <p> deck.diet.flash=false` |
| `deck.diet.onPosts`, `.onChapters` | `dodge` `hide` `show` · default `dodge`: while a post item's card (its card, slot and strip as postLayout lays them: the schedule's `covers`) or a chapter band is up where it stands, it moves to a free anchor of the footage box -- a size down to half if it must, never onto another measure extra that is up -- and hides when none fits; `hide` hides, `show` stays over it | `umtool look <p> deck.diet.onPosts=hide` |
| `deck.diet.position=shelf` | in its own slot on the shelf (`deck.shelf`: under or over the footage), scaled to the shelf's height, left to right in `deck.shelf.items` order -- nothing covers it there, so it never dodges (`onPosts`, `onChapters`, `x`/`y`, `scale` and `avoid` do not apply), and it is over the finale as the shelf is (`deck.shelf.finale`) | `umtool look <p> deck.shelf=true deck.diet.position=shelf` |
| a timeline entry's `hideModules` | `["diet", …]` on an entry hides it over that entry's span, with its own fade, whatever it would otherwise do there (text in the footage no dodge can know of) · any entry, a post item too | `umtool set <p> <entry> hideModules=diet` (`--take <t>` for a take) |
@@ -2392,11 +2425,13 @@ A sticky note per goal on a pile in a corner of the footage box, read off the sc
| Knob | Range · default | From a terminal |
|---|---|---|
-| `deck.goals` | `true` · `false` · `{show, position, x, y, scale, hold, finale, max, color, countdown}` · default on with a measure slice | `umtool look <p> deck.goals=false` |
+| `deck.goals` | `true` · `false` · `{show, position, x, y, scale, hold, finale, max, color, countdown, base}` · default on with a measure slice | `umtool look <p> deck.goals=false` |
| `deck.goals.position`, `.x`/`.y`, `.scale` | `top-left` `top-right` `bottom-left` `bottom-right` `top-center` `bottom-center` · design px · 0.5–2 · default `bottom-right`, unset, 1 | `umtool look <p> deck.goals.position=bottom-left` |
| `deck.goals.position=shelf` | its shelf form (`deck.shelf`): the count of goals set in a column, then the notes fanned sideways like the diet's tags -- ordered by the dial's goal board (measure-goals.mjs `goalsAt(goalBoard(schedule.measure), t)`, so the shelf and the dial always agree): its headline -- the closest goal in force -- in front with "+N more" for the others in force, the rest by recency; a goal the board misses struck in red, MISSED on it, for the dial's 6 s; with no goal in force, the newest in front; a new goal landing from above as on the pile; each older one showing its goal's words in the strip beside it (all of each when there is room); a repeat comes to the front with its ×n. The fan takes the shelf's spare width (shelfLayout), up to its notes side by side. On the shelf it stays up from the first goal (`hold` unset). What the dial draws of the goal stays on the dial | `umtool look <p> deck.shelf.items='["diet","goals"]' deck.goals.position=shelf` |
| `deck.goals.max`, `.color`, `.countdown` | 1–8 notes · #hex paper · bool · default 4, the palette's amber, `true` | `umtool look <p> deck.goals.max=6` |
+| `deck.goals.base` | bool · default `false`: each note also says the weight he had stated when he set the goal -- "LOSE 100 (FROM 346.7)", its qualifier kept ("(FROM ≈390)") -- the slice's own base for that goal, the one the gauge reckons its target from (measure-slice.mjs `goalBase`: the start of the run open when he set it, else the latest weight he gave by the goal's date, stated or remembered). A goal with no base (no weight by then, a target goal such as "250 LB", a base the scale's foot refuses) shows none -- never one made up. On a back card it is a line of its own, right-aligned like the label | `umtool look <p> deck.goals.base=true` |
| `deck.goals.hold`, `.finale` | 0 (up from the first goal on) or 2–600 s after each · `hide` `show` · default 20, `hide` | `umtool look <p> deck.goals.hold=0` |
+| `deck.goals.flash` | bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the note that lands lights as a goal is set -- not the first note (the stack coming up), not the board's own changes; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away | `umtool look <p> deck.goals.flash=false` |
| `deck.goals.onPosts`, `.onChapters` | `dodge` `hide` `show` · default `dodge`: while a post item's card (its card, slot and strip as postLayout lays them: the schedule's `covers`) or a chapter band is up where it stands, it moves to a free anchor of the footage box -- a size down to half if it must, never onto another measure extra that is up -- and hides when none fits; `hide` hides, `show` stays over it | `umtool look <p> deck.goals.onPosts=hide` |
| `deck.goals.position=shelf` | in its own slot on the shelf (`deck.shelf`: under or over the footage), scaled to the shelf's height, left to right in `deck.shelf.items` order -- nothing covers it there, so it never dodges (`onPosts`, `onChapters`, `x`/`y`, `scale` and `avoid` do not apply), and it is over the finale as the shelf is (`deck.shelf.finale`) | `umtool look <p> deck.shelf=true deck.goals.position=shelf` |
| a timeline entry's `hideModules` | `["goals", …]` on an entry hides it over that entry's span, with its own fade, whatever it would otherwise do there (text in the footage no dodge can know of) · any entry, a post item too | `umtool set <p> <entry> hideModules=goals` (`--take <t>` for a take) |
@@ -2419,6 +2454,8 @@ A bathroom-scale face at the top of the instruments' column (the right of the fr
| `deck.dial.mark` | a weight, or `null` · default `300` (its tick and label in the accent) | `umtool look <p> deck.dial.mark=300` |
| `deck.dial.ghosts`, `.goal` | bool · default `true` each (`.goal`: every goal in force, the closest headlined) | `umtool look <p> deck.dial.ghosts=false` |
| `deck.measure.ghosts` | `true` · `{opacity, tolerance, ramp, pulse}` · `false` / absent: off (the default). CLAIM GHOSTS (measure-ghosts.mjs), not `deck.dial.ghosts`: every weight he has claimed so far -- each stated weight the needle goes to and each remembered one, his own, in cut order -- leaves a thin faint tick across the dial's rim at its value, under everything else on the face; a value claimed again (within `tolerance` lb of the tick's first value; an `≈` value as its rounded number; `>300` and `<300` at 300) steps that tick along the `ramp` -- 1× faint, 2× warm, 3× and up hot, a little thicker each step -- and it pulses once as the repeat lands (`pulse`). In the finale every tick stays at its count at the cut's end. Seek-safe: a frame at t draws the claims before t | `umtool look <p> deck.measure.ghosts=true` |
+| `deck.dial.rememberedAs` | `needle` · `rim` · `readout` · `callout` · default `needle` (as it was: a long grey second needle from the hub to the value, its words -- "≈390 / AS OF 24 FEB 2023" -- along it). `rim`: no long needle; a bold marker across the rim at the value and a flag inside it -- "HEAVIEST ≈390 / AS OF FEB 2023 · HE SAYS" -- placed clear of the scale's figures, the hub and the readout. `readout`: a line in the readout under the date -- "HEAVIEST HE'S SAID: ≈390 (FEB 2023)", the goal under it -- and the rim marker. `callout`: as he says it a ghost needle sweeps from where the needle stands to the value and a label ("HEAVIEST HE'S SAID / ≈390 / AS OF FEB 2023") holds 2.2 s, then the rim's flag. The words are the ledger's: its qualifier, its asOf's month; HEAVIEST only for the record's highest remembered weight above every weight he stated (the peak extra's `totals.peakDrift`), else "HE SAYS HE WAS". Each is up while it is the latest remembered; the thin rim ticks of every remembered weight stay as they are | `umtool look <p> deck.dial.rememberedAs=rim` |
+| `deck.measure.flash` | bool · default `false` (off: every cut renders as before) -- THE UPDATE FLASH for every measure widget at once (update-flash.mjs): at the moment a widget's shown value changes its outline lights in its own colour and decays (0.15 s up, 0.7 s down) -- the dial on a weight stated or remembered or a goal change, the odometer on the pounds lost or NET, the trail on each weight landing, the goal stack on a goal set, the diet tags on a new diet; widgets that change on one event flash together; never on frame 0, while the deck is away (the intro, a card) or on a widget's first appearance. A widget's own `flash` overrides it | `umtool look <p> deck.measure.flash=true` |
| `deck.measure.ghosts.opacity`, `.tolerance` | 0.15–0.9 (the 1× tick's; +0.2 a step, at most 0.95) · 0–5 lb · default `0.5`, `0.5` | `umtool look <p> deck.measure.ghosts='{"tolerance":1}'` |
| `deck.measure.ghosts.ramp`, `.pulse` | 2–4 #hex, 1× first (the last for every count from there up), or `null`: the palette's muted, amber, and amber half way to the needle's red · bool · default `null`, `true` | `umtool look <p> deck.measure.ghosts='{"ramp":["#98a29b","#e8a33f","#f37e47"],"pulse":false}'` |
| `deck.dial.needle` | a #hex · default `#ff5a4e` | `umtool look <p> deck.dial.needle='"#ff5a4e"'` |
@@ -2429,6 +2466,7 @@ A bathroom-scale face at the top of the instruments' column (the right of the fr
| `deck.dial.corner` | `bottom-right` `bottom-left` `top-right` `top-left` · default `bottom-right` (the corner only): the dial in that corner, the odometer and the trail up the same side. The measure extras stand at their own anchors in the footage (goals bottom-right, peak top-right, promise top-centre, diet bottom-left, streak bottom-centre): a corner instrument over one that is on is REFUSED by the build, naming it -- move one (`deck.goals.position`, …) or the corner; `top-left` is clear of all five | `umtool look <p> deck.dial.corner=top-left` |
| `deck.dial.motion` | `spring` `ease` · default `spring`. A VARIANT: the needle's `back.out` overshoot and settle, or a plain `power2.inOut` (the finale's drop too) | `umtool look <p> deck.dial.motion=ease` |
| `deck.dial.finaleEnd` | `auto` `odometer` `promise` · default `auto` (`promise` when a promise is on camera, else `odometer`): `promise` hands the finale's last beat to the promise clock (module `promise`) -- the instruments fade out once NET has held (`dialFinaleHandoff`) and the clock takes their place in the finale's lower column, clear of the rail; with no promise module on the cut it ends on the odometer | `umtool look <p> deck.dial.finaleEnd=promise` |
+| `deck.dial.flash` | bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the bezel lights as a weight is stated or remembered, or the goal in force changes; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away | `umtool look <p> deck.dial.flash=false` |
### Lost odometer
@@ -2439,10 +2477,11 @@ Under the dial: the measure's `state.lost.total` (the highest real-time loss cla
| `deck.odometer` | `true` · an object of the knobs below · `false` off · absent: ON when the cut draws a measure (`deck.measure` set), else off | `umtool look <p> deck.odometer=false` |
| `deck.odometer.label` | words over the wheels, ≤ 40 · default `POUNDS HE SAYS HE'S LOST` | `umtool look <p> deck.odometer.label='"…"'` |
| `deck.odometer.net`, `.runs` | bool · default `true` each | `umtool look <p> deck.odometer.net=false` |
+| `deck.odometer.flash` | bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the card lights as the pounds lost go up (or the runs change) and as NET changes; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away | `umtool look <p> deck.odometer.flash=false` |
### Weight trail
-At the foot of the instruments' column: every STATED weight the cut shows, placed by the date he was weighed (its `asOf`, else its date) across the span of them, a dot appearing at its event's `t` and the line between two neighbours drawn once both are said; a red ring on the latest said. The `mark` line (300) dashed across; with `count` and the mark at 300, `UNDER 300 · SAID n×` counts the measure's `totals.under300` rows as the cut reaches each.
+At the foot of the instruments' column: every weight the cut shows -- the STATED ones and (`remembered`) the remembered ones, "≈390, as of Feb 2023" -- placed by the date he was that weight (its `asOf`, else its date), a dot appearing at its event's `t`; the line joins neighbours by date among the stated ones once both are said (a remembered one is a hollow grey dot, never joined; a qualified one hollow). The axes FIT what has been said so far (trail-plan.mjs): each new weight outside them reflows the chart over 0.4 s -- the years, the bounds, every dot -- so the time axis advances with the story; a stretch with no statement longer than `gap` is a break in the time axis (a narrow dashed band, `//` at its foot, each side with its own years) and the line across it dotted, so a decade of nothing does not take the width from the dense run after it. A red ring on the latest said. The `mark` line (300) dashed across; with `count` and the mark at 300, `UNDER 300 · SAID n×` counts the measure's `totals.under300` rows as the cut reaches each.
| Knob | Range · default | From a terminal |
|---|---|---|
@@ -2450,6 +2489,10 @@ At the foot of the instruments' column: every STATED weight the cut shows, place
| `deck.trail.mark` | a weight, or `null` · default `300` | `umtool look <p> deck.trail.mark=300` |
| `deck.trail.count` | bool · default `true` | `umtool look <p> deck.trail.count=false` |
| `deck.trail.label` | its title, ≤ 40 · default `WHAT HE SAYS HE WEIGHS, BY DATE` | `umtool look <p> deck.trail.label='"…"'` |
+| `deck.trail.bounds` | `fit` · `fixed` · default `fit`: the axes fit the weights said so far and reflow as each lands; `fixed` lays every moment on the axes of all the cut's weights | `umtool look <p> deck.trail.bounds=fixed` |
+| `deck.trail.remembered` | bool · default `true`: his remembered weights are points too, hollow and grey, not joined into the line | `umtool look <p> deck.trail.remembered=false` |
+| `deck.trail.gap` | `auto` · days 30–3650 · `0` none · default `auto`: a stretch with no statement longer than a year (or 8× the median spacing, if longer) is a break in the time axis | `umtool look <p> deck.trail.gap=540` |
+| `deck.trail.flash` | bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the card lights as each weight lands on it; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away | `umtool look <p> deck.trail.flash=false` |
### Flips
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -72,8 +72,8 @@ export const GROUPS = [
" project's characters and their drift, an audition of candidate voices (scored against the real voice)",
],
docs: [
- ["`cast [ls] \\| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--narrator] \\| set <id> … \\| rm <id> \\| undo [--json]`",
- "**THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write"],
+ ["`cast [ls] \\| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--convert-pitch target\\|source\\|contour] [--convert-semitones n] [--narrator] \\| set <id> … \\| rm <id> \\| undo [--json]`",
+ "**THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write. A character's `convert` entry is what a recording of them is made into: the stock voice, the engine, and the **pitch** the converted read lands on (`--convert-pitch`: `target` the stock voice's own, `source` the pitch it was read at, `contour` the read's rises and falls at the stock voice's register; `--convert-semitones` -12…12 moves a followed one; `set` lays the flags given over the entry). A followed pitch on an engine that has none, or semitones with nothing followed: **exit 1**"],
["`cast project <project> [--json]` · `cast use <project> <character\\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]`",
"a project's characters (each voice now, where it comes from, its stale reads), the voice for this project or everywhere, and the re-reads that asks for"],
["`cast audition <character\\|@handle> --voices a,b,… [--project <p>] [--text \"…\" \\| --item <id> \\| --line <n> \\| --stock] [--no-score \\| --score-only] [--json] [--progress ndjson]`",
@@ -1029,8 +1029,8 @@ export const GROUPS = [
"**THE PRONUNCIATION LEXICON** ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)): `narration/lexicon.json` in the project, a word or phrase said differently in EVERY synthesized read (a script's `--take`, each piece of a thread read, the bench's re-take); the scripts and cards keep their words. Whole words, without case unless `--case`, a phrase across any spaces, regex characters literal; `--item` for one item's reads (it wins over the project's). A masked slur and a redacted word are never replaced. `add` of a word already listed changes what is said. `try` prints what a voice would be asked to say. `stale` lists every picked read that still says an entry the old way, with the command that re-reads it. A bad entry or an unknown item: **exit 2**"],
["`posts voices <project> [ls] \\| set <handle\\|*> <voice> \\| remove <handle\\|*> [--json]`",
"**THE VOICE MAP** (`narration/voices.json`): the stock voice a thread read gives each author (`*`: everyone it does not name; default `leo` on Orpheus); `ls` lists the map and every author the cut's items carry with the voice each would get. A bad handle or voice: **exit 2**"],
- ["`posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--label l]`",
- "**a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked"],
+ ["`posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--pitch target\\|source\\|contour] [--semitones n] [--label l]` · `<item> --derive <n> --op convert [--engine e] [--voice v] [--pitch …] [--semitones n]`",
+ "**a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked. **`--pitch`** is the pitch the converted read lands on ([knobs.md](knobs.md#the-pitch-a-converted-read-lands-on)): `target` the stock voice's own (the read's intonation flattened to it), `source` the pitch it was read at, `contour` the read's rises and falls moved to the stock voice's register; `--semitones` (-12…12) moves a followed one. Default: the character's `convert` entry, else the editor's `settings.voice.convert`. `source` and `contour` are seed-vc's, with its f0 model (`archilyzer voice setup --engine seed-vc --with f0`); what the editor cannot do it refuses in a sentence (**exit 1**); a value outside these, or a pitch on `--op enhance`: **exit 1**"],
["`posts fx <project> <item> add caption --match \"…\" --text \"…\" [--target post\\|quoted\\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\\|above\\|side]` · `add clock [--rewind auto\\|on\\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]`",
"a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**)"],
["`posts clock <project> [on\\|off\\|default] [--zone <IANA zone>] [--json]`",
diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs
@@ -130,10 +130,13 @@ export const VERBS = Object.freeze([
form("cast ls", "corpus", "the characters' voices across projects", [], { shape: "cast ls" }),
form("cast add", "corpus", "a character: name, stock voice, handles", [
arg("id"), opt("--name", { required: true }), opt("--voice", { required: true, help: "engine:voice" }), opt("--handles", { help: "a,b" }), opt("--speakers", { help: "Name,…" }),
- pick("--convert-engine", ["openvoice", "seed-vc"]), opt("--convert-voice", { help: "engine:voice" }), opt("--note"), bool("--narrator", "the recordings' default character"),
+ pick("--convert-engine", ["openvoice", "seed-vc"]), opt("--convert-voice", { help: "engine:voice" }),
+ pick("--convert-pitch", ["target", "source", "contour"], { help: "the pitch a converted read lands on" }), num("--convert-semitones", { help: "-12…12, moves a followed pitch" }),
+ opt("--note"), bool("--narrator", "the recordings' default character"),
]),
form("cast set", "corpus", "change a character", [
arg("id"), opt("--name"), opt("--voice", { help: "engine:voice" }), opt("--handles"), opt("--speakers"), pick("--convert-engine", ["openvoice", "seed-vc"]), opt("--convert-voice"),
+ pick("--convert-pitch", ["target", "source", "contour"], { help: "the pitch a converted read lands on" }), num("--convert-semitones", { help: "-12…12, moves a followed pitch" }),
opt("--note"), opt("--add-handle"), opt("--remove-handle"), bool("--no-convert"), bool("--narrator"), bool("--no-narrator"),
]),
form("cast rm", "corpus", "a character out of the cast (an undo point)", [arg("id")]),
@@ -462,7 +465,8 @@ function posts() {
item({ required: false, help: "the post item (none: --list, --import, --all or --cut)" }), opt("--script", { type: "text" }), bool("--take", "a new read (the editor's tts)"), opt("--note"),
opt("--voice"), opt("--engine"), num("--speed"), num("--pick"), bool("--approve"), bool("--unapprove"), bool("--off"), bool("--on"),
bool("--thread", "with --take: a thread read"), opt("--parents"), bool("--words", "the picked take's word timings"), bool("--import"), bool("--list"), bool("--all"), bool("--draft-scripts"),
- num("--limit"), bool("--force"), file("--recording", { help: "a person's recording (a file of the project) made the read" }), opt("--as"), dry(),
+ num("--limit"), bool("--force"), file("--recording", { help: "a person's recording (a file of the project) made the read" }), opt("--as"),
+ pick("--pitch", ["target", "source", "contour"], { help: "a convert's pitch (--recording, --derive)" }), num("--semitones", { help: "-12…12, moves a followed pitch" }), dry(),
pairs({ required: false, help: "the mix: lead= tail= linger= rate= …, one per line" }), inTake(),
], { ...Q, ...POST_ITEM }),
p("say", "draft", "the pronunciation lexicon", [pick("op", ["ls", "add", "remove", "try", "stale"], { required: true }), arg("word", { required: false, allowAt: true, help: "the word or phrase (try: the text)" }), arg("spoken", { required: false }), bool("--case"), opt("--item"), opt("--note")], { shape: "posts say <project> <op>" }),
diff --git a/umtool/lib/report/cast.test.mjs b/umtool/lib/report/cast.test.mjs
@@ -122,6 +122,30 @@ test("umtool cast ls/add/set/rm/undo: the characters across projects", async ()
r = await cast(["ls", "--json"]);
assert.deepEqual(r.json().characters.map((c) => [c.id, c.voice, c.handles.join(",")]), [["hostman", "orpheus:zac", "hostman"], ["me", "kokoro:bm_george", "operator"]]);
assert.equal(r.json().characters[1].narrator, true);
+ // The pitch a converted read lands on: laid over the convert entry, what makes no sense refused.
+ r = await cast(["set", "me", "--convert-pitch", "contour", "--convert-semitones", "2", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual(r.json().character.convert, { engine: "seed-vc", pitch: "contour", semitones: 2 });
+ r = await cast(["set", "me", "--convert-voice", "kokoro:af_bella", "--json"]);
+ assert.deepEqual(r.json().character.convert, { engine: "seed-vc", pitch: "contour", semitones: 2, voice: "kokoro:af_bella" }, "the other keys kept");
+ r = await cast(["ls"]);
+ assert.match(r.text(), /convert: seed-vc -> kokoro:af_bella, pitch contour \+2 st/);
+ r = await cast(["set", "me", "--convert-pitch", "target", "--json"]);
+ assert.deepEqual(r.json().character.convert, { engine: "seed-vc", pitch: "target", voice: "kokoro:af_bella" }, "the target's own pitch drops the semitones");
+ for (const [args, re] of [
+ [["--convert-pitch", "high"], /--convert-pitch is one of target, source, contour/],
+ [["--convert-semitones", "13"], /--convert-semitones is a number from -12 to 12/],
+ [["--convert-semitones", "2"], /semitones moves a followed pitch/],
+ [["--convert-engine", "openvoice", "--convert-pitch", "source"], /pitch "source" is seed-vc's: openvoice lands every read on the target's own pitch/],
+ ]) {
+ r = await cast(["set", "me", ...args]);
+ assert.equal(r.code, 1, args.join(" "));
+ assert.match(r.text(), re);
+ }
+ assert.deepEqual((await readCast(ROOT)).cast.characters[1].convert, { engine: "seed-vc", pitch: "target", voice: "kokoro:af_bella" }, "a refusal writes nothing");
+ r = await cast(["set", "me", "--no-convert"]);
+ r = await cast(["set", "me", "--convert-engine", "seed-vc"]);
+ assert.equal(r.code, 0, r.text());
r = await cast(["rm", "me"]);
assert.equal(r.code, 0);
r = await cast(["undo"]);
@@ -278,4 +302,36 @@ test("a recording made a character's read: kept, cleaned (when the editor can),
assert.equal(after.narration.takes[0].engine, "recorded", "the original kept");
assert.equal(r.disclosure, "Narration: voice converted to a synthetic voice (openvoice · kokoro:af_heart)");
await assert.rejects(importRecording(project, e, rec, { as: "nobody", ask: askOp }), /no such character/);
+ assert.equal("pitch" in picked.steps[0], false, "no pitch asked, none recorded");
+ // THE PITCH: the character's own (its convert entry) goes to the editor, a flag for this read beats it, and the
+ // step keeps what the editor says it ran.
+ const bodies = [];
+ const askPitch = async (route, body) => {
+ if (route.endsWith("voice-enhance")) return askOp(route, body);
+ bodies.push(body);
+ await wavOf(body.out, VOICE_A, 2);
+ return { jobId: `conv-${bodies.length + 1}`, result: { engine: body.engine ?? "openvoice", voice: body.voice, pitch: body.pitch ?? "target", ...(body.pitch && body.pitch !== "target" ? { semitones: body.semitones ?? 0 } : {}) } };
+ };
+ await castWrite(castFile(ROOT), (chars) => {
+ const g = chars.find((c) => c.id === "guest");
+ g.convert = { ...(g.convert ?? {}), engine: "seed-vc", pitch: "contour", semitones: 2 };
+ return { changed: "updated" };
+ }, { what: "set guest's convert pitch" });
+ const own = await importRecording(project, (await manifest()).timeline.find((x) => x.id === "p-3"), rec, { ask: askPitch });
+ assert.deepEqual([bodies[0].engine, bodies[0].pitch, bodies[0].semitones], ["seed-vc", "contour", 2]);
+ assert.equal(own.takes.at(-1).step, "converted to kokoro:af_heart (pitch: contour +2 st)");
+ let now = (await manifest()).timeline.find((x) => x.id === "p-3");
+ let step = now.narration.takes[now.narration.pick].steps[0];
+ assert.deepEqual([step.pitch, step.semitones], ["contour", 2]);
+ await importRecording(project, now, rec, { pitch: "source", semitones: -1, ask: askPitch });
+ assert.deepEqual([bodies[1].pitch, bodies[1].semitones], ["source", -1]);
+ // This read at the stock voice's own pitch: the character's semitones go with its pitch.
+ const flat = await importRecording(project, (await manifest()).timeline.find((x) => x.id === "p-3"), rec, { pitch: "target", ask: askPitch });
+ assert.equal(bodies[2].pitch, "target");
+ assert.equal("semitones" in bodies[2], false);
+ assert.equal(flat.takes.at(-1).step, "converted to kokoro:af_heart");
+ now = (await manifest()).timeline.find((x) => x.id === "p-3");
+ step = now.narration.takes[now.narration.pick].steps[0];
+ assert.equal("pitch" in step, false);
+ assert.equal(own.disclosure, "Narration: voice converted to a synthetic voice (seed-vc · kokoro:af_heart)", "the disclosure line is what it was");
});
diff --git a/umtool/lib/report/castCli.mjs b/umtool/lib/report/castCli.mjs
@@ -4,7 +4,7 @@
//
// umtool cast [ls] [--json]
// umtool cast add <id> --name "…" --voice <engine:voice> [--handles a,b] [--speakers Name,…] [--convert-engine e]
-// [--convert-voice <engine:voice>] [--avatar …] [--note "…"] [--narrator] [--json]
+// [--convert-voice <engine:voice>] [--convert-pitch target|source|contour] [--convert-semitones n] [--avatar …] [--note "…"] [--narrator] [--json]
// umtool cast set <id> [the same flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-narrator] [--json]
// umtool cast rm <id> [--json] · umtool cast undo [--json]
// umtool cast project <p> [--json]
@@ -15,7 +15,7 @@
//
// Plain ESM: the CLI runs under bare node.
import path from "node:path";
-import { CAST_CONVERT_ENGINES, characterOf, charactersOf, findCharacter, isQualifiedVoice } from "umtool-report-to-video/cast";
+import { CAST_CONVERT_ENGINES, CAST_CONVERT_PITCH, CAST_SEMITONES_MAX, characterOf, convertPitchErrors, convertPitchLabel, charactersOf, findCharacter, isQualifiedVoice } from "umtool-report-to-video/cast";
import { handleKey, voiceRefOf } from "umtool-report-to-video/post-say";
import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
import { readManifest } from "../projects/report.mjs";
@@ -24,7 +24,8 @@ import { CastError, castFile, castForProject, castWrite, readCast, undoCast } fr
export const CAST_USAGE = [
"usage: umtool cast [ls] [--json]",
" umtool cast add <id> --name \"…\" --voice <engine:voice> [--handles a,b] [--speakers Name,…] [--convert-engine openvoice|seed-vc]",
- " [--convert-voice <engine:voice>] [--avatar …] [--note \"…\"] [--narrator] [--json]",
+ " [--convert-voice <engine:voice>] [--convert-pitch target|source|contour] [--convert-semitones <n>]",
+ " [--avatar …] [--note \"…\"] [--narrator] [--json]",
" umtool cast set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-narrator] [--json]",
" umtool cast rm <id> [--json]",
" umtool cast undo [--json]",
@@ -36,7 +37,10 @@ export const CAST_USAGE = [
"",
" THE CAST (<reports>/.umtool/cast.json, one writer, an undo point per write): the characters that recur across",
" projects -- an id, a name, their handles (X handles / channel slugs), the STOCK voice they read in (engine:voice),",
- " optionally the voice a recording of them is converted to (--convert-voice, its engine --convert-engine), the",
+ " optionally the voice a recording of them is converted to (--convert-voice, its engine --convert-engine) and the",
+ " PITCH that read lands on (--convert-pitch: target = the stock voice's own, the read's intonation flattened to it;",
+ " source = the pitch it was read at; contour = the read's rises and falls at the stock voice's register;",
+ " --convert-semitones -12…12 moves a followed one; source and contour are seed-vc's, with its f0 model), the",
" names their REAL voice goes by in a project's speakers.json (--speakers: a reference to compare with, never a",
" target), and one --narrator (a recording's default character). A project's narration/voices.json overrides it",
" (umtool posts voices); every read asks the same function: the read's own voice, the project's map, the cast, the",
@@ -53,7 +57,7 @@ export const CAST_USAGE = [
" each, picked, awaiting approval). Exit 0 done · 1 refused or failed · 2 usage.",
].join("\n");
-const VALUED = new Set(["--name", "--voice", "--handles", "--speakers", "--convert-engine", "--convert-voice", "--avatar", "--note", "--add-handle", "--remove-handle", "--voices", "--project", "--text", "--item", "--line", "--progress"]);
+const VALUED = new Set(["--name", "--voice", "--handles", "--speakers", "--convert-engine", "--convert-voice", "--convert-pitch", "--convert-semitones", "--avatar", "--note", "--add-handle", "--remove-handle", "--voices", "--project", "--text", "--item", "--line", "--progress"]);
const splitList = (v) => String(v ?? "").split(",").map((x) => x.trim()).filter(Boolean);
function parse(args) {
@@ -84,15 +88,33 @@ function fieldsOf(p) {
if (p.str("--speakers") !== null) f.speakers = splitList(p.str("--speakers"));
if (p.str("--avatar") !== null) f.avatar = p.str("--avatar");
if (p.str("--note") !== null) f.note = p.str("--note");
- if (p.str("--convert-engine") !== null || p.str("--convert-voice") !== null) {
+ if (["--convert-engine", "--convert-voice", "--convert-pitch", "--convert-semitones"].some((k) => p.str(k) !== null)) {
const ce = p.str("--convert-engine");
if (ce !== null && !CAST_CONVERT_ENGINES.includes(ce)) throw new CastError(`--convert-engine is ${CAST_CONVERT_ENGINES.join(" or ")}`);
- f.convert = { ...(ce ? { engine: ce } : {}), ...(p.str("--convert-voice") ? { voice: p.str("--convert-voice") } : {}) };
+ const cp = p.str("--convert-pitch");
+ if (cp !== null && !CAST_CONVERT_PITCH.includes(cp)) throw new CastError(`--convert-pitch is one of ${CAST_CONVERT_PITCH.join(", ")}`);
+ const cs = p.str("--convert-semitones") === null ? null : Number(p.str("--convert-semitones"));
+ if (cs !== null && !(p.str("--convert-semitones").trim() !== "" && Number.isFinite(cs) && Math.abs(cs) <= CAST_SEMITONES_MAX)) throw new CastError(`--convert-semitones is a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX}`);
+ // Only the keys given: `set` lays them over the character's entry (convertOver), `add` takes them as they are.
+ f.convert = { ...(ce ? { engine: ce } : {}), ...(p.str("--convert-voice") ? { voice: p.str("--convert-voice") } : {}), ...(cp ? { pitch: cp } : {}), ...(cs !== null ? { semitones: cs } : {}) };
}
return f;
}
-const line = (c) => `${c.id.padEnd(16)} ${c.voice.padEnd(20)} ${c.name}${c.handles?.length ? ` ${c.handles.map((h) => `@${h}`).join(" ")}` : ""}${c.convert ? ` convert: ${c.convert.engine ?? "default"} -> ${c.convert.voice ?? c.voice}` : ""}${c.speakers?.length ? ` real voice: ${c.speakers.join(", ")}` : ""}${c.narrator ? " (the narrator)" : ""}${c.note ? ` -- ${c.note}` : ""}`;
+/**
+ * A convert entry with the flags' keys laid over it, and what makes no sense together refused in a sentence: the
+ * target's own pitch drops the semitones (nothing is followed to move), 0 semitones is no entry.
+ */
+function convertOver(before, given) {
+ const cv = { ...(before ?? {}), ...given };
+ if (given.pitch === "target" && given.semitones === undefined) delete cv.semitones;
+ if (cv.semitones === 0) delete cv.semitones;
+ const wrong = convertPitchErrors(cv);
+ if (wrong.length) throw new CastError(`convert: ${wrong[0]} (--convert-engine seed-vc --convert-pitch source|contour)`);
+ return cv;
+}
+
+const line = (c) => `${c.id.padEnd(16)} ${c.voice.padEnd(20)} ${c.name}${c.handles?.length ? ` ${c.handles.map((h) => `@${h}`).join(" ")}` : ""}${c.convert ? ` convert: ${c.convert.engine ?? "default"} -> ${c.convert.voice ?? c.voice}${convertPitchLabel(c.convert) ? `, pitch ${convertPitchLabel(c.convert)}` : ""}` : ""}${c.speakers?.length ? ` real voice: ${c.speakers.join(", ")}` : ""}${c.narrator ? " (the narrator)" : ""}${c.note ? ` -- ${c.note}` : ""}`;
async function projectOf(ref, reportsRoot) {
const r = await resolveProject(ref, reportsRoot);
@@ -164,13 +186,14 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
if (sub === "add") {
if (at >= 0) throw new CastError(`${id} is in the cast already (umtool cast set ${id} …)`);
if (!f.name || !f.voice) throw new CastError('cast add takes --name "…" and --voice <engine:voice>');
- const c = { id, name: f.name, handles: f.handles ?? [], voice: f.voice, ...(f.convert ? { convert: f.convert } : {}), ...(f.speakers ? { speakers: f.speakers } : {}), ...(f.avatar ? { avatar: f.avatar } : {}), ...(f.note ? { note: f.note } : {}), ...(p.has("--narrator") ? { narrator: true } : {}) };
+ const c = { id, name: f.name, handles: f.handles ?? [], voice: f.voice, ...(f.convert ? { convert: convertOver(null, f.convert) } : {}), ...(f.speakers ? { speakers: f.speakers } : {}), ...(f.avatar ? { avatar: f.avatar } : {}), ...(f.note ? { note: f.note } : {}), ...(p.has("--narrator") ? { narrator: true } : {}) };
if (c.narrator) for (const x of chars) delete x.narrator;
chars.push(c);
return { changed: "added", character: c };
}
if (at < 0) throw new CastError(`no ${id} in the cast (umtool cast ls)`);
- const c = { ...chars[at], ...f };
+ // The convert flags are laid over the entry: --convert-pitch alone keeps its engine and voice.
+ const c = { ...chars[at], ...f, ...(f.convert ? { convert: convertOver(chars[at].convert, f.convert) } : {}) };
for (const h of p.all("--add-handle").map(handleKey)) if (h && !c.handles.includes(h)) c.handles = [...c.handles, h];
for (const h of p.all("--remove-handle").map(handleKey)) c.handles = c.handles.filter((x) => x !== h);
if (p.has("--no-convert")) delete c.convert;
diff --git a/umtool/lib/report/derivePitch.mjs b/umtool/lib/report/derivePitch.mjs
@@ -0,0 +1,58 @@
+// A CONVERT'S PITCH, between umtool and the editor's voice-convert (the pitch a converted read lands on: knobs.md,
+// "The pitch a converted read lands on"). The pure pieces the CLI's derive (postNarrationCli.mjs deriveTake) and the
+// app's (app/api/report/post-narration/route.ts, the post bench's "run AI on take") share, so they ask, record and
+// refuse alike:
+//
+// derivePitchOf what a derive is asked with (`pitch`, `semitones`), checked before any job
+// stepPitchOf what the new take's step keeps: the pitch as the editor RAN it, never the target's own
+// deriveRefusalOf an editor refusal read as "no engine for it" -- or passed through as it is, when it already
+// names the command that fixes it
+//
+// Dependency-free but for cast.mjs's constants.
+import { CAST_CONVERT_PITCH, CAST_SEMITONES_MAX } from "umtool-report-to-video/cast";
+
+/**
+ * A derive's `pitch` / `semitones` as asked (a body's, a flag's): `{ ok: true, value: {pitch?, semitones?} }` with only
+ * what was given, or `{ ok: false, error }`. `semitones` may be a number or its string (a form field, a query). They
+ * are a convert's: asked of another op they are refused.
+ */
+export function derivePitchOf({ pitch, semitones } = {}, op = "convert") {
+ const none = (v) => v === undefined || v === null || v === "";
+ if (none(pitch) && none(semitones)) return { ok: true, value: {} };
+ if (op !== "convert") return { ok: false, error: `pitch and semitones are a convert's: ${op} keeps the read's own pitch` };
+ const value = {};
+ if (!none(pitch)) {
+ if (!CAST_CONVERT_PITCH.includes(pitch)) return { ok: false, error: `pitch is one of ${CAST_CONVERT_PITCH.join(", ")} (got ${JSON.stringify(pitch)})` };
+ value.pitch = pitch;
+ }
+ if (!none(semitones)) {
+ const n = typeof semitones === "number" ? semitones : typeof semitones === "string" && semitones.trim() !== "" ? Number(semitones) : NaN;
+ if (!Number.isFinite(n) || Math.abs(n) > CAST_SEMITONES_MAX) return { ok: false, error: `semitones is a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX} (got ${JSON.stringify(semitones)})` };
+ value.semitones = n;
+ }
+ return { ok: true, value };
+}
+
+/**
+ * The pitch a derived take's step keeps: what the editor says it ran (its `@@voice-result`: its default when none was
+ * asked), else what was asked. The stock voice's own pitch is not a step's news (`{}`), and 0 semitones is none.
+ */
+export function stepPitchOf(asked = {}, said = {}) {
+ const pitch = typeof said?.pitch === "string" ? said.pitch : asked?.pitch;
+ if (!pitch || pitch === "target" || !CAST_CONVERT_PITCH.includes(pitch)) return {};
+ const n = typeof said?.semitones === "number" ? said.semitones : asked?.semitones;
+ return { pitch, ...(typeof n === "number" && Number.isFinite(n) && n !== 0 ? { semitones: n } : {}) };
+}
+
+/**
+ * An editor refusal of a derive, read: `null` (an ordinary error), or `{ installed: false, error }` -- the editor has
+ * no engine for the op (an older editor has no route; a newer one names the setup to run). A refusal that names an
+ * OPTIONAL group to fetch (`… --with f0`: the engine is there, its pitch-following model is not) is passed through in
+ * the editor's words: "no convert engine installed" would be false.
+ */
+export function deriveRefusalOf(op, status, message) {
+ const msg = String(message ?? "").replace(/^the editor refused it: /, "");
+ if (!(status === 404 || /not installed|no engine|unknown|not found|404/i.test(msg))) return null;
+ if (/--with\b/.test(msg)) return { installed: false, error: msg };
+ return { installed: false, error: `the editor has no ${op} engine installed (not installed: ${msg})` };
+}
diff --git a/umtool/lib/report/derivePitch.test.mjs b/umtool/lib/report/derivePitch.test.mjs
@@ -0,0 +1,65 @@
+// lib/report/derivePitch.mjs: a convert's pitch between umtool and the editor -- what a derive is asked with, what the
+// new take's step keeps, and which editor refusals mean "no engine". The app's derive route
+// (app/api/report/post-narration/route.ts) and the CLI's (postNarrationCli.mjs deriveTake) both go through it.
+// Run: node --test umtool/lib/report/derivePitch.test.mjs
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { validatePostNarration } from "umtool-report-to-video/post-narration";
+import { derivePitchOf, deriveRefusalOf, stepPitchOf } from "./derivePitch.mjs";
+
+test("a derive's pitch as asked: only what was given, a body's number or a query's string, a convert's alone", () => {
+ assert.deepEqual(derivePitchOf({}), { ok: true, value: {} });
+ assert.deepEqual(derivePitchOf({ pitch: null, semitones: "" }), { ok: true, value: {} }, "a query with neither");
+ assert.deepEqual(derivePitchOf({ pitch: "contour", semitones: 2 }), { ok: true, value: { pitch: "contour", semitones: 2 } });
+ assert.deepEqual(derivePitchOf({ pitch: "source", semitones: "-1.5" }), { ok: true, value: { pitch: "source", semitones: -1.5 } });
+ assert.deepEqual(derivePitchOf({ pitch: "target" }), { ok: true, value: { pitch: "target" } });
+ assert.deepEqual(derivePitchOf({ semitones: 0 }), { ok: true, value: { semitones: 0 } }, "0 is said, not dropped: the editor's default may be another");
+ for (const [given, re] of [
+ [{ pitch: "up" }, /^pitch is one of target, source, contour \(got "up"\)$/],
+ [{ pitch: 2 }, /pitch is one of/],
+ [{ pitch: "source", semitones: 13 }, /^semitones is a number from -12 to 12 \(got 13\)$/],
+ [{ pitch: "source", semitones: "two" }, /semitones is a number from -12 to 12 \(got "two"\)/],
+ [{ pitch: "source", semitones: true }, /semitones is a number/],
+ ]) {
+ const r = derivePitchOf(given);
+ assert.equal(r.ok, false, JSON.stringify(given));
+ assert.match(r.error, re);
+ }
+ const en = derivePitchOf({ pitch: "source" }, "enhance");
+ assert.equal(en.ok, false);
+ assert.match(en.error, /pitch and semitones are a convert's: enhance keeps the read's own pitch/);
+ assert.deepEqual(derivePitchOf({}, "enhance"), { ok: true, value: {} });
+});
+
+test("the step keeps the pitch the editor ran, else the one asked; never the target's own, never 0 semitones", () => {
+ assert.deepEqual(stepPitchOf({}, {}), {});
+ assert.deepEqual(stepPitchOf({ pitch: "target" }, {}), {});
+ assert.deepEqual(stepPitchOf({ pitch: "contour", semitones: 2 }, {}), { pitch: "contour", semitones: 2 }, "an editor that says nothing");
+ assert.deepEqual(stepPitchOf({ pitch: "source", semitones: 0 }, null), { pitch: "source" });
+ // The editor's default, when none was asked.
+ assert.deepEqual(stepPitchOf({}, { pitch: "contour", semitones: 2 }), { pitch: "contour", semitones: 2 });
+ // What it ran beats what was asked (its settings' semitones under an asked pitch).
+ assert.deepEqual(stepPitchOf({ pitch: "source" }, { pitch: "source", semitones: -1 }), { pitch: "source", semitones: -1 });
+ assert.deepEqual(stepPitchOf({ pitch: "contour", semitones: 2 }, { pitch: "target" }), {});
+ assert.deepEqual(stepPitchOf({}, { pitch: "sideways" }), {}, "not a pitch the manifest takes");
+ // Whatever it returns is a step the manifest's validator takes.
+ for (const p of [{ pitch: "contour", semitones: 2 }, { pitch: "source" }, {}]) {
+ const entry = { id: "p-1", narration: { script: "x", takes: [{ file: "narration/posts/1/take-2.convert-seed-vc.wav", engine: "derived", voice: "af_bella", seconds: 1, source: { kind: "take", from: "take-1.recorded-operator" }, steps: [{ op: "convert", engine: "seed-vc", voice: "kokoro:af_bella", ...stepPitchOf(p, {}) }] }], pick: 0 } };
+ assert.deepEqual(validatePostNarration(entry).filter((e) => /steps/.test(e)), [], JSON.stringify(p));
+ }
+});
+
+test("an editor refusal: no engine, an ordinary error, or a missing optional model said in the editor's words", () => {
+ assert.deepEqual(deriveRefusalOf("enhance", 404, "HTTP 404"), { installed: false, error: "the editor has no enhance engine installed (not installed: HTTP 404)" });
+ assert.deepEqual(
+ deriveRefusalOf("convert", 400, "the editor refused it: OpenVoice v2 is not installed (/v/openvoice): missing the python venv — run `archilyzer voice setup --engine openvoice`"),
+ { installed: false, error: "the editor has no convert engine installed (not installed: OpenVoice v2 is not installed (/v/openvoice): missing the python venv — run `archilyzer voice setup --engine openvoice`)" },
+ );
+ // seed-vc IS installed; its pitch-following model is not: the editor's sentence, as it is.
+ const f0 = "pitch \"source\" needs Seed-VC (v1, 22 kHz speech)'s f0 model, which is not installed (/v/seed-vc: missing rmvpe.pt) — run `archilyzer voice setup --engine seed-vc --with f0`";
+ assert.deepEqual(deriveRefusalOf("convert", 400, `the editor refused it: ${f0}`), { installed: false, error: f0 });
+ assert.equal(/no convert engine/.test(deriveRefusalOf("convert", 400, f0).error), false);
+ // Not about an install: the caller answers it as the error it is.
+ assert.equal(deriveRefusalOf("convert", 400, "OpenVoice v2 (tone-colour converter) has no pitch control — it lands every read on the target's own pitch"), null);
+ assert.equal(deriveRefusalOf("convert", 400, "\"semitones\" moves a followed pitch"), null);
+});
diff --git a/umtool/lib/report/postAvatarStores.test.mjs b/umtool/lib/report/postAvatarStores.test.mjs
@@ -0,0 +1,140 @@
+// The archive's authors' pictures found where they are (postReel.mjs
+// archiveAvatarStores, `umtool posts avatars`, `umtool posts avatar`):
+// a project whose channels tree is a SHADOW (posts copied in, no _avatars/)
+// reads the corpus's stores behind it; a channel with no store at all does
+// not end the search; the store's "TheSubject" is the card's "thesubject"
+// (quartering-diet rev 9, 11 Nov: "copied 0 picture(s) … no picture yet for
+// @thequartering, @madamsavvy" while the corpus held both).
+//
+// Temp dirs under UMTOOL_TEST_TMP when set (a scratch dir off /tmp), else the
+// system's.
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+
+const BASE = process.env.UMTOOL_TEST_TMP || tmpdir();
+await mkdir(BASE, { recursive: true });
+const ROOT = mkdtempSync(path.join(BASE, "umtool-post-avatar-stores-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const CORPUS = path.join(ROOT, "corpus-channels");
+const REPORTS = path.join(ROOT, "reports");
+// The corpus is CHANNELS_DIR, read when paths.mjs loads: set before the imports.
+process.env.CHANNELS_DIR = CORPUS;
+delete process.env.CHANNELS_FALLBACK;
+const reel = await import("./postReel.mjs");
+const { postsCommand } = await import("./postsCli.mjs");
+
+// First-listed channel: posts only, no posts-media/ anywhere. Then a store keyed
+// "TheSubject" (as X printed it) and one keyed "MadamOther".
+const CHANNELS = ["first-x", "subj-X", "other-x"];
+
+async function store(tree, slug, doc) {
+ const dir = path.join(tree, slug, "posts-media", "_avatars");
+ await mkdir(dir, { recursive: true });
+ for (const a of Object.values(doc)) await writeFile(path.join(dir, a.file), "picture");
+ await writeFile(path.join(dir, "avatars.json"), JSON.stringify(doc, null, 2));
+}
+async function posts(tree, slug) {
+ await mkdir(path.join(tree, slug, "posts"), { recursive: true });
+ await writeFile(path.join(tree, slug, "posts", "2026-10.jsonl"), "");
+}
+
+const item = (slug, id, handle) => ({
+ type: "post", id: `p-${id}`, post: `${slug}/${id}`, platform: "x", author: handle.toUpperCase(), handle,
+ date: `2026-10-2${id}T10:00:00.000Z`, text: `post ${id}`,
+});
+
+async function project(name) {
+ const dir = path.join(REPORTS, name);
+ const shadow = path.join(dir, ".shadow-channels");
+ for (const c of CHANNELS) await posts(shadow, c);
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({
+ schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "", channelSlug: "subj-X", channelsDir: ".shadow-channels" },
+ render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" } },
+ // The first card spells the author in lower case, as a mention does.
+ timeline: [item("first-x", "1", "thesubject"), item("subj-X", "2", "TheSubject"), item("other-x", "3", "MadamOther")],
+ }, null, 2));
+ return { id: name, dir, shadow };
+}
+const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
+const cli = async (args) => {
+ const lines = [];
+ const errs = [];
+ const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) });
+ return { code, out: lines.join("\n"), err: errs.join("\n") };
+};
+
+for (const c of CHANNELS) await posts(CORPUS, c);
+await store(CORPUS, "subj-X", {
+ TheSubject: { file: "TheSubject.png", url: "https://pbs.twimg.com/a.png", capturedAt: "2026-11-07T00:00:00Z" },
+ MadamOther: { file: "MadamOther.jpg", capturedAt: "2026-11-01T00:00:00Z" },
+});
+await store(CORPUS, "other-x", { MadamOther: { file: "MadamOther.jpg", url: "https://pbs.twimg.com/b.jpg", capturedAt: "2026-11-07T00:00:00Z" } });
+
+test("archiveAvatarStores: every tree, every channel; a missing _avatars/ is noted and skipped; keys any case", async () => {
+ const p = await project("unit");
+ const { store: got, searched } = await reel.archiveAvatarStores([p.shadow, CORPUS], CHANNELS);
+ assert.deepEqual([...got.keys()].sort(), ["madamother", "thesubject"]);
+ assert.equal(got.get("thesubject").handle, "TheSubject");
+ // The newest of two stores' pictures of one author.
+ assert.equal(got.get("madamother").file, path.join(CORPUS, "other-x", "posts-media", "_avatars", "MadamOther.jpg"));
+ assert.deepEqual(searched.map((s) => `${s.channel}@${s.tree === CORPUS ? "corpus" : "shadow"}:${s.state}`), [
+ "first-x@shadow:none", "first-x@corpus:none", "subj-X@shadow:none", "subj-X@corpus:read", "other-x@shadow:none", "other-x@corpus:read",
+ ]);
+ const said = reel.avatarStoresSaid(searched);
+ assert.equal(said.length, 3);
+ assert.match(said[0], /^first-x: no _avatars\/ in .*\.shadow-channels or .*corpus-channels$/);
+ assert.match(said[1], /^subj-X: 2 picture\(s\) in .*corpus-channels\/subj-X\/posts-media\/_avatars; no _avatars\/ in .*\.shadow-channels$/);
+ // One tree, as a string, as before.
+ assert.equal((await reel.archiveAvatars(CORPUS, ["subj-X"])).size, 2);
+});
+
+test("posts avatars: a shadow-channels project copies the corpus's pictures, names the stores it searched", async () => {
+ const p = await project("shadowed");
+ const r = await cli(["avatars", "shadowed"]);
+ assert.equal(r.code, 0, r.err);
+ assert.match(r.out, /^copied 2 picture\(s\) from subj-X \+ other-x's stores: /, r.out);
+ assert.doesNotMatch(r.out, /no picture yet/, r.out);
+ assert.match(r.out, /first-x: no _avatars\//);
+ const m = await manifest(p);
+ assert.equal(m.postAvatars.TheSubject.src, "posts-media/_avatars/TheSubject.png");
+ assert.equal(m.postAvatars.TheSubject.source, "archive");
+ assert.equal(m.postAvatars.MadamOther.url, "https://pbs.twimg.com/b.jpg");
+ await readFile(path.join(p.dir, "posts-media", "_avatars", "TheSubject.png"));
+ // Again: nothing more to copy, and nobody without one.
+ const again = await cli(["avatars", "shadowed", "--json"]);
+ const j = JSON.parse(again.out);
+ assert.deepEqual(j.copied, {});
+ assert.deepEqual(j.without, []);
+ assert.ok(j.stores.some((s) => s.channel === "first-x" && s.state === "none"));
+});
+
+test("posts avatars: no store anywhere says so, and names the author as the card draws them", async () => {
+ const p = await project("bare");
+ const m0 = await manifest(p);
+ m0.timeline = [item("first-x", "1", "NoPicture")];
+ await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(m0, null, 2));
+ const r = await cli(["avatars", "bare"]);
+ assert.equal(r.code, 0, r.err);
+ assert.match(r.out, /^copied 0 picture\(s\) from no store/);
+ assert.match(r.out, /no picture yet for @NoPicture /);
+});
+
+test("posts avatar: a handle in any case sets and clears the drawn author's picture", async () => {
+ const p = await project("manual");
+ const pic = path.join(ROOT, "manual.png");
+ await writeFile(pic, "picture");
+ assert.equal((await cli(["avatar", "manual", "@madamother", pic])).code, 0);
+ let m = await manifest(p);
+ assert.deepEqual(m.postAvatars, { MadamOther: { src: "posts-media/_avatars/MadamOther-manual.png", source: "manual" } });
+ // The archive's never replaces it.
+ assert.equal((await cli(["avatars", "manual"])).code, 0);
+ m = await manifest(p);
+ assert.equal(m.postAvatars.MadamOther.source, "manual");
+ assert.equal(m.postAvatars.TheSubject.source, "archive");
+ assert.equal((await cli(["avatar", "manual", "MADAMOTHER", "off"])).code, 0);
+ assert.equal((await manifest(p)).postAvatars.MadamOther, undefined);
+});
diff --git a/umtool/lib/report/postNarration.test.mjs b/umtool/lib/report/postNarration.test.mjs
@@ -8,7 +8,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { after, test } from "node:test";
import { postsCommand } from "./postsCli.mjs";
-import { importPatches, makeTake, mixPatchOf } from "./postNarrationCli.mjs";
+import { importPatches, makeTake, mixPatchOf, pitchFlags } from "./postNarrationCli.mjs";
import { fitPostItem, rmsFrames, scanAttachment, scoreWindows } from "./postFit.mjs";
import { manifestToken, updatePostNarration } from "./manifest.mjs";
import { postItemPlan } from "umtool-report-to-video/post-item";
@@ -292,6 +292,7 @@ test("a DERIVED take: run through the editor's op into a new take, the original
});
assert.equal(asked.at(-1).route, "/api/ops/voice-enhance");
assert.equal("voice" in asked.at(-1).body, false);
+ assert.equal("pitch" in asked.at(-1).body, false);
assert.equal(e1.take.voice, "operator");
assert.deepEqual([e1.take.steps[0].op, e1.take.steps[0].engine, e1.take.steps[0].voice], ["enhance", "deepfilternet", undefined]);
// A convert that named no target: the stock voice the editor landed on.
@@ -302,7 +303,26 @@ test("a DERIVED take: run through the editor's op into a new take, the original
assert.equal("voice" in asked.at(-1).body, false);
assert.equal(c1.take.voice, "zac");
assert.deepEqual([c1.take.steps[0].engine, c1.take.steps[0].voice], ["openvoice", "zac"]);
- for (const k of [3, 2]) await deleteTake(p, (await manifest(p)).timeline[0], k);
+ // A convert's PITCH goes as asked, and the step keeps what the editor says it ran.
+ const c2 = await deriveTake(p, (await manifest(p)).timeline[0], {
+ from: 0, op: "convert", engine: "seed-vc", voice: "kokoro:af_bella", pitch: "contour", semitones: 2,
+ ask: async (route, body) => { asked.push({ route, body }); wav(body.out, 1.5); return { jobId: "job-p", result: { op: "convert", engine: "seed-vc", voice: "af_bella", pitch: "contour", semitones: 2, f0: { targetHz: 197.5, sourceHz: 208.8, shiftSemitones: 1.04 } } }; },
+ });
+ assert.deepEqual([asked.at(-1).body.pitch, asked.at(-1).body.semitones], ["contour", 2]);
+ assert.deepEqual([c2.take.steps[0].pitch, c2.take.steps[0].semitones, c2.take.voice], ["contour", 2, "af_bella"]);
+ // Asked of an enhance, a pitch is not sent; the flags' values are checked in their own names.
+ const e2 = await deriveTake(p, (await manifest(p)).timeline[0], {
+ from: 0, op: "enhance", pitch: "source", semitones: 2,
+ ask: async (route, body) => { asked.push({ route, body }); wav(body.out, 1.5); return { jobId: "job-e2", result: { op: "enhance", engine: "deepfilternet" } }; },
+ });
+ assert.deepEqual(["pitch" in asked.at(-1).body, "semitones" in asked.at(-1).body, "pitch" in e2.take.steps[0]], [false, false, false]);
+ const flag = (o) => pitchFlags((k) => o[k] ?? null);
+ assert.deepEqual(flag({}), {});
+ assert.deepEqual(flag({ "--pitch": "source", "--semitones": "-2.5" }), { pitch: "source", semitones: -2.5 });
+ assert.throws(() => flag({ "--pitch": "up" }), /--pitch is one of target, source, contour \(got up\)/);
+ assert.throws(() => flag({ "--semitones": "20" }), /--semitones is a number from -12 to 12 \(got 20\)/);
+ assert.throws(() => flag({ "--semitones": "" }), /--semitones is a number/);
+ for (const k of [5, 4, 3, 2]) await deleteTake(p, (await manifest(p)).timeline[0], k);
// An op the editor has no engine for.
const { OpNotInstalled } = await import("umtool-report-to-video/narrate-via-editor");
await assert.rejects(
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -26,6 +26,8 @@ import { promisify } from "node:util";
import {
NARRATION_INDEX, POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf,
} from "umtool-report-to-video/post-narration";
+import { CAST_CONVERT_PITCH, CAST_SEMITONES_MAX } from "umtool-report-to-video/cast";
+import { stepPitchOf } from "./derivePitch.mjs";
import { excerptSpansOf, postItemPlan, postReadText } from "umtool-report-to-video/post-item";
import { partRoles } from "umtool-report-to-video/post-thread";
import { spokenRead } from "umtool-report-to-video/post-redact";
@@ -45,6 +47,9 @@ export const NARRATE_USAGE = [
" [--pick <n>] [--approve|--unapprove] [--off|--on] [lead=… tail=… ramp=… linger=… clip=read|full",
" wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=… pace=fast|normal] [--json]",
" umtool posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert]",
+ " [--pitch target|source|contour] [--semitones <n>]",
+ " umtool posts narrate <project> <item> --derive <n> --op enhance|convert [--engine e] [--voice v]",
+ " [--pitch target|source|contour] [--semitones <n>]",
" umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id>]… [--no-quoted]",
" [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--force] [--dry-run]",
" umtool posts narrate <project> <item> … --in-take <take> any of these on a TAKE of the project: the pick, a new",
@@ -71,6 +76,12 @@ export const NARRATE_USAGE = [
" narrator) -- each a new take, the last picked, the disclosure line said.",
" --derive <n> --op enhance|convert [--engine e] [--voice v]: a NEW take made from take n by the editor's op",
" (enhance: denoise, level; convert: the performance kept, the timbre a STOCK synthetic voice) -- the original kept.",
+ " --pitch target|source|contour [--semitones <n>] (a convert, by --derive or --recording): the PITCH the converted",
+ " read lands on -- target: the stock voice's own (the read's intonation is flattened to it); source: the pitch it",
+ " was read at (raise your voice and it rises); contour: the read's rises and falls, moved as a whole to the stock",
+ " voice's register; --semitones (-12 to 12) then moves a followed pitch. Default: the character's own (umtool cast",
+ " set <id> --convert-pitch …), else the editor's (settings.voice.convert). source and contour are seed-vc's, with",
+ " its f0 model (archilyzer voice setup --engine seed-vc --with f0); the editor refuses what it cannot do.",
" A narrated post lasts lead + its read + tail + linger (1.8 s); a longer video is cut to that -- its best part,",
" pace=fast plays a post (or, with --cut, every post) back to back: lead 0.1, tail 0.15, ramp 0.3, linger 0.45 --",
" unless it sets one itself; pace=normal the cut's gaps.",
@@ -522,6 +533,7 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
// A RECORDING made a character's read: kept as a take (the original), cleaned, converted to its stock voice.
const r = await importRecording(project, e, str("--recording"), {
as: str("--as"), label: str("--label") ?? "operator", clean: !flags.has("--no-clean"), convert: !flags.has("--no-convert"), note: str("--note"),
+ ...pitchFlags(str),
emit: (_ev, f) => !json && f?.message && out(f.message),
});
if (json) out(JSON.stringify({ ok: true, id: e.id, ...r }, null, 2));
@@ -537,7 +549,9 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
if (!Number.isInteger(k) || k < 1) throw new NarrateError("--derive takes a take's number as --list shows it (1 = the first)");
const op = str("--op") ?? "";
try {
- const r = await deriveTake(project, e, { from: k - 1, op, engine: str("--engine"), voice: str("--voice"), emit: (_ev, f) => !json && f?.message && out(f.message) });
+ const pitched = pitchFlags(str);
+ if (op !== "convert" && (pitched.pitch !== undefined || pitched.semitones !== undefined)) throw new NarrateError("--pitch and --semitones are a convert's (--op convert): an enhance keeps the read's own pitch");
+ const r = await deriveTake(project, e, { from: k - 1, op, engine: str("--engine"), voice: str("--voice"), ...pitched, emit: (_ev, f) => !json && f?.message && out(f.message) });
if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, token: r.result.token }, null, 2));
else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), from take ${k} by ${op}, picked`);
return 0;
@@ -659,16 +673,34 @@ export async function fitCommand(project, refs, { all = false, linger = null, js
return 0;
}
+/** `--pitch` / `--semitones` as a convert takes them (only those given); a value the editor would refuse anyway is refused here, in the flag's name. */
+export function pitchFlags(str) {
+ const out = {};
+ const p = str("--pitch");
+ if (p !== null) {
+ if (!CAST_CONVERT_PITCH.includes(p)) throw new NarrateError(`--pitch is one of ${CAST_CONVERT_PITCH.join(", ")} (got ${p || "nothing"})`);
+ out.pitch = p;
+ }
+ const s = str("--semitones");
+ if (s !== null) {
+ const n = Number(s);
+ if (s.trim() === "" || !Number.isFinite(n) || Math.abs(n) > CAST_SEMITONES_MAX) throw new NarrateError(`--semitones is a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX} (got ${s || "nothing"})`);
+ out.semitones = n;
+ }
+ return out;
+}
+
/**
* A DERIVED TAKE (post-narration.mjs: "run AI on recorded voice"): take
* `from` (an index) run through the editor's `op` (`enhance`, `convert`) into
* a NEW take -- source `{kind: "take", from: <its id>}`, its step recorded --
* the original untouched; a parted take part by part (its parts kept). The
* editor's op is a job (`POST /api/ops/voice-enhance|voice-convert` with
- * `{file, out, engine?, voice?, params?, parts?}`); one it has no engine for
- * throws OpNotInstalled.
+ * `{file, out, engine?, voice?, pitch?, semitones?, params?, parts?}`); one it has no engine for
+ * throws OpNotInstalled. A convert's `pitch` / `semitones` (the pitch the read lands on: the editor's voice-convert)
+ * go as asked and are kept on the take's step as the editor says it ran them.
*/
-export async function deriveTake(project, e, { from, op, engine = null, voice = null, params = null, emit = () => {}, editor = null, ask = null } = {}) {
+export async function deriveTake(project, e, { from, op, engine = null, voice = null, pitch = null, semitones = null, params = null, emit = () => {}, editor = null, ask = null } = {}) {
const takes = e.narration?.takes ?? [];
const t = takes[from];
if (!t) throw new NarrateError(`${e.id} has no take ${from + 1}`);
@@ -688,6 +720,7 @@ export async function deriveTake(project, e, { from, op, engine = null, voice =
const body = {
file: abs(t.file), out: abs(rel),
...(engine ? { engine } : {}), ...(target ? { voice: target } : {}), ...(params ? { params } : {}),
+ ...(op === "convert" && pitch ? { pitch } : {}), ...(op === "convert" && typeof semitones === "number" ? { semitones } : {}),
...(parts ? { parts: t.parts.map((p, k) => ({ file: abs(p.file), out: abs(parts[k].file) })) } : {}),
};
const askOp = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp;
@@ -697,11 +730,13 @@ export async function deriveTake(project, e, { from, op, engine = null, voice =
// The editor's defaults, when the ask named none: the engine it ran, the stock voice it landed on.
const ran = engine ?? (typeof said?.engine === "string" ? said.engine : null);
const landed = op === "convert" ? (target ?? (typeof said?.voice === "string" ? said.voice : null)) : null;
+ // The pitch it landed on, as the editor ran it (its default when none was asked); the target's own is not a step's news.
+ const pitched = op === "convert" ? stepPitchOf({ pitch, semitones }, said) : {};
const take = {
// A take's voice is the bare stock voice ("am_michael"); its step keeps the target as asked ("kokoro:am_michael").
file: rel, engine: "derived", voice: (landed ? String(landed).split(":").pop() : null) ?? t.voice ?? "?", seconds: m.seconds ?? t.seconds,
source: { kind: "take", from: takeIdOf(t) },
- steps: [{ op, ...(ran ? { engine: ran } : {}), ...(landed ? { voice: landed } : {}), ...(params ? { params } : {}), ranAt: new Date().toISOString(), job: jobId }],
+ steps: [{ op, ...(ran ? { engine: ran } : {}), ...(landed ? { voice: landed } : {}), ...pitched, ...(params ? { params } : {}), ranAt: new Date().toISOString(), job: jobId }],
script: t.script ?? e.narration?.script ?? "", at: new Date().toISOString(), jobId,
...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), ...(parts ? { parts } : {}),
};
@@ -715,16 +750,17 @@ export async function deriveTake(project, e, { from, op, engine = null, voice =
* as a RECORDED take (postRecord.mjs keepRecording: trimmed, levelled -- the original, never overwritten), then a
* derived take CLEANED by the editor's voice-enhance (skipped, and said, when it has no engine for it), then a
* derived take CONVERTED by its voice-convert to the character's STOCK voice (cast.mjs convertTargetOf: its convert
- * voice, else its voice) -- the character `as` names (an id, a handle), else the post's author's in the cast, else
+ * voice, else its voice) at the PITCH asked (`pitch`, `semitones`), else the character's own (its convert entry's),
+ * else the editor's -- the character `as` names (an id, a handle), else the post's author's in the cast, else
* the cast's narrator; none: kept as recorded (and cleaned). Each step a new take, the last one picked, with the
* disclosure line the cut will carry. Returns `{ takes: [{ step, file }], picked, notes, disclosure, character }`.
*/
-export async function importRecording(project, e0, file, { as = null, label = "operator", clean = true, convert = true, note = null, emit = () => {}, editor = null, ask = null } = {}) {
+export async function importRecording(project, e0, file, { as = null, label = "operator", clean = true, convert = true, pitch = undefined, semitones = undefined, note = null, emit = () => {}, editor = null, ask = null } = {}) {
const abs = path.resolve(String(file ?? ""));
if (!(await stat(abs).catch(() => null))?.isFile()) throw new NarrateError(`--recording takes a sound file (no ${file})`);
const { keepRecording } = await import("./postRecord.mjs");
const { castForProject } = await import("./castStore.mjs");
- const { characterOf, convertTargetOf, findCharacter, narratorOf } = await import("umtool-report-to-video/cast");
+ const { characterOf, convertPitchLabel, convertTargetOf, findCharacter, narratorOf } = await import("umtool-report-to-video/cast");
const { postNarrationDisclosure } = await import("umtool-report-to-video/post-narration");
const castRead = await castForProject(project.dir);
const character = as ? findCharacter(castRead.cast, String(as).replace(/^@+/, "")) : characterOf(castRead.cast, e0.handle) ?? narratorOf(castRead.cast);
@@ -753,9 +789,13 @@ export async function importRecording(project, e0, file, { as = null, label = "o
if (!character) notes.push("not converted: no character to convert to (--as <character>, or the post's author or a narrator in the cast: umtool cast add …)");
else {
const target = convertTargetOf(character);
+ // The pitch asked for this read, else the character's; semitones asked of the target's own pitch are dropped
+ // with it (a character kept at "contour +2" read once with --pitch target).
+ const pitched = { pitch: pitch ?? target.pitch ?? null, semitones: semitones ?? (pitch === "target" ? null : target.semitones ?? null) };
try {
- const r = await deriveTake(project, e, { from, op: "convert", engine: target.engine, voice: target.voice, emit, editor, ask });
- takes.push({ step: `converted to ${target.voice}`, file: r.take.file });
+ const r = await deriveTake(project, e, { from, op: "convert", engine: target.engine, voice: target.voice, ...pitched, emit, editor, ask });
+ const how = convertPitchLabel(r.take.steps?.[0]);
+ takes.push({ step: `converted to ${target.voice}${how ? ` (pitch: ${how})` : ""}`, file: r.take.file });
e = await fresh();
} catch (err) {
if (err?.name !== "OpNotInstalled" && !/not installed/i.test(String(err?.message))) throw err;
diff --git a/umtool/lib/report/postReel.mjs b/umtool/lib/report/postReel.mjs
@@ -330,32 +330,92 @@ async function copyInto(projectDir, from, rel) {
/**
* The archive's pictures (each channel's posts-media/_avatars/avatars.json,
* the editor's capture-posts store: `{ <handle>: { file, url, capturedAt } }`),
- * by handle key, the newest when two channels hold one.
+ * by handle key -- the handle without `@`, LOWERCASED: the store keys a
+ * picture by the handle as X printed it ("TheQuartering"), a card or a
+ * mention may spell it otherwise ("@thequartering") -- the newest when two
+ * stores hold one.
*
- * @returns {Promise<Map<string, { handle: string, file: string, url: string | null, capturedAt: string | null }>>}
+ * `layers` is one channels tree or the trees a project reads, in order
+ * (projects/report.mjs channelsLayersFor: its own `.shadow-channels/` or
+ * `provenance.channelsDir`, then the corpus behind it). EVERY tree's store of
+ * EVERY channel is read -- not only the project's own tree, nor the first
+ * tree that holds the channel's posts: a shadow is made by copying a
+ * channel's `posts/` (and a capture or two), never its `_avatars/`, so the
+ * pictures are in the corpus while the posts are in the shadow
+ * (quartering-diet rev 9, 11 Nov: the shadow held the three channels' posts
+ * and none of their stores, `posts avatars` read the shadow alone and copied
+ * 0 of the two pictures the corpus had -- "no picture yet for
+ * @thequartering, @madamsavvy"). A channel with no store in one tree -- or in
+ * any -- is noted in `searched` and skipped, never the end of the search.
+ *
+ * @param {string | string[]} layers
+ * @param {string[]} channels
+ * @returns {Promise<{ store: Map<string, { handle: string, file: string, url: string | null, capturedAt: string | null }>,
+ * searched: Array<{ channel: string, tree: string, dir: string, state: "read" | "none" | "unreadable", pictures: number }> }>}
*/
-export async function archiveAvatars(channelsDir, channels) {
- const out = new Map();
+export async function archiveAvatarStores(layers, channels) {
+ const trees = [...new Set((Array.isArray(layers) ? layers : [layers]).filter((d) => typeof d === "string" && d).map((d) => path.resolve(d)))];
+ const store = new Map();
+ const searched = [];
for (const slug of channels) {
- const dir = path.join(channelsDir, slug, "posts-media", ARCHIVE_AVATARS_DIR);
- let doc;
- try {
- doc = JSON.parse(await readFile(path.join(dir, ARCHIVE_AVATARS_FILE), "utf8"));
- } catch {
- continue;
- }
- if (!doc || typeof doc !== "object" || Array.isArray(doc)) continue;
- for (const [h, a] of Object.entries(doc)) {
- if (!a || typeof a !== "object" || typeof a.file !== "string" || a.file.includes("/") || a.file.includes("\\") || !AVATAR_EXT_RE.test(a.file)) continue;
- const file = path.join(dir, a.file);
- if (!(await stat(file).catch(() => null))?.isFile()) continue;
- const had = out.get(handleKey(h));
- const at = typeof a.capturedAt === "string" ? a.capturedAt : null;
- if (had && (had.capturedAt ?? "") >= (at ?? "")) continue;
- out.set(handleKey(h), { handle: h.replace(/^@/, ""), file, url: typeof a.url === "string" ? a.url : null, capturedAt: at });
+ for (const tree of trees) {
+ const dir = path.join(tree, slug, "posts-media", ARCHIVE_AVATARS_DIR);
+ let doc;
+ try {
+ doc = JSON.parse(await readFile(path.join(dir, ARCHIVE_AVATARS_FILE), "utf8"));
+ } catch (e) {
+ searched.push({ channel: slug, tree, dir, state: e?.code === "ENOENT" || e?.code === "ENOTDIR" ? "none" : "unreadable", pictures: 0 });
+ continue;
+ }
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
+ searched.push({ channel: slug, tree, dir, state: "unreadable", pictures: 0 });
+ continue;
+ }
+ let pictures = 0;
+ for (const [h, a] of Object.entries(doc)) {
+ if (!a || typeof a !== "object" || typeof a.file !== "string" || a.file.includes("/") || a.file.includes("\\") || !AVATAR_EXT_RE.test(a.file)) continue;
+ const file = path.join(dir, a.file);
+ if (!(await stat(file).catch(() => null))?.isFile()) continue;
+ pictures += 1;
+ const k = handleKey(h);
+ const had = store.get(k);
+ const at = typeof a.capturedAt === "string" ? a.capturedAt : null;
+ if (had && (had.capturedAt ?? "") >= (at ?? "")) continue;
+ store.set(k, { handle: h.replace(/^@/, ""), file, url: typeof a.url === "string" ? a.url : null, capturedAt: at });
+ }
+ searched.push({ channel: slug, tree, dir, state: "read", pictures });
}
}
- return out;
+ return { store, searched };
+}
+
+/** The archive's pictures alone (archiveAvatarStores' `store`); `layers` one channels tree or several. */
+export async function archiveAvatars(layers, channels) {
+ return (await archiveAvatarStores(layers, channels)).store;
+}
+
+/**
+ * What archiveAvatarStores searched, in words, one line per channel: each
+ * store it read (and how many pictures it holds), and each tree that had
+ * none -- so "no picture" says WHERE it looked. PURE.
+ *
+ * @param {Array<{ channel: string, tree: string, dir: string, state: string, pictures: number }>} searched
+ * @returns {string[]}
+ */
+export function avatarStoresSaid(searched) {
+ const by = new Map();
+ for (const s of searched ?? []) {
+ if (!by.has(s.channel)) by.set(s.channel, []);
+ by.get(s.channel).push(s);
+ }
+ const lines = [];
+ for (const [channel, rows] of by) {
+ const said = rows.filter((r) => r.state === "read").map((r) => `${r.pictures} picture(s) in ${r.dir}`);
+ const none = rows.filter((r) => r.state !== "read");
+ if (none.length) said.push(`no ${ARCHIVE_AVATARS_DIR}/ in ${none.map((r) => `${r.tree}${r.state === "unreadable" ? ` (${ARCHIVE_AVATARS_FILE} unreadable)` : ""}`).join(" or ")}`);
+ lines.push(`${channel}: ${said.join("; ")}`);
+ }
+ return lines;
}
/** Every handle an entry's card draws UNBLURRED (a redacted author never gets a picture). */
@@ -482,9 +542,9 @@ export async function postsReel(project, o) {
entries.push(made.entry);
dropped += made.dropped;
}
- // The authors' pictures: the archive's, for every author the cards draw unblurred that the cut has none of.
- const store = new Map();
- for (const c of channels) for (const [k, v] of await archiveAvatars(await root(c), [c])) if (!store.has(k)) store.set(k, v);
+ // The authors' pictures: the archive's, for every author the cards draw unblurred that the cut has none of --
+ // from every tree's store (the project's, the corpus behind it), not only the tree its posts were read from.
+ const store = await archiveAvatars(layers, channels);
const avatars = store.size ? await avatarsToCopy(manifest, entries, store, o.dryRun ? async (_f, rel) => rel : (from, rel) => copyInto(project.dir, from, rel)) : {};
const summary = { channels, channelsDir, archived: index.size, selected: picked.length, already, added: entries.length, droppedMedia: dropped, avatars: Object.keys(avatars) };
if (o.dryRun) return { ...summary, entries, dryRun: true, result: null, editNotes: null };
@@ -548,8 +608,8 @@ export async function postItemFromArchive(project, manifest, slug, postId, { id
* @param {{ channelsDir?: string | null }} [o]
*/
export async function archiveAvatarsFor(project, manifest, channels, entries, { channelsDir = null } = {}) {
- const dir = channelsDir ?? channelsDirFor(project.dir, manifest);
- const store = await archiveAvatars(dir, channels);
+ // Every tree the project reads (its own, the corpus behind it): a shadow copies posts, not the stores.
+ const store = await archiveAvatars(channelsDir ?? channelsLayersFor(project.dir, manifest), channels);
if (!store.size) return {};
return avatarsToCopy(manifest, entries, store, (from, rel) => copyInto(project.dir, from, rel));
}
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -195,7 +195,7 @@ export const POSTS_USAGE = [
" none: the rule as it stands",
].join("\n");
-const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label"]);
+const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--pitch", "--semitones", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label"]);
/** The valued flags that may be given more than once (each value kept, in order). */
const MULTI = new Set(["--skip-parent", "--voice-for"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
@@ -1319,8 +1319,14 @@ async function avatarCommand(projectArg, rest, { root, json, out }) {
else for (const [h, a] of Object.entries(map)) out(`@${h} ${a.src} (${a.source ?? "manual"}${a.capturedAt ? `, captured ${String(a.capturedAt).slice(0, 10)}` : ""})`);
return 0;
}
- const h = String(handle).replace(/^@/, "");
- if (!/^[A-Za-z0-9_.-]{1,64}$/.test(h)) throw new CliError(`"${handle}" is not a handle`);
+ const typed = String(handle).replace(/^@/, "");
+ if (!/^[A-Za-z0-9_.-]{1,64}$/.test(typed)) throw new CliError(`"${handle}" is not a handle`);
+ // Matched without regard to case (post-avatars.mjs handleKey): "thequartering" sets the picture of the
+ // author the cards draw as "TheQuartering", and is kept under that spelling (the first card's).
+ const { handleKey } = await import("umtool-report-to-video/post-avatars");
+ const { shownHandles } = await import("./postReel.mjs");
+ const drawnAs = ((await readManifest(project.dir))?.timeline ?? []).flatMap((e) => shownHandles(e)).map((x) => String(x).replace(/^@/, "")).find((x) => handleKey(x) === handleKey(typed));
+ const h = drawnAs && /^[A-Za-z0-9_.-]{1,64}$/.test(drawnAs) ? drawnAs : typed;
if (!file) throw new CliError(`name the picture: umtool posts avatar ${project.id} ${h} <image-file> (or off)`);
if (OFF.has(String(file).toLowerCase())) {
const { result, editNotes } = await withEditNotes(project, async () => setPostAvatar(project.dir, h, null, { token: await manifestToken(project.dir) }));
@@ -1354,10 +1360,13 @@ async function avatarsCommand(projectArg, { root, json, dryRun, out }) {
const project = await projectOf(projectArg, root);
const manifest = await readManifest(project.dir);
if (!manifest) throw new CliError(`${project.id} has no manifest`);
- const { archiveAvatars, avatarsToCopy, postChannelsOf, shownHandles } = await import("./postReel.mjs");
- const { channelsDirFor } = await import("../projects/report.mjs");
+ const { archiveAvatarStores, avatarStoresSaid, avatarsToCopy, postChannelsOf, shownHandles } = await import("./postReel.mjs");
+ const { channelsLayersFor } = await import("../projects/report.mjs");
+ const { handleKey } = await import("umtool-report-to-video/post-avatars");
const channels = postChannelsOf(manifest);
- const store = await archiveAvatars(channelsDirFor(project.dir, manifest), channels);
+ // Every tree the project reads -- its own (.shadow-channels/, provenance.channelsDir) and the corpus behind
+ // it: a shadow copies a channel's posts, never its _avatars/ (postReel.mjs archiveAvatarStores).
+ const { store, searched } = await archiveAvatarStores(channelsLayersFor(project.dir, manifest), channels);
const pics = store.size
? await avatarsToCopy(manifest, [], store, dryRun ? async (_f, rel) => rel : async (from, rel) => {
const to = path.join(project.dir, ...rel.split("/"));
@@ -1366,16 +1375,21 @@ async function avatarsCommand(projectArg, { root, json, dryRun, out }) {
return rel;
})
: {};
- const drawn = [...new Set((manifest.timeline ?? []).flatMap((e) => shownHandles(e)).map((h) => h.toLowerCase()))];
- const have = Object.keys(manifest.postAvatars ?? {}).map((h) => h.toLowerCase());
- const without = drawn.filter((h) => !have.includes(h) && !Object.keys(pics).some((p) => p.toLowerCase() === h));
+ // The authors drawn, compared by handle key (no @, any case), each said as its first card spells it.
+ const drawnAs = new Map();
+ for (const h of (manifest.timeline ?? []).flatMap((e) => shownHandles(e))) if (!drawnAs.has(handleKey(h))) drawnAs.set(handleKey(h), String(h).replace(/^@/, ""));
+ const have = new Set([...Object.keys(manifest.postAvatars ?? {}), ...Object.keys(pics)].map(handleKey));
+ const without = [...drawnAs].filter(([k]) => !have.has(k)).map(([, h]) => h);
let result = null;
if (!dryRun && Object.keys(pics).length) ({ result } = await withEditNotes(project, async () => addArchiveAvatars(project.dir, pics, { token: await manifestToken(project.dir) })));
if (json) {
- out(JSON.stringify({ ok: true, dryRun, channels, copied: pics, without, snapshot: result?.snapshot ?? null }, null, 2));
+ out(JSON.stringify({ ok: true, dryRun, channels, stores: searched, copied: pics, without, snapshot: result?.snapshot ?? null }, null, 2));
return 0;
}
- out(`${dryRun ? "would copy" : "copied"} ${Object.keys(pics).length} picture(s) from ${channels.join(" + ") || "no channel"}'s store${Object.keys(pics).length ? `: ${Object.keys(pics).map((h) => `@${h}`).join(", ")}` : ""}`);
+ const read = [...new Set(searched.filter((s) => s.state === "read").map((s) => s.channel))];
+ out(`${dryRun ? "would copy" : "copied"} ${Object.keys(pics).length} picture(s) from ${read.length ? `${read.join(" + ")}'s store${read.length > 1 ? "s" : ""}` : "no store"}${Object.keys(pics).length ? `: ${Object.keys(pics).map((h) => `@${h}`).join(", ")}` : ""}`);
+ if (!channels.length) out(" the cut has no post item from a posts channel (post: \"<channel>/<postId>\") -- no store to read");
+ for (const line of avatarStoresSaid(searched)) out(` ${line}`);
if (without.length) out(` no picture yet for ${without.map((h) => `@${h}`).join(", ")} (pnpm ops capture-posts … "avatars": true, or umtool posts avatar ${project.id} <handle> <image>)`);
return 0;
}
diff --git a/umtool/report-to-video/cast.mjs b/umtool/report-to-video/cast.mjs
@@ -10,6 +10,8 @@
// "handles": ["thequartering"], // X handles / channel slugs (no @, lower case)
// "voice": "kokoro:am_michael", // <tts engine>:<stock voice>
// "convert": { "engine": "seed-vc", "voice": "kokoro:am_michael" }, // a recording made his (optional)
+// // + "pitch": "source" | "contour" | "target", "semitones": -12…12 -- the pitch a
+// // converted read lands on (seed-vc; the editor's voice-convert, CAST_CONVERT_PITCH)
// "speakers": ["Jeremy"], // his REAL voice's name in a project's speakers.json
// "avatar": "…", "note": "…", "narrator": true } ] }
//
@@ -37,6 +39,14 @@ export const CAST_KEYS = Object.freeze(["id", "name", "handles", "voice", "conve
/** The tts engines a cast voice may name (the editor's tts op), and the convert engines (its voice-convert op). */
export const CAST_TTS_ENGINES = TTS_ENGINE_IDS;
export const CAST_CONVERT_ENGINES = Object.freeze(["openvoice", "seed-vc"]);
+/**
+ * The pitch a converted read lands on (the editor's voice-convert, common/lib/voiceApps.ts VoicePitch): the stock
+ * voice's own (`target`), the pitch it was read at (`source`), or the read's rises and falls at the stock voice's
+ * register (`contour`); `semitones` moves a followed one. The engines that can follow a pitch.
+ */
+export const CAST_CONVERT_PITCH = Object.freeze(["target", "source", "contour"]);
+export const CAST_PITCH_ENGINES = Object.freeze(["seed-vc"]);
+export const CAST_SEMITONES_MAX = 12;
/** Which engine is heavy to run (the operator's rule: Orpheus pins ~8.5 GB; Kokoro first). */
export const ENGINE_WEIGHT = Object.freeze({ kokoro: "fast", "espeak-ng": "fast", orpheus: "heavy" });
@@ -84,8 +94,9 @@ export function validateCast(doc, where = "cast.json") {
if (!isQualifiedVoice(c.voice)) errors.push(`${w}.voice must be a STOCK voice with its engine, "<${CAST_TTS_ENGINES.join("|")}>:<voice>" (got ${JSON.stringify(c.voice)})`);
if (c.convert !== undefined) {
const cv = c.convert;
- if (!isObj(cv) || Object.keys(cv).some((k) => !["engine", "voice"].includes(k))) errors.push(`${w}.convert must be {engine?, voice?}`);
+ if (!isObj(cv) || Object.keys(cv).some((k) => !["engine", "voice", "pitch", "semitones"].includes(k))) errors.push(`${w}.convert must be {engine?, voice?, pitch?, semitones?}`);
else {
+ errors.push(...convertPitchErrors(cv).map((m) => `${w}.convert.${m}`));
if (cv.engine !== undefined && !CAST_CONVERT_ENGINES.includes(cv.engine)) errors.push(`${w}.convert.engine must be one of ${CAST_CONVERT_ENGINES.join(", ")}`);
if (cv.voice !== undefined && !isQualifiedVoice(cv.voice)) errors.push(`${w}.convert.voice must be a STOCK voice, "<engine>:<voice>" (never a file or a recording)`);
}
@@ -130,9 +141,41 @@ export function castVoiceMap(cast) {
return out;
}
-/** A character's convert target -- what a recording is made into: its convert voice, else its voice. */
+/**
+ * What is wrong with a convert entry's pitch (`{engine?, pitch?, semitones?}`), as sentences that start at the key:
+ * the mode is one of CAST_CONVERT_PITCH, the semitones a number within CAST_SEMITONES_MAX, a followed pitch is an
+ * engine's that can follow one (CAST_PITCH_ENGINES; an entry with no engine takes the editor's default, which answers
+ * for itself), and semitones move a FOLLOWED pitch. The editor's op refuses the same things in its own words.
+ */
+export function convertPitchErrors(cv) {
+ const errors = [];
+ const { engine, pitch, semitones } = cv ?? {};
+ if (pitch !== undefined && !CAST_CONVERT_PITCH.includes(pitch)) errors.push(`pitch must be one of ${CAST_CONVERT_PITCH.join(", ")}`);
+ if (semitones !== undefined && !(typeof semitones === "number" && Number.isFinite(semitones) && Math.abs(semitones) <= CAST_SEMITONES_MAX)) errors.push(`semitones must be a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX}`);
+ if (errors.length) return errors;
+ const follows = pitch === "source" || pitch === "contour";
+ if (follows && engine !== undefined && !CAST_PITCH_ENGINES.includes(engine)) errors.push(`pitch "${pitch}" is ${CAST_PITCH_ENGINES.join(", ")}'s: ${engine} lands every read on the target's own pitch`);
+ if (semitones && !follows) errors.push(`semitones moves a followed pitch: it needs pitch source or contour`);
+ return errors;
+}
+
+/** How a convert entry's (or a step's) pitch is said: "contour +2 st", "source", "" for the target's own. */
+export function convertPitchLabel(cv) {
+ if (!cv?.pitch || cv.pitch === "target") return "";
+ const n = Number(cv.semitones) || 0;
+ return n ? `${cv.pitch} ${n > 0 ? "+" : "−"}${Math.abs(n)} st` : cv.pitch;
+}
+
+/**
+ * A character's convert target -- what a recording is made into: its convert voice, else its voice -- and, when the
+ * entry says one, the pitch the read lands on (`pitch`, `semitones`; absent: the editor's default).
+ */
export function convertTargetOf(c) {
- return { engine: c?.convert?.engine ?? null, voice: c?.convert?.voice ?? c?.voice ?? null };
+ const cv = c?.convert;
+ return {
+ engine: cv?.engine ?? null, voice: cv?.voice ?? c?.voice ?? null,
+ ...(cv?.pitch !== undefined ? { pitch: cv.pitch } : {}), ...(cv?.semitones !== undefined ? { semitones: cv.semitones } : {}),
+ };
}
/** The names a character's real voice may go by in a project's speakers.json (lower case, no punctuation). */
diff --git a/umtool/report-to-video/cast.test.mjs b/umtool/report-to-video/cast.test.mjs
@@ -4,7 +4,7 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import {
- castDrift, castVoiceMap, characterOf, convertTargetOf, emptyCast, findCharacter, isQualifiedVoice, narratorOf, speakerFor, takeReads, validateCast, voiceDrift, voiceRefOf,
+ castDrift, castVoiceMap, characterOf, convertPitchLabel, convertTargetOf, emptyCast, findCharacter, isQualifiedVoice, narratorOf, speakerFor, takeReads, validateCast, voiceDrift, voiceRefOf,
} from "./cast.mjs";
import { resolvePieceVoice, validateVoiceMap, voiceForPiece, voiceOverridesOf, voiceSourceOf } from "./post-say.mjs";
@@ -34,6 +34,16 @@ test("validateCast: the shape, ids, one owner a handle, stock voices only, one n
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, voice: "/tmp/jeremy.wav" }] }).some((e) => /STOCK voice with its engine/.test(e)));
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, convert: { voice: "me.wav" } }] }).some((e) => /never a file/.test(e)));
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, narrator: true }, S] }).some((e) => /one character at most is the narrator/.test(e)));
+ // The pitch a converted read lands on: a mode, semitones in range, and only what an engine can follow.
+ const conv = (convert) => validateCast({ ...emptyCast(), characters: [{ ...Q, convert }] });
+ assert.deepEqual(conv({ engine: "seed-vc", pitch: "contour", semitones: 2 }), []);
+ assert.deepEqual(conv({ pitch: "source" }), [], "no engine: the editor's default answers for itself");
+ assert.deepEqual(conv({ engine: "openvoice", pitch: "target" }), []);
+ assert.ok(conv({ pitch: "high" }).some((e) => /convert\.pitch must be one of target, source, contour/.test(e)));
+ assert.ok(conv({ pitch: "source", semitones: 13 }).some((e) => /convert\.semitones must be a number from -12 to 12/.test(e)));
+ assert.ok(conv({ engine: "openvoice", pitch: "contour" }).some((e) => /convert\.pitch "contour" is seed-vc's: openvoice lands every read on the target's own pitch/.test(e)));
+ assert.ok(conv({ engine: "seed-vc", semitones: 2 }).some((e) => /convert\.semitones moves a followed pitch/.test(e)));
+ assert.ok(conv({ engine: "seed-vc", speed: 2 }).some((e) => /convert must be \{engine\?, voice\?, pitch\?, semitones\?\}/.test(e)));
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, handles: ["@TheQuartering"] }] }).some((e) => /lower case, no @/.test(e)));
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, extra: 1 }] }).some((e) => /extra is not a character key/.test(e)));
});
@@ -47,6 +57,8 @@ test("a character by handle, id or name; the narrator; a recording's target; the
assert.deepEqual(castVoiceMap(cast), { thequartering: "kokoro:am_michael", madamsavvy: "orpheus:tara" });
assert.deepEqual(convertTargetOf(S), { engine: "seed-vc", voice: "orpheus:tara" });
assert.deepEqual(convertTargetOf({ ...Q, convert: { voice: "kokoro:am_onyx" } }), { engine: null, voice: "kokoro:am_onyx" });
+ assert.deepEqual(convertTargetOf({ ...S, convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } }), { engine: "seed-vc", voice: "orpheus:tara", pitch: "contour", semitones: 2 });
+ assert.deepEqual([convertPitchLabel(undefined), convertPitchLabel({ pitch: "target" }), convertPitchLabel({ pitch: "source" }), convertPitchLabel({ pitch: "contour", semitones: 2 }), convertPitchLabel({ pitch: "source", semitones: -1.5 })], ["", "", "source", "contour +2 st", "source −1.5 st"]);
const speakers = [{ name: "Jeremy" }, { name: "Melonie Mac" }];
assert.equal(speakerFor(Q, speakers)?.name, "Jeremy");
assert.equal(speakerFor({ id: "mm", name: "MelonieMac", handles: [] }, speakers)?.name, "Melonie Mac", "the name, its punctuation and case aside");
diff --git a/umtool/report-to-video/chrome-cues.mjs b/umtool/report-to-video/chrome-cues.mjs
@@ -14,6 +14,7 @@
//
// PURE: data in, an HTML string out.
import { pageDuration } from "./deck.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */
export const INSTANT = 0.001;
@@ -55,7 +56,7 @@ export function compileCues(init, events) {
freeAt.set(e.k, r4(at + dur));
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease });
}
- return { init, cues };
+ return { init, cues: settleFirstFrame(init, cues) };
}
/**
diff --git a/umtool/report-to-video/chrome-deck.mjs b/umtool/report-to-video/chrome-deck.mjs
@@ -46,6 +46,7 @@ import { claimsCues, claimsMarkup } from "./chrome-claims.mjs";
import { fitTallyLabel, resolveFactcheck, TALLY_WRITTEN, tallyCues, tallyFinals, tallyKey, tallyOf, tallyPopIns } from "./factcheck.mjs";
import { resolveCounter } from "./counter.mjs";
import { SUBSECTION_SEPARATOR } from "./marker-limits.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
/**
* GSAP, vendored, for every chrome region.
@@ -450,7 +451,7 @@ export function deckCues(schedule, render) {
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why });
}
return {
- init, cues, pips, slideY, choreography: ch, ...(markers.length ? { markers } : {}), ...(claims ? { claims } : {}),
+ init, cues: settleFirstFrame(init, cues, fps), pips, slideY, choreography: ch, ...(markers.length ? { markers } : {}), ...(claims ? { claims } : {}),
...(sections ? { sections: { ...sections, fuses: fuseParts ?? [], rings } } : {}),
...(sectionTitle ? { sectionTitle } : {}),
};
diff --git a/umtool/report-to-video/chrome-finale.mjs b/umtool/report-to-video/chrome-finale.mjs
@@ -26,6 +26,7 @@ import { cueTime, cueTimeAfter, finaleRail, pageDuration, resolveDeck } from "./
import { finaleClaimsMarkup } from "./chrome-claims.mjs";
import { mix, rgba, shapeCss, subtitleMarkup, subtitlePartsCss, subtitleTokens } from "./chrome-deck.mjs";
import { resolveFactcheck, tallyCells, tallyFinals, tallyOf } from "./factcheck.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
import { resolveCounter } from "./counter.mjs";
import { aboveTop, FINALE_CLAIMS, FINALE_MOTION, finaleGeometry, resolveFinale } from "./finale.mjs";
@@ -299,7 +300,7 @@ export function finaleCues(schedule, render, L = finaleLayout(schedule, render))
freeAt.set(e.k, at + dur);
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why });
}
- return { init, cues };
+ return { init, cues: settleFirstFrame(init, cues, fps) };
}
/**
diff --git a/umtool/report-to-video/chrome-instruments.mjs b/umtool/report-to-video/chrome-instruments.mjs
@@ -19,6 +19,8 @@ import { mix, rgba } from "./chrome-deck.mjs";
import { finaleLayout } from "./chrome-finale.mjs";
import { FINALE_MOTION } from "./finale.mjs";
import { resolveDial, resolveOdometer, resolveTrail } from "./instruments.mjs";
+import { TRAIL_REFLOW, trailLayout, trailPoints, trailStates } from "./trail-plan.mjs";
+import { deckAwaySpans, flashCss, flashCues, flashOn, flashTimes } from "./update-flash.mjs";
import { promiseStates, upSpans } from "./measure-extras.mjs";
import { ghostOpacity, ghostRamp, ghostTicks, resolveGhosts } from "./measure-ghosts.mjs";
import { goalBoard, goalsAt } from "./measure-goals.mjs";
@@ -99,7 +101,8 @@ function withDeck(L, schedule, render, k) {
const D = Number(schedule.transition) || 0;
const m = Math.max(D, 0.3);
for (const sd of mergedSpans(stackedStandDowns(schedule))) {
- shown.push({ at: Math.max(0, sd.from), dur: m, hide: true });
+ // Standing down from the cut's first instant is init, not a fade over the opening (cue-start.mjs).
+ shown.push({ at: Math.max(0, sd.from), dur: sd.from <= 0 ? INSTANT : m, hide: true });
if (sd.to < (schedule.total ?? Infinity) - 0.05) shown.push({ at: sd.to, dur: m, hide: false });
}
// Each change once, in time: a stand-down inside a span the deck is already away for adds nothing.
@@ -247,6 +250,33 @@ export function clearSpot(spots, obstacles, m = 0) {
/** A centred box `w` x `h` at (x, y). */
const boxAt = (x, y, w, h) => ({ x0: x - w / 2, x1: x + w / 2, y0: y - h / 2, y1: y + h / 2 });
+/** How the dial shows a remembered weight (`deck.dial.rememberedAs`): "needle" (the long grey needle, as it was), "rim", "readout", "callout". */
+export const rememberedMode = (cfg) => (["rim", "readout", "callout"].includes(cfg?.rememberedAs) ? cfg.rememberedAs : "needle");
+
+/** His highest remembered weight above every one he stated (the peak extra's `totals.peakDrift`), or null. */
+export const heaviestOf = (measure) => {
+ const drift = Array.isArray(measure?.totals?.peakDrift) ? measure.totals.peakDrift.filter(Number.isFinite) : [];
+ return drift.length ? Math.max(...drift) : null;
+};
+
+/**
+ * A remembered weight's words, from its own fields: `value` with its qualifier ("≈390"), `when` its asOf's month
+ * ("FEB 2023", null without one), `kind` "HEAVIEST HE'S SAID" when it is `heaviest` (heaviestOf) else "HE SAYS HE
+ * WAS"; and the forms the looks draw -- `head`/`sub` (the rim's flag), `line` (the readout's).
+ */
+export function rememberedWords(g, heaviest = null) {
+ const value = weightWords(g);
+ const top = heaviest !== null && Number.isFinite(g.value) && Math.abs(g.value - heaviest) < 0.05;
+ const when = g.asOf ? fmtDate(g.asOf, { day: false }) : null;
+ const kind = top ? "HEAVIEST HE'S SAID" : "HE SAYS HE WAS";
+ return {
+ value, when, kind, heaviest: top,
+ head: top ? `HEAVIEST ${value}` : value,
+ sub: [when ? `AS OF ${when}` : "REMEMBERED", top ? "HE SAYS" : ""].filter(Boolean).join(" · "),
+ line: `${kind}: ${value}${when ? ` (${when})` : ""}`,
+ };
+}
+
/**
* An as-of label's places, best first: along its ghost (angle `a`) at half the face's radius, each of its `forms`
* (its small words on one line, then on two), then stepping in toward the hub; never lower than just under the hub,
@@ -274,7 +304,7 @@ function asofSpots({ C, Rf, u, a, head, forms, px, fpx }) {
* the hub and the readout blocks. Shared by the column's dial and the
* finale's. Returns its markup and css; its cues are the caller's.
*/
-function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [], lines = [], ghosts = null, prefix = "", preState = true }) {
+function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [], lines = [], ghosts = null, prefix = "", preState = true, heaviest = null }) {
const face = dialFaceSvg({ size, scale, mark: cfg.mark, colors: { ...colors, mark: colors.accent }, labelFont: fontStack(fonts, "condensed") });
const { C, R, Rf, u } = face;
const px = (v) => Math.round(v * u * 100) / 100;
@@ -348,7 +378,8 @@ function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [],
parts.push(`<div class="ly" data-k="${prefix}gm${i}">${svg(`gm${i}h`, head)}${svg(`gm${i}o`, other)}${svg(`gm${i}x`, strike)}${svg(`gm${i}p`, flash)}</div>`);
});
}
- if (cfg.ghosts && track.remembered.length) {
+ const mode = rememberedMode(cfg);
+ if (cfg.ghosts && track.remembered.length && (mode === "needle" || mode === "callout")) {
parts.push(layer("gn", `<line x1="${C}" y1="${C + 22 * u}" x2="${C}" y2="${C - Rf + 66 * u}" stroke="${colors.ghost}" stroke-width="${px(5)}" stroke-linecap="round"/>`));
}
// The needle: a tapered blade from a counterweight through the hub.
@@ -359,7 +390,7 @@ function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [],
// The as-of labels, each by its ghost, up while it is the latest -- and never on a scale figure (rev 9: "≈390 ·
// AS OF FEB 2025 · TOLD 4×" sat on the 380). Along its ghost, never down into the readout's words under the hub;
// where its box would touch a figure's, its words go on two lines, then it steps in toward the hub.
- if (cfg.ghosts) {
+ if (cfg.ghosts && mode === "needle") {
track.remembered.forEach((g, j) => {
const a = dialAngle(g.value, scale);
const head = weightWords(g);
@@ -371,6 +402,52 @@ function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [],
parts.push(`<div class="asof" data-k="${prefix}ga${j}" style="left:${spot.x}px; top:${spot.y}px"><b>${esc(head)}</b>${spot.lines.map((l) => `<span>${esc(l)}</span>`).join("")}</div>`);
});
}
+ // THE REMEMBERED WEIGHT'S OTHER LOOKS (`deck.dial.rememberedAs`, 11 Nov: the long grey second needle and its
+ // small words crossed the main needle and the readout and did not say what the weight was). Each from the
+ // ledger's own fields -- the qualifier, the asOf, "heaviest" only for the record's highest remembered weight above
+ // every one he stated (the peak extra's `totals.peakDrift`) -- never words of ours.
+ // rim a bold marker on the rim at the value and a flag inside it, clear of the hub, the figures and the readout
+ // readout a line in the readout under the date ("HEAVIEST HE'S SAID: ≈390 (FEB 2023)"), a marker on the rim
+ // callout a ghost needle sweeps to the value as he says it, a clear label holds ~2 s, then the rim's flag
+ const readoutBox = { x0: C - 128 * u, x1: C + 128 * u, y0: C + 60 * u, y1: C + 230 * u };
+ if (cfg.ghosts && mode !== "needle") {
+ const ink = mix(colors.ghost, colors.fg, 0.55);
+ track.remembered.forEach((g, j) => {
+ const w = rememberedWords(g, heaviest);
+ const a = dialAngle(g.value, scale);
+ // The marker: a bold wedge across the rim, pointing in -- the scale's own ticks show through either side.
+ parts.push(layer(`gk${j}`, `<polygon points="${C - 9 * u},${C - R - 3 * u} ${C + 9 * u},${C - R - 3 * u} ${C + 3 * u},${C - Rf + 30 * u} ${C - 3 * u},${C - Rf + 30 * u}" fill="${ink}" stroke="${colors.bg}" stroke-width="${px(2)}"/>`));
+ if (mode === "readout") {
+ parts.push(`<div class="rline" data-k="${prefix}gr${j}" style="top:${C + 188 * u}px">${esc(w.line)}</div>`);
+ return;
+ }
+ // The flag: inside the rim by the marker -- along it, then turning a little either way, stepping in -- clear of
+ // the scale's figures, the hub, the readout and the needle where it stands as he says it.
+ const hb = px(22), hs = fpx(12);
+ const flagLines = [w.heaviest ? "HEAVIEST" : "REMEMBERED", w.when ? w.when : ""].filter(Boolean);
+ const fw = Math.max(w.value.length * hb * 0.56, ...flagLines.map((l) => l.length * hs * 0.66)) + 2 * px(8);
+ const fh = hb * 1.08 + flagLines.length * hs * 1.12 + 2 * px(4);
+ const stands = [...track.current].filter((c) => c.t <= g.t + 1e-9 && Number.isFinite(c.value)).pop();
+ const needle = [];
+ if (stands) {
+ const na = dialAngle(stands.value, scale);
+ for (let r = 24 * u; r <= Rf - 30 * u; r += 14 * u) { const [x, y] = polar(C, C, r, na); needle.push(boxAt(x, y, 10 * u, 10 * u)); }
+ }
+ const spots = [];
+ for (const da of [0, -8, 8, -16, 16, -24, 24, -32, 32, -40, -48]) {
+ for (let r = Rf * 0.64; r >= Rf * 0.34 - 1e-9; r -= Rf * 0.04) {
+ const [x, y] = polar(C, C, r, a + da);
+ spots.push({ x, y, box: boxAt(x, y, fw, fh) });
+ }
+ }
+ const spot = clearSpot(spots, [...faceFigures.map((f) => f.box), hub, readoutBox, ...needle], 4 * u);
+ const [l0, l1] = flagLines;
+ parts.push(`<div class="rflag" data-k="${prefix}gl${j}" style="left:${spot.x}px; top:${spot.y}px"><span>${esc(l0)}</span><b>${esc(w.value)}</b>${l1 ? `<span>${esc(l1)}</span>` : ""}</div>`);
+ if (mode === "callout") {
+ parts.push(`<div class="rcall" data-k="${prefix}gc${j}" style="top:${C - 104 * u}px"><span>${esc(w.kind)}</span><b>${esc(w.value)}</b>${w.when ? `<span>AS OF ${esc(w.when)}</span>` : ""}</div>`);
+ }
+ });
+ }
// The readout under the hub: the words, the weight, the weighing's date, the goal.
// Inside the face's open quarter: each line kept within the chord at its height.
parts.push(`<div class="rlab" style="top:${C + 72 * u}px">${esc(cfg.label)}</div>`);
@@ -382,7 +459,9 @@ function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [],
});
if (cfg.goal) {
lines.forEach((g, j) => {
- parts.push(`<div class="goalw${g.missed ? " miss" : ""}" data-k="${prefix}gw${j}" style="top:${C + 188 * u}px">${esc(g.words)}</div>`);
+ // Under the remembered line when the readout carries one (rememberedAs "readout").
+ const gy = cfg.ghosts && mode === "readout" && track.remembered.length ? C + 210 * u : C + 188 * u;
+ parts.push(`<div class="goalw${g.missed ? " miss" : ""}" data-k="${prefix}gw${j}" style="top:${gy}px">${esc(g.words)}</div>`);
});
}
const css = `
@@ -408,7 +487,19 @@ function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [],
color: ${colors.accent}; white-space: nowrap; padding: ${px(1)}px ${px(6)}px; border-radius: ${px(5)}px; background: ${rgba(colors.face, 0.9)}; }
.dial .goalw { position: absolute; left: 0; width: ${size}px; text-align: center; font-family: ${fontStack(fonts, "bold")};
font-size: ${fpx(17)}px; line-height: ${Math.max(15, px(20))}px; letter-spacing: 0.05em; color: ${colors.amber}; white-space: nowrap; }
- .dial .goalw.miss { color: ${colors.needle}; }`;
+ .dial .goalw.miss { color: ${colors.needle}; }${cfg.ghosts && mode !== "needle" && track.remembered.length ? `
+ .dial .rflag { position: absolute; transform: translate(-50%, -50%); text-align: center; white-space: nowrap; line-height: 1.08;
+ padding: ${px(4)}px ${px(8)}px; border-radius: ${px(6)}px; background: ${rgba(colors.face, 0.92)};
+ border: ${px(1.5)}px solid ${rgba(mix(colors.ghost, colors.fg, 0.55), 0.7)}; color: ${mix(colors.ghost, colors.fg, 0.6)}; }
+ .dial .rflag b { display: block; font-family: ${fontStack(fonts, "display")}; font-weight: 400; font-size: ${px(22)}px; }
+ .dial .rflag span { display: block; font-family: ${fontStack(fonts, "condensed")}; font-size: ${fpx(12)}px; letter-spacing: 0.1em; color: ${colors.ghost}; }
+ .dial .rline { position: absolute; left: 0; width: ${size}px; text-align: center; font-family: ${fontStack(fonts, "condensed")};
+ font-size: ${fpx(16)}px; line-height: ${Math.max(15, px(20))}px; letter-spacing: 0.06em; color: ${mix(colors.ghost, colors.fg, 0.55)}; white-space: nowrap; }
+ .dial .rcall { position: absolute; left: 50%; transform: translate(-50%, -50%); text-align: center; white-space: nowrap; line-height: 1.05;
+ padding: ${px(6)}px ${px(14)}px; border-radius: ${px(8)}px; background: ${rgba(colors.face, 0.94)};
+ border: ${px(2)}px solid ${mix(colors.ghost, colors.fg, 0.55)}; color: ${mix(colors.ghost, colors.fg, 0.7)}; }
+ .dial .rcall b { display: block; font-family: ${fontStack(fonts, "display")}; font-weight: 400; font-size: ${px(40)}px; }
+ .dial .rcall span { display: block; font-family: ${fontStack(fonts, "condensed")}; font-size: ${fpx(15)}px; letter-spacing: 0.1em; color: ${colors.ghost}; }` : ""}`;
return { html: `<div class="dial">${parts.join("\n ")}</div>`, css, face };
}
@@ -461,7 +552,8 @@ function dialCues(L, { track, scale, cfg, marks = [], lines = [], ghosts = null,
L.add(k(`gb${j}`), g.t, M.fade, { autoAlpha: 1 }, "power1.out");
}
});
- if (track.remembered.length && finale) {
+ if (rememberedMode(cfg) !== "needle") rememberedCues(L, { track, scale, cfg, k, finale });
+ else if (track.remembered.length && finale) {
// All at once: the long ghost and its words on the last (the finale puts his highest there).
const last = track.remembered.length - 1;
const g = track.remembered[last];
@@ -482,6 +574,48 @@ function dialCues(L, { track, scale, cfg, marks = [], lines = [], ghosts = null,
if (ghosts) ghostCues(L, { ghosts, scale, k, finale, at });
}
+/** The callout's hold (rememberedAs "callout"): the label up this long after he says it, then the rim's flag. */
+export const CALLOUT_HOLD = 2.2;
+
+/**
+ * The remembered weight's cues in the looks other than the long needle (dialParts, `deck.dial.rememberedAs`): its
+ * rim marker and its flag (or its readout line) up while it is the latest remembered; with "callout", first the
+ * ghost needle sweeping from where the needle stands to the value and the label held CALLOUT_HOLD s. In the finale,
+ * the last one's, all at once.
+ */
+function rememberedCues(L, { track, scale, cfg, k, finale }) {
+ const M = INSTRUMENT_MOTION;
+ const R = track.remembered;
+ if (!R.length) return;
+ const mode = rememberedMode(cfg);
+ const call = mode === "callout" && !finale;
+ const label = mode === "readout" ? "gr" : "gl";
+ const startOf = (g) => (call ? g.t + CALLOUT_HOLD : g.t);
+ R.forEach((g, j) => {
+ L.set(k(`gk${j}`), { rotation: dialAngle(g.value, scale), autoAlpha: 0 });
+ L.set(k(`${label}${j}`), { autoAlpha: 0 });
+ if (call) L.set(k(`gc${j}`), { autoAlpha: 0 });
+ if (finale && j !== R.length - 1) return;
+ const next = finale ? null : R[j + 1];
+ for (const key of [`gk${j}`, `${label}${j}`]) {
+ L.add(k(key), startOf(g), M.fade, { autoAlpha: 1 }, "power1.out");
+ if (next) L.add(k(key), startOf(next), M.fade * 0.6, { autoAlpha: 0 }, "power1.in");
+ }
+ });
+ if (!call) return;
+ const a0 = dialAngle(scale.min, scale);
+ L.set(k("gn"), { rotation: dialAngle(R[0].value, scale), autoAlpha: 0 });
+ R.forEach((g, j) => {
+ // From where the needle stands as he says it (his stated weight in force then; the scale's foot before one).
+ const cur = [...track.current].filter((c) => c.t <= g.t + 1e-9 && Number.isFinite(c.value)).pop();
+ L.add(k("gn"), g.t, INSTANT, { rotation: cur ? dialAngle(cur.value, scale) : a0, autoAlpha: 0.9 }, "none");
+ L.add(k("gn"), g.t + 0.05, M.needle, { rotation: dialAngle(g.value, scale) }, "power2.inOut");
+ L.add(k("gn"), g.t + CALLOUT_HOLD, 0.4, { autoAlpha: 0 }, "power1.in");
+ L.add(k(`gc${j}`), g.t + 0.25, M.fade, { autoAlpha: 1 }, "power1.out");
+ L.add(k(`gc${j}`), g.t + CALLOUT_HOLD, 0.4, { autoAlpha: 0 }, "power1.in");
+ });
+}
+
/**
* The goal board's cues (goalMarks, goalLines): each mark's status from each board state -- the headline's triangle,
* an other's tick, a miss struck in red with a flash -- and the goal line's words.
@@ -578,16 +712,26 @@ export function dialHtml(schedule, render, opts = {}) {
const marks = goalMarks(board, M.scale);
const lines = goalLines(board);
const ghosts = ghostsOf(M, render, colors);
- const parts = dialParts({ size, ox: Math.floor((W - size) / 2), oy: Math.floor((H - size) / 2), scale: M.scale, cfg, colors, fonts, track, marks, lines, ghosts });
+ const parts = dialParts({ size, ox: Math.floor((W - size) / 2), oy: Math.floor((H - size) / 2), scale: M.scale, cfg, colors, fonts, track, marks, lines, ghosts, heaviest: heaviestOf(M) });
const L = cueList(fps);
withDeck(L, schedule, render, "rt");
dialCues(L, { track, scale: M.scale, cfg, marks, lines, ghosts });
+ // THE UPDATE FLASH (update-flash.mjs): the bezel lights as a weight is stated or remembered, or the goal changes.
+ let flash = { html: "", css: "" };
+ if (flashOn(render, cfg.flash)) {
+ const times = [...track.current.slice(1), ...track.remembered, ...track.goals.slice(1)].map((x) => x.t);
+ flashCues(L, "fl", flashTimes(times, { fps, away: deckAwaySpans(schedule, render) }));
+ flash = {
+ html: `<div class="flw" style="left:${Math.floor((W - size) / 2)}px; top:${Math.floor((H - size) / 2)}px; width:${size}px; height:${size}px"><div class="fl" data-k="fl"></div></div>`,
+ css: `\n .flw { position: absolute; }\n ${flashCss(".flw .fl", colors.accent, { radius: "50%", width: 3 })}`,
+ };
+ }
const { init, cues } = L.build();
return pageHtml({
id: "dial", W, H, fps, fonts, gsap: opts.gsap,
data: { total: r4(schedule.total), window: windowOf(schedule, opts, "dial"), init, cues },
- css: `#rt { position: absolute; inset: 0; }${parts.css}`,
- body: `<div id="rt" data-k="rt">${parts.html}</div>`,
+ css: `#rt { position: absolute; inset: 0; }${parts.css}${flash.css}`,
+ body: `<div id="rt" data-k="rt">${parts.html}${flash.html}</div>`,
});
}
@@ -681,12 +825,19 @@ export function odometerHtml(schedule, render, opts = {}) {
});
if (cfg.runs) blocks(L, track.lost, "rn");
if (cfg.net) blocks(L, track.net, "nt");
+ // THE UPDATE FLASH (update-flash.mjs): the card lights as the pounds lost go up, its runs or NET change.
+ let flash = { html: "", css: "" };
+ if (flashOn(render, cfg.flash)) {
+ const times = [...track.lost.slice(1), ...(cfg.net ? track.net.slice(1) : [])].map((x) => x.t);
+ flashCues(L, "fl", flashTimes(times, { fps, away: deckAwaySpans(schedule, render) }));
+ flash = { html: `<div class="fl" data-k="fl"></div>`, css: `\n ${flashCss("#rt > .fl", colors.accent, { radius: `${Math.round(10 * u * 100) / 100}px`, width: 2 })}` };
+ }
const { init, cues } = L.build();
return pageHtml({
id: "odometer", W, H, fps, fonts, gsap: opts.gsap,
data: { total: r4(schedule.total), window: windowOf(schedule, opts, "odometer"), init, cues },
- css: `#rt { position: absolute; inset: 0; }${parts.css}`,
- body: `<div id="rt" data-k="rt">${parts.html}</div>`,
+ css: `#rt { position: absolute; inset: 0; }${parts.css}${flash.css}`,
+ body: `<div id="rt" data-k="rt">${parts.html}${flash.html}</div>`,
});
}
@@ -707,58 +858,126 @@ export function trailHtml(schedule, render, opts = {}) {
const colors = colorsOf(render);
const track = measureTrack(M);
const mark = Number.isFinite(cfg.mark) ? cfg.mark : null;
- // By date: each stated weight at the day it was weighed, in date order.
- const pts = track.stated
- .map((p, n) => ({ ...p, day: dayNumber(p.date), n }))
- .filter((p) => Number.isFinite(p.day))
- .sort((a, b) => a.day - b.day || a.n - b.n);
- const x0 = px(54), x1 = W - px(18), y0 = px(38), y1 = H - px(26);
- let d0 = pts.length ? pts[0].day : 0, d1 = pts.length ? pts[pts.length - 1].day : 1;
- if (d1 - d0 < 60) { d0 -= 30; d1 += 30; }
- const vals = pts.map((p) => p.value).concat(mark !== null ? [mark] : []);
- const lo = vals.length ? Math.floor((Math.min(...vals) - 5) / 10) * 10 : M.scale.min;
- const hi = vals.length ? Math.ceil((Math.max(...vals) + 5) / 10) * 10 : M.scale.max;
- const X = (d) => r4(x0 + ((d - d0) / (d1 - d0)) * (x1 - x0));
- const Y = (v) => r4(y1 - ((v - lo) / Math.max(1, hi - lo)) * (y1 - y0));
- const parts = [];
- // The years along the foot.
- const yearOf = (d) => new Date(d * 86400000).getUTCFullYear();
- for (let yr = yearOf(d0) + 1; yr <= yearOf(d1); yr += 1) {
- const x = X(Date.UTC(yr, 0, 1) / 86400000);
- parts.push(`<div class="yr" style="left:${x}px; top:${y1 + px(4)}px">${yr}</div><div class="ytick" style="left:${x}px; top:${y0}px; height:${y1 - y0}px"></div>`);
- }
- if (mark !== null && mark >= lo && mark <= hi) {
- parts.push(`<div class="mark" style="left:${x0}px; top:${Y(mark)}px; width:${x1 - x0}px"></div><div class="marklab" style="left:${px(12)}px; top:${Y(mark)}px">${mark}</div>`);
- }
- parts.push(`<div class="lohi" style="left:${px(12)}px; top:${y0}px">${hi}</div><div class="lohi" style="left:${px(12)}px; top:${y1}px">${lo}</div>`);
+ // THE PLAN (trail-plan.mjs): a state per moment a weight is said -- stated, and remembered unless `remembered` is
+ // off -- each laid out on axes that fit what is shown, the time axis broken across long empty stretches.
+ const pts = trailPoints(M, { remembered: cfg.remembered !== false });
+ const box = { x0: px(54), x1: W - px(18), y0: px(38), y1: H - px(26), gapPx: px(22), yearPx: px(34) };
+ const states = trailStates(pts, box, { gap: cfg.gap ?? "auto", mark, bounds: cfg.bounds ?? "fit" });
+ const first = states[0]?.layout ?? trailLayout([], box, { mark });
+ const { y0, y1 } = box;
const L = cueList(fps);
withDeck(L, schedule, render, "rt");
const M2 = INSTRUMENT_MOTION;
- // The line: each pair of neighbours by date, drawn once both have been said.
- for (let j = 0; j + 1 < pts.length; j += 1) {
- const a = pts[j], b = pts[j + 1];
- const xa = X(a.day), ya = Y(a.value), xb = X(b.day), yb = Y(b.value);
- const len = r4(Math.hypot(xb - xa, yb - ya));
- const ang = r4((Math.atan2(yb - ya, xb - xa) * 180) / Math.PI);
- parts.push(`<div class="seg" data-k="s${j}" style="left:${xa}px; top:${ya}px; width:${len}px"></div>`);
- L.set(`s${j}`, { rotation: ang, scaleX: 0, transformOrigin: "0% 50%" });
- L.add(`s${j}`, Math.max(a.t, b.t), M2.segment, { scaleX: 1 }, "power2.out");
- }
- pts.forEach((p, j) => {
- parts.push(`<div class="pt${p.qualifier ? " q" : ""}" data-k="p${j}" style="left:${X(p.day)}px; top:${Y(p.value)}px"></div>`);
- L.set(`p${j}`, { autoAlpha: 0, scale: 0.3 });
- L.add(`p${j}`, p.t, M2.point, { autoAlpha: 1, scale: 1 }, "back.out(2)");
+ const RF = TRAIL_REFLOW;
+ const parts = [];
+ const moved = (a, b) => !a || !b || Math.abs(a.x - b.x) > 0.05 || Math.abs(a.y - b.y) > 0.05;
+
+ // The axes: a label per year (its tick inside a cluster), a break per gap between clusters, the bounds' two figures
+ // and the mark line -- each shown, moved and hidden state by state; before the first weight, the first state's axes.
+ const yearKeys = new Map();
+ const gapKeys = new Map();
+ const bounds = new Map();
+ states.forEach((st) => {
+ for (const y of st.layout.years) if (!yearKeys.has(y.key)) yearKeys.set(y.key, y);
+ for (const g of st.layout.gaps) if (!gapKeys.has(g.key)) gapKeys.set(g.key, g);
+ for (const v of [`hi${st.layout.hi}`, `lo${st.layout.lo}`]) bounds.set(v, null);
});
- // The latest said, ringed in the needle's red: it travels to each as it lands.
- if (pts.length) {
- parts.push(`<div class="ring" data-k="pl"></div>`);
- const inCut = [...pts].sort((a, b) => a.t - b.t || a.n - b.n);
- L.set("pl", { x: X(inCut[0].day), y: Y(inCut[0].value), autoAlpha: 0 });
- inCut.forEach((p, j) => {
- if (j === 0) L.add("pl", p.t, M2.point, { autoAlpha: 1 }, "power1.out");
- else L.add("pl", p.t, M2.point, { x: X(p.day), y: Y(p.value) }, "power2.inOut");
- });
+ if (!states.length) for (const v of [`hi${first.hi}`, `lo${first.lo}`]) bounds.set(v, null);
+ for (const [key, y] of yearKeys) {
+ parts.push(`<div class="yw" data-k="y${key}">${y.tick ? `<div class="ytick" style="top:${y0}px; height:${r4(y1 - y0)}px"></div>` : ""}<div class="yr" style="top:${r4(y1 + px(4))}px">${y.text}</div></div>`);
+ }
+ for (const [key] of gapKeys) {
+ parts.push(`<div class="gp" data-k="g${key}" style="top:${y0}px; height:${r4(y1 - y0)}px"><div class="gz">//</div></div>`);
}
+ for (const key of bounds.keys()) {
+ parts.push(`<div class="lohi" data-k="b${key}" style="left:${px(12)}px; top:${key.startsWith("hi") ? y0 : y1}px">${key.slice(2)}</div>`);
+ }
+ if (mark !== null) parts.push(`<div class="mark" data-k="mk" style="left:${box.x0}px; width:${r4(box.x1 - box.x0)}px"></div><div class="marklab" data-k="ml" style="left:${px(12)}px">${mark}</div>`);
+ const axisAt = (layout, at, prev) => {
+ const vis = (list) => new Map(list.map((x) => [x.key, x]));
+ const ys = vis(layout.years), gs = vis(layout.gaps);
+ const pys = prev ? vis(prev.years) : new Map(), pgs = prev ? vis(prev.gaps) : new Map();
+ for (const [key] of yearKeys) {
+ const now = ys.get(key), was = pys.get(key);
+ if (!prev) { L.set(`y${key}`, { x: (now ?? yearKeys.get(key)).x ?? 0, autoAlpha: now ? 1 : 0 }); continue; }
+ if (now && was) { if (Math.abs(now.x - was.x) > 0.05) L.add(`y${key}`, at, RF, { x: now.x }, "power2.inOut"); }
+ else if (now) L.add(`y${key}`, at, RF, { x: now.x, autoAlpha: 1 }, "power2.out");
+ else if (was) L.add(`y${key}`, at, RF * 0.6, { autoAlpha: 0 }, "power1.in");
+ }
+ for (const [key] of gapKeys) {
+ const now = gs.get(key), was = pgs.get(key);
+ if (!prev) { L.set(`g${key}`, { x: (now ?? gapKeys.get(key)).x, autoAlpha: now ? 1 : 0 }); continue; }
+ if (now && was) { if (Math.abs(now.x - was.x) > 0.05) L.add(`g${key}`, at, RF, { x: now.x }, "power2.inOut"); }
+ else if (now) L.add(`g${key}`, at, RF, { x: now.x, autoAlpha: 1 }, "power2.out");
+ else if (was) L.add(`g${key}`, at, RF * 0.6, { autoAlpha: 0 }, "power1.in");
+ }
+ // A bound's figure gives way to the mark's when they would sit on each other.
+ const clear = (lay, v) => mark === null || Math.abs(lay.Y(mark) - lay.Y(v)) >= px(14);
+ const shows = (lay, key) => (key === `hi${lay.hi}` && clear(lay, lay.hi)) || (key === `lo${lay.lo}` && clear(lay, lay.lo));
+ for (const key of bounds.keys()) {
+ const on = shows(layout, key);
+ const was = prev ? shows(prev, key) : null;
+ if (!prev) L.set(`b${key}`, { autoAlpha: on ? 1 : 0 });
+ else if (on !== was) L.add(`b${key}`, at, RF * 0.6, { autoAlpha: on ? 1 : 0 }, "power1.inOut");
+ }
+ if (mark !== null) {
+ const y = layout.Y(mark);
+ if (!prev) { L.set("mk", { y }); L.set("ml", { y, yPercent: -50 }); }
+ else if (Math.abs(prev.Y(mark) - y) > 0.05) { L.add("mk", at, RF, { y }, "power2.inOut"); L.add("ml", at, RF, { y }, "power2.inOut"); }
+ }
+ };
+ axisAt(first, 0, null);
+
+ // The points: each pops in at its place in the state it is said in, then moves with every reflow after.
+ const firstState = new Map();
+ states.forEach((st, j) => { for (const n of st.shown) if (!firstState.has(n)) firstState.set(n, j); });
+ for (const p of pts) {
+ const j = firstState.get(p.n);
+ const at = states[j].pos.get(p.n);
+ const cls = `pt${p.kind === "remembered" ? " rem" : ""}${p.qualifier ? " q" : ""}`;
+ parts.push(`<div class="${cls}" data-k="p${p.n}"></div>`);
+ L.set(`p${p.n}`, { x: at.x, y: at.y, autoAlpha: 0, scale: 0.3 });
+ L.add(`p${p.n}`, p.t, M2.point, { autoAlpha: 1, scale: 1 }, "back.out(2)");
+ }
+ // The line: neighbours by date among the stated points shown, a pair drawn in when it first is one, moved with the
+ // reflows while it lasts, gone the moment a weight said later lands between them. Across a break it is dotted.
+ const pairFirst = new Map();
+ states.forEach((st, j) => { for (const pr of st.pairs) if (!pairFirst.has(pr.key)) pairFirst.set(pr.key, { ...pr, j }); });
+ const geomOf = (st, pr) => {
+ const a = st.pos.get(pr.a), b = st.pos.get(pr.b);
+ return { x: a.x, y: a.y, width: r4(Math.hypot(b.x - a.x, b.y - a.y)), rotation: r4((Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI) };
+ };
+ for (const [key, pr] of pairFirst) {
+ parts.push(`<div class="seg${pr.gap ? " gap" : ""}" data-k="s${key}"></div>`);
+ L.set(`s${key}`, { ...geomOf(states[pr.j], pr), scaleX: 0, autoAlpha: 1, transformOrigin: "0% 50%" });
+ L.add(`s${key}`, states[pr.j].at, M2.segment, { scaleX: 1 }, "power2.out");
+ }
+ // The latest said, ringed in the needle's red: it travels to each as it lands, and with the reflows.
+ if (pts.length) parts.push(`<div class="ring" data-k="pl"></div>`);
+ states.forEach((st, j) => {
+ const prev = j ? states[j - 1] : null;
+ const latest = pts.filter((p) => p.t <= st.at + 1e-9).at(-1);
+ if (!prev) {
+ const at0 = st.pos.get(latest.n);
+ L.set("pl", { x: at0.x, y: at0.y, autoAlpha: 0 });
+ L.add("pl", st.at, M2.point, { autoAlpha: 1 }, "power1.out");
+ return;
+ }
+ axisAt(st.layout, st.at, prev.layout);
+ for (const n of prev.shown) {
+ const a = prev.pos.get(n), b = st.pos.get(n);
+ if (moved(a, b)) L.add(`p${n}`, st.at, RF, { x: b.x, y: b.y }, "power2.inOut");
+ }
+ const was = new Map(prev.pairs.map((pr) => [pr.key, pr]));
+ const now = new Map(st.pairs.map((pr) => [pr.key, pr]));
+ for (const [key, pr] of was) {
+ if (!now.has(key)) { L.add(`s${key}`, st.at, RF * 0.5, { autoAlpha: 0 }, "power1.in"); continue; }
+ const g0 = geomOf(prev, pr), g1 = geomOf(st, pr);
+ if (moved(g0, g1) || Math.abs(g0.width - g1.width) > 0.05 || Math.abs(g0.rotation - g1.rotation) > 0.05) L.add(`s${key}`, st.at, RF, g1, "power2.inOut");
+ }
+ const ring = st.pos.get(latest.n);
+ L.add("pl", st.at, RF, { x: ring.x, y: ring.y }, "power2.inOut");
+ });
// How many times he says he is under 300, counted as each lands.
const counts = cfg.count && mark === 300 ? track.under.slice().sort((a, b) => a.t - b.t).map((x, n) => ({ t: x.t, n: n + 1 })) : [];
counts.forEach((c) => parts.push(`<div class="cnt" data-k="uc${c.n - 1}">UNDER ${mark} · SAID ${c.n}×</div>`));
@@ -770,26 +989,39 @@ export function trailHtml(schedule, render, opts = {}) {
if (sp.out < schedule.total - 0.05) L.add("ty", sp.out, 0.4, { autoAlpha: 1 }, "power1.out");
}
L.set("ty", { autoAlpha: 1 });
+ // THE UPDATE FLASH (update-flash.mjs): the card lights as each weight lands on it.
+ const flashing = flashOn(render, cfg.flash);
+ if (flashing) {
+ flashCues(L, "fl", flashTimes(states.map((st) => st.at), { fps, away: deckAwaySpans(schedule, render) }));
+ parts.push(`<div class="fl" data-k="fl"></div>`);
+ }
const { init, cues } = L.build();
const css = `
#rt { position: absolute; inset: 0; }
- .ty { position: absolute; inset: 0; }
- .trail { position: absolute; inset: 0; border-radius: ${px(10)}px; background: ${colors.card}; }
+ .ty { position: absolute; inset: 0; }${flashing ? `\n ${flashCss(".trail .fl", colors.accent, { radius: `${px(10)}px`, width: 2 })}` : ""}
+ .trail { position: absolute; inset: 0; border-radius: ${px(10)}px; background: ${colors.card}; overflow: hidden; }
.trail .lab { position: absolute; left: ${px(14)}px; top: ${px(10)}px; font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(14)}px;
letter-spacing: 0.12em; color: ${colors.muted}; white-space: nowrap; }
.trail .cnt { position: absolute; right: ${px(16)}px; top: ${px(9)}px; font-family: ${fontStack(fonts, "bold")}; font-size: ${px(15)}px;
letter-spacing: 0.06em; color: ${colors.accent}; white-space: nowrap; }
- .trail .yr { position: absolute; transform: translateX(-50%); font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(13)}px;
- color: ${colors.muted}; letter-spacing: 0.06em; }
- .trail .ytick { position: absolute; width: 1px; background: ${colors.rule}; }
- .trail .mark { position: absolute; height: 0; border-top: ${px(2)}px dashed ${rgba(colors.accent, 0.75)}; }
+ .trail .yw { position: absolute; left: 0; top: 0; width: 0; height: 0; }
+ .trail .yr { position: absolute; left: 0; transform: translateX(-50%); font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(13)}px;
+ color: ${colors.muted}; letter-spacing: 0.06em; white-space: nowrap; }
+ .trail .ytick { position: absolute; left: 0; width: 1px; background: ${colors.rule}; }
+ .trail .gp { position: absolute; left: 0; width: ${px(14)}px; margin-left: -${px(7)}px; background: ${rgba(colors.muted, 0.08)}; }
+ .trail .gz { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); font-family: ${fontStack(fonts, "condensed")};
+ font-size: ${px(13)}px; color: ${colors.muted}; letter-spacing: -0.1em; }
+ .trail .mark { position: absolute; top: 0; height: 0; border-top: ${px(2)}px dashed ${rgba(colors.accent, 0.75)}; }
.trail .marklab, .trail .lohi { position: absolute; transform: translateY(-50%); font-family: ${fontStack(fonts, "condensed")};
font-size: ${px(13)}px; color: ${colors.muted}; }
- .trail .marklab { color: ${colors.accent}; font-family: ${fontStack(fonts, "bold")}; }
- .trail .seg { position: absolute; height: ${px(2.6)}px; margin-top: -${px(1.3)}px; background: ${colors.accent}; border-radius: ${px(2)}px; }
- .trail .pt { position: absolute; width: ${px(10)}px; height: ${px(10)}px; margin: -${px(5)}px 0 0 -${px(5)}px; border-radius: 50%;
+ .trail .marklab { top: 0; transform: none; color: ${colors.accent}; font-family: ${fontStack(fonts, "bold")}; }
+ .trail .seg { position: absolute; left: 0; top: 0; height: ${px(2.6)}px; margin-top: -${px(1.3)}px; background: ${colors.accent}; border-radius: ${px(2)}px; }
+ .trail .seg.gap { height: 0; margin-top: -${px(1)}px; background: none; border-top: ${px(2)}px dotted ${rgba(colors.accent, 0.55)}; border-radius: 0; }
+ .trail .pt { position: absolute; left: 0; top: 0; width: ${px(10)}px; height: ${px(10)}px; margin: -${px(5)}px 0 0 -${px(5)}px; border-radius: 50%;
background: ${colors.accent}; border: ${px(2)}px solid ${colors.card}; }
.trail .pt.q { background: ${colors.card}; border: ${px(2.4)}px solid ${colors.accent}; }
+ .trail .pt.rem { background: ${colors.card}; border: ${px(2.4)}px solid ${colors.ghost}; }
+ .trail .pt.rem.q { border-style: dashed; }
.trail .ring { position: absolute; left: 0; top: 0; width: ${px(20)}px; height: ${px(20)}px; margin: -${px(10)}px 0 0 -${px(10)}px;
border-radius: 50%; border: ${px(3)}px solid ${colors.needle}; }`;
return pageHtml({
@@ -934,7 +1166,7 @@ export function dialFinaleHtml(schedule, render, window, opts = {}) {
const k = size / 524;
const dial = dialParts({
size, ox: portrait ? Math.floor((W - size) / 2) : 0, oy: portrait ? titleH + Math.round(18 * u) + Math.floor((cardH - size) / 2) : Math.floor((H - size) / 2),
- scale: M.scale, cfg, colors, fonts, track, marks, lines, ghosts, prefix: "f", preState: false,
+ scale: M.scale, cfg, colors, fonts, track, marks, lines, ghosts, prefix: "f", preState: false, heaviest: heaviestOf(M),
});
const rw = portrait ? W - Math.round(48 * u) : W - size - Math.round(40 * k);
const top = Math.max(Number(M.totals?.lost) || 0, nums.lost);
diff --git a/umtool/report-to-video/chrome-measure-extras.mjs b/umtool/report-to-video/chrome-measure-extras.mjs
@@ -22,6 +22,7 @@ import {
import { dietTagWidth, MEASURE_RED, resolveMeasureExtra, SHELF_POSITION } from "./modules/measure-extras-settings.mjs";
import { dialFinaleGeometry, dialFinaleHandoff } from "./chrome-instruments.mjs";
import { goalBoard, goalsAt } from "./measure-goals.mjs";
+import { deckAwaySpans, flashCss, flashEvents, flashOn, flashTimes } from "./update-flash.mjs";
/** How each module's panel comes in and goes out, s. */
export const MEASURE_FADE = Object.freeze({ in: 0.35, out: 0.4 });
@@ -203,9 +204,19 @@ export function goalsHtml(schedule, render, opts = {}) {
const paper = cfg.color ?? pal.amber ?? "#E8A33F";
const spans = upSpans(states.map((s) => s.at), cfg, schedule);
const items = [];
+ // THE UPDATE FLASH (update-flash.mjs): a goal set lights the note that lands -- not the first, the stack's entrance.
+ const flashing = flashOn(render, cfg.flash);
+ const away = flashing ? deckAwaySpans(schedule, render) : [];
const { init, cues } = stateCues(states, spans, {
own: (st, j, init) => {
const ev = [];
+ if (flashing && j > 0) {
+ const top = st.notes.find((n) => n.key === st.top);
+ if (top) {
+ init[`s${j}.${top.id}.fl`] = { opacity: 0 };
+ ev.push(...flashEvents(`s${j}.${top.id}.fl`, flashTimes([st.at], { fps: F.fps, away })));
+ }
+ }
for (const n of st.notes) {
const k = `s${j}.${n.id}`;
const to = notePlace(n, n.depth, px, H);
@@ -236,7 +247,9 @@ export function goalsHtml(schedule, render, opts = {}) {
: "";
const count = n.count > 1 ? `<div class="ct" data-k="${k}c">×${n.count}</div>` : "";
const shade = n.depth ? `<div class="sh" style="opacity:${r4(Math.min(0.5, 0.14 * n.depth))}"></div>` : "";
- return `<div class="note${dl ? " due" : ""}" data-k="${k}" style="z-index:${20 - n.depth}"><div class="tape"></div><div class="nh">Goal${n.date ? ` · ${esc(monthYear(n.date))}` : ""}</div><div class="nt">${esc(n.text)}</div>${dl}${count}${shade}</div>`;
+ const fr = n.base ? `<div class="fr">${esc(n.base)}</div>` : "";
+ const fl = flashing && j > 0 && n.key === st.top ? `<div class="fl" data-k="${k}.fl"></div>` : "";
+ return `<div class="note${dl ? " due" : ""}${fr ? " based" : ""}" data-k="${k}" style="z-index:${20 - n.depth}"><div class="tape"></div><div class="nh">Goal${n.date ? ` · ${esc(monthYear(n.date))}` : ""}</div><div class="nt">${esc(n.text)}</div>${fr}${dl}${count}${shade}${fl}</div>`;
}).join("");
const html = `<div class="st" data-k="s${j}">${notes}<div class="hd"><span class="hn">${st.goalsSet}</span> goal${st.goalsSet === 1 ? "" : "s"} set</div></div>`;
items.push({ key: `s${j}`, gate: [`s${j}`, "autoAlpha"], html });
@@ -256,6 +269,9 @@ export function goalsHtml(schedule, render, opts = {}) {
text-transform: uppercase; color: rgba(42, 28, 6, 0.62); }
.nt { font-family: ${DISPLAY}; font-size: ${px(54)}px; line-height: ${px(58)}px; white-space: nowrap; letter-spacing: 0.01em; }
.due .nt { font-size: ${px(44)}px; line-height: ${px(48)}px; }
+ .based .nt { font-size: ${px(46)}px; line-height: ${px(50)}px; }
+ .based.due .nt { font-size: ${px(38)}px; line-height: ${px(41)}px; }
+ .fr { font-family: ${DISPLAY}; font-size: ${px(22)}px; line-height: ${px(25)}px; color: rgba(42, 28, 6, 0.78); white-space: nowrap; letter-spacing: 0.02em; }
.dl { font-family: 'DeckSansBold', sans-serif; font-size: ${px(19)}px; line-height: ${px(23)}px; color: #7d150c; white-space: nowrap; }
.dl2 { font-family: 'DeckSansBold', sans-serif; font-size: ${px(18)}px; line-height: ${px(22)}px; color: rgba(42, 28, 6, 0.8); white-space: nowrap; }
/* The count sits in the note's top strip: what shows of a note further down the pile. */
@@ -266,13 +282,27 @@ export function goalsHtml(schedule, render, opts = {}) {
.hd { position: absolute; left: ${px(10)}px; bottom: ${px(4)}px; height: ${px(32)}px; padding: 0 ${px(14)}px; border-radius: ${px(16)}px;
background: ${rgba(pal.bg, 0.88)}; color: ${pal.muted}; font-family: 'DeckSansBold', sans-serif; font-size: ${px(17)}px;
line-height: ${px(32)}px; letter-spacing: 0.12em; text-transform: uppercase; white-space: nowrap; }
- .hn { color: ${paper}; font-family: ${DISPLAY}; font-size: ${px(22)}px; letter-spacing: 0.02em; }`;
+ .hn { color: ${paper}; font-family: ${DISPLAY}; font-size: ${px(22)}px; letter-spacing: 0.02em; }${flashing ? `
+ ${flashCss(".note .fl", paper, { radius: `${px(5)}px`, width: Math.max(2, Math.round(px(3))), inset: `-${px(5)}px` })}` : ""}`;
const body = `<div id="pn" data-k="pn">
${blocks.join("\n ")}
</div>`;
return { html: page("goals", schedule, opts, F, css, body, init, cues, states.map((_, j) => `s${j}`), render), items };
}
+/** A back card's padding (design px): its sides and foot, and the top it leaves to the ×n badge. */
+export const GOALS_BACK = Object.freeze({ pad: 8, top: 30, max: 24, min: 17 });
+
+/**
+ * A back card's words a size that fits `room` (design px, the strip that shows) when they can -- the display face
+ * at ~0.5 em a letter, 24 px at most -- and 17 px at the least: below that they keep their size, right-aligned, and
+ * their left goes under the card in front.
+ */
+export function backTextSize(text, room) {
+ const n = Math.max(1, [...String(text)].length);
+ return Math.max(GOALS_BACK.min, Math.min(GOALS_BACK.max, Math.floor(room / (0.5 * n))));
+}
+
/**
* The goal stack ON THE SHELF (`goals.position: "shelf"`): the count of goals
* set in a column at the left, then the notes -- the same paper, tape, shadow
@@ -294,6 +324,8 @@ function goalsShelfHtml(schedule, render, opts, cfg, states) {
const room = geo.width / F.k - G.count - G.gap - G.card;
const step = max > 1 ? Math.max(G.back, Math.min(G.card + G.step, room / (max - 1))) : 0;
const backs = step < G.card;
+ // The strip of a back card that shows beside the card in front (design px), less its padding.
+ const strip = Math.min(step, G.card) - 14 - 2 * GOALS_BACK.pad;
const place = (note, depth) => ({
x: px(G.count + G.gap + depth * step),
y: Math.round(px(6) + note.dx * 0.15 * F.k + (depth ? px(1) : 0)),
@@ -304,9 +336,22 @@ function goalsShelfHtml(schedule, render, opts, cfg, states) {
// THE ORDER ON THE SHELF is the dial's (shelfGoalStates): the goal board's headline -- the closest goal in force --
// in front with "+N more" for the others in force, the rest by how recently he set them, a missed goal struck.
const shelfStates = shelfGoalStates(schedule, states);
+ // THE UPDATE FLASH (update-flash.mjs): a goal set lights the note that lands -- not the first, the shelf's entrance.
+ const flashing = flashOn(render, cfg.flash);
+ const away = flashing ? deckAwaySpans(schedule, render) : [];
+ const flashKey = (st, j) => {
+ if (!flashing || j === 0 || !st.top) return null;
+ const top = st.notes.find((n) => n.key === st.top);
+ return top ? `s${j}.${top.id}.fl` : null;
+ };
const { init, cues } = stateCues(shelfStates, spans, {
own: (st, j, init) => {
const ev = [];
+ const fk = flashKey(st, j);
+ if (fk) {
+ init[fk] = { opacity: 0 };
+ ev.push(...flashEvents(fk, flashTimes([st.at], { fps: F.fps, away })));
+ }
for (const n of st.notes) {
const k = `s${j}.${n.id}`;
const to = place(n, n.depth);
@@ -348,13 +393,18 @@ function goalsShelfHtml(schedule, render, opts, cfg, states) {
const more = n.depth === 0 && st.headline && Number.isFinite(st.active) && st.active > 1 ? `<div class="mo">+${st.active - 1} more</div>` : "";
const front = n.depth === 0 || !backs;
const crossing = backs && n.prev === 0 && n.depth > 0;
- const face = `<div class="nf"${crossing ? ` data-k="${k}f"` : ""} style="opacity:${front || crossing ? 1 : 0}"><div class="nh">Goal${n.date ? ` · ${esc(monthYear(n.date))}` : ""}</div><div class="nt">${esc(n.text)}</div>${dl}</div>`;
+ const fr = n.base ? `<div class="fr">${esc(n.base)}</div>` : "";
+ const face = `<div class="nf${fr ? " based" : ""}"${crossing ? ` data-k="${k}f"` : ""} style="opacity:${front || crossing ? 1 : 0}"><div class="nh">Goal${n.date ? ` · ${esc(monthYear(n.date))}` : ""}</div><div class="nt">${esc(n.text)}</div>${fr}${dl}</div>`;
+ // A BACK CARD's words end at its right edge and are never cut there (11 Nov): the right end is what tells one
+ // goal from another ("LOSE 1…" read as any of three). Sized to fit the strip that shows when they can
+ // (backTextSize); when they cannot, it is their LEFT that goes under the card in front.
const back = backs && n.depth > 0
- ? `<div class="nb"${crossing ? ` data-k="${k}b"` : ""} style="opacity:${crossing ? 0 : 1}"><div class="bt">${esc(n.text)}</div>${n.date ? `<div class="bh">${esc(monthYear(n.date))}</div>` : ""}</div>`
+ ? `<div class="nb"${crossing ? ` data-k="${k}b"` : ""} style="opacity:${crossing ? 0 : 1}"><div class="bt" style="font-size:${px(backTextSize(n.text, strip))}px">${esc(n.text)}</div>${n.base ? `<div class="bf">${esc(n.base)}</div>` : ""}${n.date ? `<div class="bh">${esc(monthYear(n.date))}</div>` : ""}</div>`
: "";
// Missed (the board's, held as the dial holds it): struck in red, MISSED on it.
const miss = st.missed?.includes(n.key) ? `<div class="mx"></div><div class="ms">Missed</div>` : "";
- return `<div class="note${miss ? " missed" : ""}" data-k="${k}" style="z-index:${20 - n.depth}"><div class="tape"></div>${face}${back}${count}${more}${miss}</div>`;
+ const fl = flashKey(st, j) === `${k}.fl` ? `<div class="fl" data-k="${k}.fl"></div>` : "";
+ return `<div class="note${miss ? " missed" : ""}" data-k="${k}" style="z-index:${20 - n.depth}"><div class="tape"></div>${face}${back}${count}${more}${miss}${fl}</div>`;
}).join("");
const html = `<div class="st" data-k="s${j}"><div class="gc"><div class="gn" data-k="s${j}.c">${st.goalsSet}</div><div class="gl">goal${st.goalsSet === 1 ? "" : "s"} set</div></div>${notes}</div>`;
items.push({ key: `s${j}`, gate: [`s${j}`, "autoAlpha"], html });
@@ -374,16 +424,19 @@ function goalsShelfHtml(schedule, render, opts, cfg, states) {
.tape { position: absolute; left: 50%; top: ${px(-6)}px; width: ${px(70)}px; height: ${px(18)}px; margin-left: ${px(-35)}px;
background: rgba(255, 255, 255, 0.38); transform: rotate(-3deg); }
.nf { position: absolute; inset: 0; padding: ${px(8)}px ${px(14)}px; display: flex; flex-direction: column; justify-content: center; gap: ${px(1)}px; overflow: hidden; }
- .nb { position: absolute; right: 0; top: 0; bottom: 0; width: ${px(Math.min(step, G.card) - 14)}px; padding: 0 ${px(6)}px;
- display: flex; flex-direction: column; justify-content: center; align-items: center; overflow: hidden; }
+ .nb { position: absolute; left: 0; right: 0; top: 0; bottom: 0; padding: ${px(GOALS_BACK.top)}px ${px(GOALS_BACK.pad)}px ${px(GOALS_BACK.pad)}px;
+ display: flex; flex-direction: column; justify-content: center; align-items: flex-end; text-align: right; overflow: hidden; }
.nh { font-family: 'DeckSansBold', sans-serif; font-size: ${px(13)}px; line-height: ${px(16)}px; letter-spacing: 0.14em;
text-transform: uppercase; color: rgba(42, 28, 6, 0.62); white-space: nowrap; }
.nt { font-family: ${DISPLAY}; font-size: ${px(40)}px; line-height: ${px(44)}px; white-space: nowrap; letter-spacing: 0.01em; }
.dl { font-family: 'DeckSansBold', sans-serif; font-size: ${px(13)}px; line-height: ${px(16)}px; color: #7d150c; white-space: nowrap;
overflow: hidden; text-overflow: ellipsis; }
- .bt { font-family: ${DISPLAY}; font-size: ${px(24)}px; line-height: ${px(27)}px; white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
+ .bt { font-family: ${DISPLAY}; line-height: 1.12; white-space: nowrap; flex: none; }
+ .bf { font-family: ${DISPLAY}; font-size: ${px(15)}px; line-height: ${px(18)}px; color: rgba(42, 28, 6, 0.78); white-space: nowrap; flex: none; }
.bh { font-family: 'DeckSansBold', sans-serif; font-size: ${px(12)}px; line-height: ${px(15)}px; letter-spacing: 0.1em; text-transform: uppercase;
- color: rgba(42, 28, 6, 0.62); white-space: nowrap; }
+ color: rgba(42, 28, 6, 0.62); white-space: nowrap; flex: none; }
+ .fr { font-family: ${DISPLAY}; font-size: ${px(18)}px; line-height: ${px(20)}px; color: rgba(42, 28, 6, 0.78); white-space: nowrap; letter-spacing: 0.02em; }
+ .nf.based .nt { font-size: ${px(36)}px; line-height: ${px(38)}px; }
.mo { position: absolute; right: ${px(8)}px; bottom: ${px(6)}px; padding: 0 ${px(7)}px; height: ${px(20)}px; border-radius: ${px(10)}px;
background: rgba(42, 28, 6, 0.85); color: ${paper}; font-family: 'DeckSansBold', sans-serif; font-size: ${px(12)}px; line-height: ${px(20)}px; }
.mx { position: absolute; left: ${px(6)}px; right: ${px(6)}px; top: 50%; height: ${px(4)}px; margin-top: ${px(-2)}px; background: ${MEASURE_RED};
@@ -393,7 +446,8 @@ function goalsShelfHtml(schedule, render, opts, cfg, states) {
letter-spacing: 0.1em; text-transform: uppercase; }
.ct { position: absolute; right: ${px(8)}px; top: ${px(5)}px; min-width: ${px(40)}px; height: ${px(24)}px; padding: 0 ${px(7)}px;
border-radius: ${px(12)}px; background: #2a1c06; color: ${paper}; text-align: center;
- font-family: ${DISPLAY}; font-size: ${px(19)}px; line-height: ${px(24)}px; }`;
+ font-family: ${DISPLAY}; font-size: ${px(19)}px; line-height: ${px(24)}px; }${flashing ? `
+ ${flashCss(".note .fl", paper, { radius: `${px(4)}px`, width: Math.max(2, Math.round(px(3))), inset: `-${px(4)}px` })}` : ""}`;
const body = `<div id="pn" data-k="pn">
${blocks.join("\n ")}
</div>`;
@@ -993,6 +1047,21 @@ function dietTagsHtml(schedule, render, opts, cfg, states) {
dayBlocks.get(r.card).push(`<div class="dy" data-k="${k}"><div class="dyn">${r.days}</div><div class="dyl">day${r.days === 1 ? "" : "s"}</div></div>`);
});
}
+ // THE UPDATE FLASH (update-flash.mjs): a new diet -- a new front tag, or new words for it -- lights that tag in its
+ // ink; never the running day count, never the first tag (the badge's entrance).
+ const flashing = flashOn(render, cfg.flash);
+ const flashed = new Set();
+ if (flashing) {
+ const away = deckAwaySpans(schedule, render);
+ states.forEach((st, j) => {
+ const front = st.tags[0]?.id;
+ if (!j || front === undefined || front === states[j - 1].tags[0]?.id) return;
+ const k = `t${front}.fl`;
+ init[k] = { opacity: 0 };
+ flashed.add(front);
+ ev.push(...flashEvents(k, flashTimes([st.at], { fps: F.fps, away })));
+ });
+ }
const { cues } = compileCues(init, ev);
const items = [];
const room = DIET_TAG.width - 44;
@@ -1015,14 +1084,16 @@ function dietTagsHtml(schedule, render, opts, cfg, states) {
? `<div class="bk" data-k="${k}.b"><div class="bl" style="font-size:${px(Math.min(32, tagWordSize(label, step - 30)))}px">${esc(label)}</div>${date ? `<div class="bd">${esc(date)}</div>` : ""}</div>`
: "";
const html = `<div class="tg" data-k="${k}"${fan ? ` style="z-index:${10 + t.id}"` : ""}><div class="dm" data-k="${k}.d"><div class="sw" data-k="${k}.w"><div class="sp${d ? "" : " off"}" data-k="${k}.s">` +
- `<div class="ink" style="color:${ink};border-color:${ink}"><div class="fr"${fan ? ` data-k="${k}.f"` : ""}>${face}</div>${back}</div></div></div></div></div>`;
+ `<div class="ink" style="color:${ink};border-color:${ink}"><div class="fr"${fan ? ` data-k="${k}.f"` : ""}>${face}</div>${back}</div>` +
+ `${flashed.has(t.id) ? `<div class="fl" data-k="${k}.fl" style="color:${ink}"></div>` : ""}</div></div></div></div>`;
items.push({ key: k, gate: [k, "autoAlpha"], html });
return html;
});
const css = `
#pn { position: absolute; inset: 0; visibility: hidden; opacity: 0; }
.tg { position: absolute; left: 0; top: 0; width: ${px(W)}px; height: ${px(DIET_TAG.height)}px; visibility: hidden; opacity: 0;${fan ? " transform-origin: 30% 60%;" : ""} }
- .dm, .sw { position: absolute; inset: 0; }
+ .dm, .sw { position: absolute; inset: 0; }${flashing ? `
+ ${flashCss(".sp > .fl", "currentColor", { radius: `${px(9)}px`, width: Math.max(2, Math.round(px(3))), inset: `-${px(2)}px` })}` : ""}
/* A tag: the stamp's plate and pressed ink, small. The plate is solid; only the ink is pressed. */
.sp { position: absolute; left: ${px(4)}px; top: ${px(4)}px; right: ${px(4)}px; bottom: ${px(4)}px; border-radius: ${px(8)}px;
background: ${rgba(pal.bg, fan ? 0.97 : 0.93)}; padding: ${px(4)}px;
diff --git a/umtool/report-to-video/chrome-posts.mjs b/umtool/report-to-video/chrome-posts.mjs
@@ -34,6 +34,7 @@
import { formatDeckDate } from "./attribution.mjs";
import { pageDuration, postsGeometry, resolveDeck, snapWindow } from "./deck.mjs";
import { mix, rgba } from "./chrome-deck.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
// The window arithmetic is deck.mjs's (pure, and loaded by the build without
// this page module); re-exported for the page's own callers.
@@ -195,7 +196,7 @@ export function postsCues({
// keeps every element's own order (and so every from).
cues.sort((x, y) => x.at - y.at || x.n - y.n);
for (const c of cues) delete c.n;
- return { tops, init, cues };
+ return { tops, init, cues: settleFirstFrame(init, cues) };
}
/** A card's head: `@handle · Bluesky`, the separator in the deck's accent. */
@@ -428,6 +429,7 @@ export function postsHtml(schedule, render, window, opts = {}) {
const P = JSON.parse(document.getElementById("posts-data").textContent);
const byK = {};
for (const el of document.querySelectorAll("[data-k]")) byK[el.dataset.k] = el;
+ ${embedFn("settleFirstFrame", settleFirstFrame)}
${embedFn("postsCues", postsCues)}
const params = new URLSearchParams(location.search);
diff --git a/umtool/report-to-video/chrome-stamp.mjs b/umtool/report-to-video/chrome-stamp.mjs
@@ -14,6 +14,7 @@
import { cueTime, cueTimeAfter, pageDuration, stampGeometry, stampsOnFrames } from "./deck.mjs";
import { mix, rgba } from "./chrome-deck.mjs";
import { drawnStamps, resolveFactcheck, STAMP_MOTION } from "./factcheck.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */
const INSTANT = 0.001;
@@ -102,7 +103,7 @@ export function stampCues(schedule, render = null) {
freeAt.set(e.k, at + dur);
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why });
}
- return { init, cues };
+ return { init, cues: settleFirstFrame(init, cues, fps) };
}
/**
diff --git a/umtool/report-to-video/chrome-stats.mjs b/umtool/report-to-video/chrome-stats.mjs
@@ -18,6 +18,7 @@
import { pageDuration, statsGeometry } from "./deck.mjs";
import { rgba } from "./chrome-deck.mjs";
import { STATS_LABELS, STATS_MOTION } from "./stats.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */
const INSTANT = 0.001;
@@ -112,7 +113,7 @@ export function statsCues(schedule) {
freeAt.set(e.k, r4(at + dur));
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease });
}
- return { init, cues };
+ return { init, cues: settleFirstFrame(init, cues, schedule.fps) };
}
/**
diff --git a/umtool/report-to-video/chrome-teaser.mjs b/umtool/report-to-video/chrome-teaser.mjs
@@ -31,6 +31,7 @@ import {
export { TEASER_MOTION };
import { mix, rgba } from "./chrome-deck.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
/**
* The display face: Archivo, a variable font (wght 100–900, wdth 62–125),
@@ -222,7 +223,7 @@ export function teaserCues({ lines, tail = "", seconds, motion = TEASER_MOTION,
}
// `need` is the validator's; the page's data is what it always was.
const { T: _T, need: _need, ...times } = beats;
- return { init, cues, beats: times, scale: beats.scale };
+ return { init, cues: settleFirstFrame(init, cues), beats: times, scale: beats.scale };
}
/** Each role's type: size (px, the most it may be), weight, width (%), tracking (em), and the fit floor. */
diff --git a/umtool/report-to-video/cue-start.mjs b/umtool/report-to-video/cue-start.mjs
@@ -0,0 +1,66 @@
+// THE CUT'S FIRST FRAME (the frame-zero fix, 11 Nov): a cue that takes effect
+// at the cut's first instant belongs in a page's init, not in its cue list.
+//
+// Every cue page sets its init, then builds a paused timeline of fromTo tweens
+// (`immediateRender: false`) and is seeked frame by frame. The renderer's first
+// frame is a seek to 0 -- no change to GSAP, and a tween placed at 0 shows its
+// FROM there anyway -- so a cue at 0 shorter than a frame is drawn on frame 1,
+// never on frame 0. That is how the instruments' column (dial, odometer, trail:
+// chrome-instruments.mjs withDeck) showed for one frame over a cut that opens on
+// the intro: their root is up in init and hidden by an instant cue at 0.
+//
+// LEAF: no imports, so every cue compiler can call it -- and SELF-CONTAINED
+// (no module constant): the posts' page embeds postsCues, and this with it, in
+// the browser (chrome-posts.mjs embedFn).
+
+/**
+ * Fold every cue that has finished before frame 1 and starts at the cut's
+ * first instant (at or before 0, or where an earlier folded cue on the same
+ * element ended) into init. A cue a frame or longer, or one after a cue on
+ * its element that stays, is left alone: frame 0 then shows its FROM, which is
+ * init, as it should.
+ *
+ * `init` is changed IN PLACE (an entry replaced, never mutated -- entries may
+ * be shared) because several callers read their own init after compiling; the
+ * cue list is returned without the folded cues.
+ *
+ * @template {{ k: string, at: number, dur: number, to: object }} C
+ * @param {Record<string, object>} init
+ * @param {C[]} cues in time order per element (every compiler's output)
+ * @param {number} [fps]
+ * @returns {C[]}
+ */
+export function settleFirstFrame(init, cues, fps = 30) {
+ // At or before this, a time is the cut's first instant.
+ const START_EPS = 1e-4;
+ const frame = 1 / (Number(fps) > 0 ? Number(fps) : 30);
+ /** element -> where its folded cues end; absent once a cue on it stays. */
+ const foldEnd = new Map();
+ const kept = new Set();
+ const out = [];
+ for (const c of cues) {
+ const start = foldEnd.has(c.k) ? foldEnd.get(c.k) : 0;
+ const foldable = !kept.has(c.k) && Number(c.at) <= start + START_EPS && Number(c.at) + Number(c.dur) < frame - START_EPS;
+ if (!foldable) {
+ kept.add(c.k);
+ out.push(c);
+ continue;
+ }
+ init[c.k] = { ...(init[c.k] ?? {}), ...c.to };
+ foldEnd.set(c.k, Number(c.at) + Number(c.dur));
+ }
+ return out;
+}
+
+/**
+ * The cues a renderer's frame 0 cannot show: a change at the cut's first
+ * instant, over before frame 1. Empty for a page settleFirstFrame has seen.
+ *
+ * @param {{ init?: object, cues?: Array<{ k: string, at: number, dur: number, from?: object, to: object }> }} data
+ */
+export function unseenFirstFrameCues(data, fps = 30) {
+ const init = structuredClone(data.init ?? {});
+ const cues = (data.cues ?? []).filter((c) => JSON.stringify(c.from ?? null) !== JSON.stringify(c.to));
+ const settled = settleFirstFrame(init, cues, fps);
+ return cues.filter((c) => !settled.includes(c));
+}
diff --git a/umtool/report-to-video/fixtures/measure-remembered/measure.json b/umtool/report-to-video/fixtures/measure-remembered/measure.json
@@ -0,0 +1,249 @@
+{
+ "_fixture": "rev9-a7's moment for the dial's remembered-weight looks (11 Nov): 342.9 stated (21 Mar 2013), LOSE 75 in force, ≈390 remembered as of 24 Feb 2023 -- his heaviest (totals.peakDrift) -- and a 368 as of 2008 that is not.",
+ "version": 1,
+ "unit": "lb",
+ "scale": {
+ "min": 220,
+ "max": 400
+ },
+ "asOfRender": "2026-11-11",
+ "scopes": [
+ "weight"
+ ],
+ "events": [
+ {
+ "t": 1,
+ "row": "w1",
+ "scope": "weight",
+ "kind": "stated",
+ "value": 342.9,
+ "qualifier": null,
+ "date": "2013-03-21",
+ "asOf": null,
+ "display": "342.9 lb"
+ },
+ {
+ "t": 1.5,
+ "row": "g1",
+ "scope": "weight",
+ "kind": "goalLoss",
+ "value": -75,
+ "qualifier": null,
+ "date": "2023-07-26",
+ "asOf": null,
+ "display": "lose 75",
+ "deadline": null,
+ "due": null
+ },
+ {
+ "t": 3,
+ "row": "w21",
+ "scope": "weight",
+ "kind": "remembered",
+ "value": 390,
+ "qualifier": "≈",
+ "date": "2023-09-29",
+ "asOf": "2023-02-24",
+ "display": "≈390 lb"
+ },
+ {
+ "t": 8,
+ "row": "w35",
+ "scope": "weight",
+ "kind": "remembered",
+ "value": 368,
+ "qualifier": null,
+ "date": "2024-01-10",
+ "asOf": "2008-06-30",
+ "display": "368 lb"
+ }
+ ],
+ "hidden": [],
+ "state": [
+ {
+ "t": 0,
+ "current": null,
+ "remembered": [],
+ "goal": null,
+ "goals": [],
+ "lost": {
+ "total": 0,
+ "runs": []
+ },
+ "net": null
+ },
+ {
+ "t": 1,
+ "current": {
+ "value": 342.9,
+ "qualifier": null,
+ "row": "w1",
+ "date": "2013-03-21"
+ },
+ "remembered": [],
+ "goal": null,
+ "goals": [],
+ "lost": {
+ "total": 0,
+ "runs": []
+ },
+ "net": null
+ },
+ {
+ "t": 1.5,
+ "current": {
+ "value": 342.9,
+ "qualifier": null,
+ "row": "w1",
+ "date": "2013-03-21"
+ },
+ "remembered": [],
+ "goal": {
+ "value": 267.9,
+ "loss": 75,
+ "deadline": null,
+ "due": null,
+ "row": "g1",
+ "display": "lose 75",
+ "base": {
+ "value": 342.9,
+ "row": "w1",
+ "from": "stated"
+ }
+ },
+ "goals": [
+ {
+ "value": 267.9,
+ "loss": 75,
+ "deadline": null,
+ "due": null,
+ "row": "g1",
+ "display": "lose 75",
+ "base": {
+ "value": 342.9,
+ "row": "w1",
+ "from": "stated"
+ }
+ }
+ ],
+ "lost": {
+ "total": 0,
+ "runs": []
+ },
+ "net": null
+ },
+ {
+ "t": 3,
+ "current": {
+ "value": 342.9,
+ "qualifier": null,
+ "row": "w1",
+ "date": "2013-03-21"
+ },
+ "remembered": [
+ {
+ "value": 390,
+ "asOf": "2023-02-24",
+ "row": "w21"
+ }
+ ],
+ "goal": {
+ "value": 267.9,
+ "loss": 75,
+ "deadline": null,
+ "due": null,
+ "row": "g1",
+ "display": "lose 75",
+ "base": {
+ "value": 342.9,
+ "row": "w1",
+ "from": "stated"
+ }
+ },
+ "goals": [
+ {
+ "value": 267.9,
+ "loss": 75,
+ "deadline": null,
+ "due": null,
+ "row": "g1",
+ "display": "lose 75",
+ "base": {
+ "value": 342.9,
+ "row": "w1",
+ "from": "stated"
+ }
+ }
+ ],
+ "lost": {
+ "total": 0,
+ "runs": []
+ },
+ "net": null
+ },
+ {
+ "t": 8,
+ "current": {
+ "value": 342.9,
+ "qualifier": null,
+ "row": "w1",
+ "date": "2013-03-21"
+ },
+ "remembered": [
+ {
+ "value": 390,
+ "asOf": "2023-02-24",
+ "row": "w21"
+ },
+ {
+ "value": 368,
+ "asOf": "2008-06-30",
+ "row": "w35"
+ }
+ ],
+ "goal": {
+ "value": 267.9,
+ "loss": 75,
+ "deadline": null,
+ "due": null,
+ "row": "g1",
+ "display": "lose 75",
+ "base": {
+ "value": 342.9,
+ "row": "w1",
+ "from": "stated"
+ }
+ },
+ "goals": [
+ {
+ "value": 267.9,
+ "loss": 75,
+ "deadline": null,
+ "due": null,
+ "row": "g1",
+ "display": "lose 75",
+ "base": {
+ "value": 342.9,
+ "row": "w1",
+ "from": "stated"
+ }
+ }
+ ],
+ "lost": {
+ "total": 0,
+ "runs": []
+ },
+ "net": null
+ }
+ ],
+ "totals": {
+ "lost": 0,
+ "peakDrift": [
+ 390
+ ],
+ "under300": {
+ "said": 0,
+ "rows": []
+ }
+ }
+}
+\ No newline at end of file
diff --git a/umtool/report-to-video/frame-zero.test.mjs b/umtool/report-to-video/frame-zero.test.mjs
@@ -0,0 +1,88 @@
+// THE CUT'S FIRST FRAME (cue-start.mjs): a page a renderer seeks to 0 draws its
+// init there, so whatever the cut is at its first instant must be IN init. The
+// instruments' column (dial, odometer, trail) was up in init and hidden by an
+// instant cue at 0: over a cut that opens on the intro, frame 0 showed the
+// gauge, the counter and the chart strip before the wordmark (rev9-a6/a7, 11 Nov).
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { estimateSchedule } from "./deck.mjs";
+import { dialHtml, odometerHtml, trailHtml } from "./chrome-instruments.mjs";
+import { settleFirstFrame, unseenFirstFrameCues } from "./cue-start.mjs";
+import { cueList } from "./measure-draw.mjs";
+import { compileCues } from "./chrome-cues.mjs";
+import { statsCues } from "./chrome-stats.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const MEASURE = JSON.parse(readFileSync(path.join(HERE, "fixtures", "measure-dial", "measure.json"), "utf8"));
+const FPS = 30;
+const RENDER = {
+ width: 1920, height: 1080, fps: FPS, transition: 0.4,
+ palette: { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" },
+ chrome: { engine: "hyperframes", layout: "deck", deck: { dial: true, odometer: true, trail: true, qr: { show: false }, finale: { video: "side", totals: false } } },
+};
+const fonts = { DeckSans: "assets/DeckSans.ttf", DeckSansBold: "assets/DeckSansBold.ttf" };
+
+/** The instruments' fixture cut, opening on the intro (selectVariant's entry: the deck hides over it). */
+function introCut() {
+ const timeline = Array.from({ length: 9 }, (_, i) => ({
+ type: "clip", id: `c${i + 1}`, video: "vidx", start: 10 * i, end: 10 * i + (i === 8 ? 14 : 8), cite: 1, section: 0,
+ quote: "q", onscreen: { title: `Clip ${i + 1}` }, ...(i === 8 ? { layout: "finale" } : {}),
+ }));
+ timeline.unshift({ type: "intro", id: "brand-intro", style: "boot-dark", seconds: 4.75, heading: "Intro" });
+ const manifest = { slug: "m", title: "M", provenance: {}, render: RENDER, timeline };
+ const schedule = { ...estimateSchedule(manifest), measure: MEASURE };
+ assert.equal(schedule.segments[0].hideDeck, true, "the intro hides the deck");
+ return schedule;
+}
+
+const dataOf = (html, id) => JSON.parse(new RegExp(`<script id="${id}-data" type="application/json">(.*?)</script>`, "s").exec(html)[1]);
+
+test("over an intro the instruments are hidden from frame 0: their root is down in init, with no instant cue at 0", () => {
+ const schedule = introCut();
+ for (const [id, html] of [["dial", dialHtml(schedule, RENDER, { fonts })], ["odometer", odometerHtml(schedule, RENDER, { fonts })], ["trail", trailHtml(schedule, RENDER, { fonts })]]) {
+ const data = dataOf(html, id);
+ assert.deepEqual(data.init.rt, { autoAlpha: 0 }, `${id}: hidden at the cut's first instant`);
+ assert.deepEqual(unseenFirstFrameCues(data, FPS), [], `${id}: no change at 0 that frame 0 cannot show`);
+ // And up again with the deck, after the intro: the first cue on the root shows it.
+ const first = data.cues.find((c) => c.k === "rt");
+ assert.ok(first.at > 4, `${id}: the column comes up after the intro (${first.at})`);
+ assert.deepEqual(first.to, { autoAlpha: 1 });
+ }
+});
+
+test("settleFirstFrame folds what happens at the first instant into init, and leaves every real move alone", () => {
+ const init = { a: { autoAlpha: 1 }, b: { opacity: 0 }, c: { x: 0 } };
+ const shared = init.a;
+ const cues = [
+ { k: "a", at: 0, dur: 0.001, from: { autoAlpha: 1 }, to: { autoAlpha: 0 } },
+ { k: "a", at: 0.001, dur: 0.001, from: { autoAlpha: 0 }, to: { autoAlpha: 0.5 } }, // chained after the first, still before frame 1
+ { k: "b", at: 0, dur: 0.4, from: { opacity: 0 }, to: { opacity: 1 } }, // a fade from 0: frame 0 is its from
+ { k: "b", at: 0.4, dur: 0.001, from: { opacity: 1 }, to: { opacity: 0 } },
+ { k: "c", at: 0.5, dur: 0.001, from: { x: 0 }, to: { x: 5 } },
+ ];
+ const out = settleFirstFrame(init, cues, 30);
+ assert.deepEqual(init.a, { autoAlpha: 0.5 });
+ assert.deepEqual(shared, { autoAlpha: 1 }, "an init entry is replaced, never mutated (entries may be shared)");
+ assert.deepEqual(out.map((c) => `${c.k}@${c.at}`), ["b@0", "b@0.4", "c@0.5"]);
+});
+
+test("every cue compiler settles the first frame: cueList, compileCues, the stats panel", () => {
+ const L = cueList(FPS);
+ L.set("rt", { autoAlpha: 1 });
+ L.add("rt", 0, 0, { autoAlpha: 0 });
+ L.add("rt", 5, 0.45, { autoAlpha: 1 });
+ const built = L.build();
+ assert.deepEqual(built.init.rt, { autoAlpha: 0 });
+ assert.deepEqual(built.cues.map((c) => c.at), [5]);
+ const cc = compileCues({ x: { autoAlpha: 0 } }, [{ k: "x", at: 0, dur: 0, to: { autoAlpha: 1 }, ease: "none" }]);
+ assert.deepEqual(cc.init.x, { autoAlpha: 1 });
+ assert.equal(cc.cues.length, 0);
+ // A stat card shown from the cut's first instant (v7gkv5w-poker-2's s0_0): up on frame 0, not frame 1.
+ const st = statsCues({ fps: FPS, stats: { clips: [{ in: 0, out: 6, states: [{ at: 0 }, { at: 3 }] }] } });
+ assert.deepEqual(unseenFirstFrameCues(st, FPS), []);
+ assert.equal(st.init.s0_0.autoAlpha, 1);
+});
diff --git a/umtool/report-to-video/fx.mjs b/umtool/report-to-video/fx.mjs
@@ -38,6 +38,7 @@
import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
import { offsetIn, sourceAtOffset } from "./gaps.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
/** Each effect's key under `render.chrome.fx`, in the order the page stacks them (later on top). */
export const FX_KEYS = Object.freeze(["scrubber", "receipts", "zoom", "kineticQuote", "redact", "odometer", "punchIn", "thenNow", "whip", "glitch"]);
@@ -1053,7 +1054,7 @@ export function compileCues(init, events) {
freeAt.set(e.k, r4(at + dur));
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease });
}
- return cues;
+ return settleFirstFrame(init, cues);
}
/** An object's numbers with -0 as 0: the cue list is data, and JSON has no -0. */
diff --git a/umtool/report-to-video/instruments.mjs b/umtool/report-to-video/instruments.mjs
@@ -66,12 +66,19 @@ export const DIAL_DEFAULTS = Object.freeze({
// "auto" (the default): "promise" when a promise is on camera, else "odometer" --
// the contract's finale: the dial drops, the odometer rolls, NET holds, THEN the promise clock.
finaleEnd: "auto",
+ // A remembered weight (11 Nov variants): "needle" -- the long grey second needle and its as-of words, as it was --
+ // "rim" (a bold rim marker and a flag), "readout" (a line under the date, a rim marker), "callout" (a ghost needle
+ // sweeps to it with a label held ~2 s, then the rim's flag). chrome-instruments.mjs dialParts.
+ rememberedAs: "needle",
+ // The update flash (update-flash.mjs): null follows render.chrome.deck.measure.flash; true/false for this one.
+ flash: null,
});
export const DIAL_PLACEMENTS = Object.freeze(["column", "corner"]);
export const DIAL_CORNERS = Object.freeze(["bottom-right", "bottom-left", "top-right", "top-left"]);
export const DIAL_MOTIONS = Object.freeze(["spring", "ease"]);
export const DIAL_FINALE_ENDS = Object.freeze(["auto", "odometer", "promise"]);
+export const DIAL_REMEMBERED = Object.freeze(["needle", "rim", "readout", "callout"]);
/** A corner dial's size bounds, px at 1920 wide. */
export const DIAL_SIZE = Object.freeze([200, 540]);
@@ -81,6 +88,8 @@ export const ODOMETER_DEFAULTS = Object.freeze({
net: true,
// "ACROSS 8 RUNS" under the wheels.
runs: true,
+ // The update flash (update-flash.mjs): null follows render.chrome.deck.measure.flash; true/false for this one.
+ flash: null,
});
export const TRAIL_DEFAULTS = Object.freeze({
@@ -89,6 +98,15 @@ export const TRAIL_DEFAULTS = Object.freeze({
// How many times he says he is under 300 (the measure's `totals.under300` rows), as they land.
count: true,
label: "WHAT HE SAYS HE WEIGHS, BY DATE",
+ // The axes: "fit" what is shown so far, reflowing as each weight lands; "fixed" to every point of the cut.
+ bounds: "fit",
+ // His remembered weights ("≈390, as of Feb 2023") as points too: hollow and grey, never joined into the line.
+ remembered: true,
+ // A stretch with no statement longer than this many days is a break in the time axis, not a line across it:
+ // "auto" (a year, or 8× the median spacing if that is longer), a number of days (30–3650), or 0 for none.
+ gap: "auto",
+ // The update flash (update-flash.mjs): null follows render.chrome.deck.measure.flash; true/false for this one.
+ flash: null,
});
/** A label's characters at most. */
@@ -171,10 +189,12 @@ export function validateDial(v, where = "render.chrome.deck.dial") {
oneOf("placement", DIAL_PLACEMENTS);
oneOf("motion", DIAL_MOTIONS);
oneOf("finaleEnd", DIAL_FINALE_ENDS);
+ oneOf("rememberedAs", DIAL_REMEMBERED);
oneOf("corner", DIAL_CORNERS);
if (obj.size !== undefined && !(Number.isInteger(obj.size) && numIn(obj.size, DIAL_SIZE[0], DIAL_SIZE[1]))) {
errors.push(`${where}.size must be a whole number of pixels from ${DIAL_SIZE[0]} to ${DIAL_SIZE[1]}`);
}
+ if (obj.flash !== undefined && obj.flash !== null) { const p = boolProblem(obj.flash, `${where}.flash`); if (p) errors.push(p); }
return errors;
}
@@ -184,6 +204,7 @@ export function validateOdometer(v, where = "render.chrome.deck.odometer") {
if (!obj) return errors;
for (const k of ["net", "runs"]) if (obj[k] !== undefined) { const p = boolProblem(obj[k], `${where}.${k}`); if (p) errors.push(p); }
if (obj.label !== undefined) { const p = labelProblem(obj.label, `${where}.label`); if (p) errors.push(p); }
+ if (obj.flash !== undefined && obj.flash !== null) { const p = boolProblem(obj.flash, `${where}.flash`); if (p) errors.push(p); }
return errors;
}
@@ -194,5 +215,9 @@ export function validateTrail(v, where = "render.chrome.deck.trail") {
if (obj.mark !== undefined) { const p = markProblem(obj.mark, `${where}.mark`); if (p) errors.push(p); }
if (obj.count !== undefined) { const p = boolProblem(obj.count, `${where}.count`); if (p) errors.push(p); }
if (obj.label !== undefined) { const p = labelProblem(obj.label, `${where}.label`); if (p) errors.push(p); }
+ if (obj.remembered !== undefined) { const p = boolProblem(obj.remembered, `${where}.remembered`); if (p) errors.push(p); }
+ if (obj.bounds !== undefined && !["fit", "fixed"].includes(obj.bounds)) errors.push(`${where}.bounds must be "fit" or "fixed"`);
+ if (obj.gap !== undefined && !(obj.gap === "auto" || obj.gap === 0 || numIn(obj.gap, 30, 3650))) errors.push(`${where}.gap must be "auto", 0 (no breaks) or 30 to 3650 days`);
+ if (obj.flash !== undefined && obj.flash !== null) { const p = boolProblem(obj.flash, `${where}.flash`); if (p) errors.push(p); }
return errors;
}
diff --git a/umtool/report-to-video/instruments.test.mjs b/umtool/report-to-video/instruments.test.mjs
@@ -112,14 +112,14 @@ test("the instruments' settings: true, an object of known keys, or off; the side
const side = validateChrome({ ...chromeWith({ trail: true }), threads: { list: [{ id: "a", label: "A" }] } }, {});
assert.ok(side.some((e) => /render\.chrome\.threads and render\.chrome\.deck\.trail both need the frame/.test(e)), side.join("\n"));
assert.deepEqual(resolveDial(RENDER), {
- mark: 300, ghosts: true, goal: true, needle: "#ff5a4e", finale: true, label: "HE SAYS HE WEIGHS", placement: "column", size: 340, corner: "bottom-right", motion: "spring", finaleEnd: "auto",
+ mark: 300, ghosts: true, goal: true, needle: "#ff5a4e", finale: true, label: "HE SAYS HE WEIGHS", placement: "column", size: 340, corner: "bottom-right", motion: "spring", finaleEnd: "auto", rememberedAs: "needle", flash: null,
});
assert.match(validateDial({ placement: "left" })[0], /placement must be "column" or "corner"/);
assert.match(validateDial({ size: 100 })[0], /size must be a whole number of pixels from 200 to 540/);
assert.match(validateDial({ motion: "bounce" })[0], /motion must be "spring" or "ease"/);
assert.match(validateDial({ finaleEnd: "net" })[0], /finaleEnd must be "auto" or "odometer" or "promise"/);
assert.equal(resolveDial({ chrome: chromeWith({ dial: false }) }), null);
- assert.deepEqual(moduleProblems({ render: { ...RENDER, chrome: chromeWith({ dial: { ghost: true } }) } }).dial, ["render.chrome.deck.dial.ghost is not a setting of it (mark, ghosts, goal, needle, finale, label, placement, size, corner, motion, finaleEnd)"]);
+ assert.deepEqual(moduleProblems({ render: { ...RENDER, chrome: chromeWith({ dial: { ghost: true } }) } }).dial, ["render.chrome.deck.dial.ghost is not a setting of it (mark, ghosts, goal, needle, finale, label, placement, size, corner, motion, finaleEnd, rememberedAs, flash)"]);
});
// ---------------------------------------------------------------------------
diff --git a/umtool/report-to-video/measure-draw.mjs b/umtool/report-to-video/measure-draw.mjs
@@ -16,6 +16,7 @@
//
// Pure: strings in, strings out. No fs.
import { cueTime, pageDuration } from "./deck.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */
export const INSTANT = 0.001;
@@ -71,7 +72,7 @@ export function cueList(fps) {
freeAt.set(e.k, r4(at + dur));
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease });
}
- return { init, cues };
+ return { init, cues: settleFirstFrame(init, cues, fps) };
},
};
}
diff --git a/umtool/report-to-video/measure-extras.mjs b/umtool/report-to-video/measure-extras.mjs
@@ -216,6 +216,18 @@ export function goalText(e, unit = "lb") {
}
/**
+ * A goal's base as its note writes it -- "(FROM 346.7)", "(FROM ≈390)" -- from the
+ * slice's `goal.base` ({ value, row }), the qualifier its row carries; null
+ * when there is none.
+ */
+export function goalBaseText(base, m) {
+ if (!base || !Number.isFinite(base.value)) return null;
+ const row = [...(m?.events ?? []), ...(m?.hidden ?? [])].find((e) => e.row === base.row);
+ const q = typeof row?.qualifier === "string" && /^[≈<>]$/.test(row.qualifier) ? row.qualifier : "";
+ return `(FROM ${q}${weightText(base.value)})`;
+}
+
+/**
* The pile's states: one per goal event, `{ at, top, goalsSet, notes }` --
* `notes` back to front (the last is the one that just landed, `top` its key),
* each `{ key, text, count, date, deadline, deadlineDate, days, target, rot,
@@ -255,6 +267,10 @@ export function goalStates(schedule, render) {
const target = s?.goal && s.goal.row === e.row && Number.isFinite(s.goal.value) ? s.goal.value
: e.kind === "goal" && Number.isFinite(e.value) ? e.value : null;
note.target = target;
+ // The weight he had stated when he set it (`goals.base`): the slice's own base for this goal -- the weight the
+ // gauge's target is reckoned from (measure-slice.mjs goalBase: the run's start, else the latest weight he gave by
+ // the goal's date) -- with its row's qualifier. None resolved, none shown: never one made up here.
+ note.base = cfg.base && s?.goal?.row === e.row ? goalBaseText(s.goal.base, m) : null;
order = [...order.filter((k) => k !== key), key];
const shown = order.slice(-cfg.max);
const depth = new Map(shown.map((k, i) => [k, shown.length - 1 - i]));
@@ -267,7 +283,7 @@ export function goalStates(schedule, render) {
const x = notes.get(k);
return {
key: k, id: x.id, text: x.text, count: x.count, date: x.date, deadline: x.deadline,
- deadlineDate: x.deadlineDate, days: x.days, target: x.target, rot: x.rot, dx: x.dx,
+ deadlineDate: x.deadlineDate, days: x.days, target: x.target, base: x.base ?? null, rot: x.rot, dx: x.dx,
depth: depth.get(k), prev: k === key ? null : prevDepth.get(k) ?? null,
};
}),
diff --git a/umtool/report-to-video/measure-slice.mjs b/umtool/report-to-video/measure-slice.mjs
@@ -33,7 +33,7 @@ export const MEASURE_SLICE_VERSION = 1;
export { PROMISE_FORMS };
/** `render.chrome.deck.measure`'s keys. */
-export const MEASURE_SETTINGS_KEYS = Object.freeze(["scopes", "scale", "asOf", "ghosts"]);
+export const MEASURE_SETTINGS_KEYS = Object.freeze(["scopes", "scale", "asOf", "ghosts", "flash"]);
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
const isIso = (v) => typeof v === "string" && /^\d{4}-\d{2}-\d{2}$/.test(v) && !Number.isNaN(Date.parse(`${v}T00:00:00Z`));
@@ -66,6 +66,8 @@ export function validateMeasureSettings(v, where = "render.chrome.deck.measure")
else for (const k of Object.keys(s)) if (k !== "min" && k !== "max") errors.push(`${where}.scale.${k} is not a scale setting (min, max)`);
}
if (v.asOf !== undefined && !isIso(v.asOf)) errors.push(`${where}.asOf must be a date (YYYY-MM-DD)`);
+ // The update flash (update-flash.mjs): every measure widget's outline lights as its value changes.
+ if (v.flash !== undefined && typeof v.flash !== "boolean") errors.push(`${where}.flash must be true or false`);
errors.push(...validateGhosts(v.ghosts, `${where}.ghosts`));
return errors;
}
diff --git a/umtool/report-to-video/measure-slice.test.mjs b/umtool/report-to-video/measure-slice.test.mjs
@@ -198,7 +198,7 @@ test("the settings: their shape, their scopes against the ledger, and when a cut
assert.deepEqual(validateMeasureSettings(undefined), []);
assert.deepEqual(validateMeasureSettings({ scopes: ["weight"], scale: { min: 220, max: 400 }, asOf: "2026-11-05" }), []);
assert.deepEqual(validateMeasureSettings({ scopes: [], scale: { min: 4, max: 2 }, asOf: "Nov 5", x: 1 }), [
- "render.chrome.deck.measure.x is not a measure setting (scopes, scale, asOf, ghosts)",
+ "render.chrome.deck.measure.x is not a measure setting (scopes, scale, asOf, ghosts, flash)",
"render.chrome.deck.measure.scopes must be a list of the ledger's track keys (at least one)",
"render.chrome.deck.measure.scale.min must be below scale.max",
"render.chrome.deck.measure.asOf must be a date (YYYY-MM-DD)",
diff --git a/umtool/report-to-video/modules/dial.mjs b/umtool/report-to-video/modules/dial.mjs
@@ -43,6 +43,8 @@ export default defineModule({
{ key: "corner", type: "enum", options: ["bottom-right", "bottom-left", "top-right", "top-left"], label: "The corner", default: "bottom-right" },
{ key: "motion", type: "enum", options: ["spring", "ease"], label: "The needle's move", default: "spring" },
{ key: "finaleEnd", type: "enum", options: ["auto", "odometer", "promise"], label: "The finale's last beat", default: "auto" },
+ { key: "rememberedAs", type: "enum", options: ["needle", "rim", "readout", "callout"], label: "A remembered weight drawn as", default: "needle" },
+ { key: "flash", type: "boolean", label: "Flash its outline when its value changes (unset: deck.measure.flash)" },
],
docs: {
heading: "Scale dial",
@@ -52,6 +54,8 @@ export default defineModule({
["`deck.dial.mark`", "a weight, or `null` · default `300` (its tick and label in the accent)", "`umtool look <p> deck.dial.mark=300`"],
["`deck.dial.ghosts`, `.goal`", "bool · default `true` each (`.goal`: every goal in force, the closest headlined)", "`umtool look <p> deck.dial.ghosts=false`"],
["`deck.measure.ghosts`", "`true` · `{opacity, tolerance, ramp, pulse}` · `false` / absent: off (the default). CLAIM GHOSTS (measure-ghosts.mjs), not `deck.dial.ghosts`: every weight he has claimed so far -- each stated weight the needle goes to and each remembered one, his own, in cut order -- leaves a thin faint tick across the dial's rim at its value, under everything else on the face; a value claimed again (within `tolerance` lb of the tick's first value; an `≈` value as its rounded number; `>300` and `<300` at 300) steps that tick along the `ramp` -- 1× faint, 2× warm, 3× and up hot, a little thicker each step -- and it pulses once as the repeat lands (`pulse`). In the finale every tick stays at its count at the cut's end. Seek-safe: a frame at t draws the claims before t", "`umtool look <p> deck.measure.ghosts=true`"],
+ ["`deck.dial.rememberedAs`", "`needle` · `rim` · `readout` · `callout` · default `needle` (as it was: a long grey second needle from the hub to the value, its words -- \"≈390 / AS OF 24 FEB 2023\" -- along it). `rim`: no long needle; a bold marker across the rim at the value and a flag inside it -- \"HEAVIEST ≈390 / AS OF FEB 2023 · HE SAYS\" -- placed clear of the scale's figures, the hub and the readout. `readout`: a line in the readout under the date -- \"HEAVIEST HE'S SAID: ≈390 (FEB 2023)\", the goal under it -- and the rim marker. `callout`: as he says it a ghost needle sweeps from where the needle stands to the value and a label (\"HEAVIEST HE'S SAID / ≈390 / AS OF FEB 2023\") holds 2.2 s, then the rim's flag. The words are the ledger's: its qualifier, its asOf's month; HEAVIEST only for the record's highest remembered weight above every weight he stated (the peak extra's `totals.peakDrift`), else \"HE SAYS HE WAS\". Each is up while it is the latest remembered; the thin rim ticks of every remembered weight stay as they are", "`umtool look <p> deck.dial.rememberedAs=rim`"],
+ ["`deck.measure.flash`", "bool · default `false` (off: every cut renders as before) -- THE UPDATE FLASH for every measure widget at once (update-flash.mjs): at the moment a widget's shown value changes its outline lights in its own colour and decays (0.15 s up, 0.7 s down) -- the dial on a weight stated or remembered or a goal change, the odometer on the pounds lost or NET, the trail on each weight landing, the goal stack on a goal set, the diet tags on a new diet; widgets that change on one event flash together; never on frame 0, while the deck is away (the intro, a card) or on a widget's first appearance. A widget's own `flash` overrides it", "`umtool look <p> deck.measure.flash=true`"],
["`deck.measure.ghosts.opacity`, `.tolerance`", "0.15–0.9 (the 1× tick's; +0.2 a step, at most 0.95) · 0–5 lb · default `0.5`, `0.5`", "`umtool look <p> deck.measure.ghosts='{\"tolerance\":1}'`"],
["`deck.measure.ghosts.ramp`, `.pulse`", "2–4 #hex, 1× first (the last for every count from there up), or `null`: the palette's muted, amber, and amber half way to the needle's red · bool · default `null`, `true`", "`umtool look <p> deck.measure.ghosts='{\"ramp\":[\"#98a29b\",\"#e8a33f\",\"#f37e47\"],\"pulse\":false}'`"],
["`deck.dial.needle`", "a #hex · default `#ff5a4e`", "`umtool look <p> deck.dial.needle='\"#ff5a4e\"'`"],
@@ -62,6 +66,7 @@ export default defineModule({
["`deck.dial.corner`", "`bottom-right` `bottom-left` `top-right` `top-left` · default `bottom-right` (the corner only): the dial in that corner, the odometer and the trail up the same side. The measure extras stand at their own anchors in the footage (goals bottom-right, peak top-right, promise top-centre, diet bottom-left, streak bottom-centre): a corner instrument over one that is on is REFUSED by the build, naming it -- move one (`deck.goals.position`, …) or the corner; `top-left` is clear of all five", "`umtool look <p> deck.dial.corner=top-left`"],
["`deck.dial.motion`", "`spring` `ease` · default `spring`. A VARIANT: the needle's `back.out` overshoot and settle, or a plain `power2.inOut` (the finale's drop too)", "`umtool look <p> deck.dial.motion=ease`"],
["`deck.dial.finaleEnd`", "`auto` `odometer` `promise` · default `auto` (`promise` when a promise is on camera, else `odometer`): `promise` hands the finale's last beat to the promise clock (module `promise`) -- the instruments fade out once NET has held (`dialFinaleHandoff`) and the clock takes their place in the finale's lower column, clear of the rail; with no promise module on the cut it ends on the odometer", "`umtool look <p> deck.dial.finaleEnd=promise`"],
+ ["`deck.dial.flash`", "bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the bezel lights as a weight is stated or remembered, or the goal in force changes; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away", "`umtool look <p> deck.dial.flash=false`"],
],
},
region: "dial",
diff --git a/umtool/report-to-video/modules/diet.mjs b/umtool/report-to-video/modules/diet.mjs
@@ -25,6 +25,7 @@ export default measureExtraModule({
{ key: "tags", type: "number", min: DIET_TAGS[0], max: DIET_TAGS[1], step: 1, label: "Tags in the row", default: 3, when: { form: "tags" } },
{ key: "overlap", type: "number", min: DIET_OVERLAP[0], max: DIET_OVERLAP[1], step: 0.05, label: "Overlap (0: side by side; the share of each older tag behind the one in front)", default: 0, when: { form: "tags" } },
{ key: "days", type: "boolean", label: "Days on the diet, on the front tag", default: false, when: { form: "tags" } },
+ { key: "flash", type: "boolean", label: "Flash its outline when its value changes (unset: deck.measure.flash)" },
],
docs: {
intro: "The diet he names as a rubber stamp in a corner of the footage box (`render.chrome.deck.diet`, measure-extras.mjs): at each change of the state's diet -- its regime or its diet number -- a new stamp slams on (in big and turned, onto the page, a shake), the regime's word in its ink and \"DIET #n\" under it with the ledger's words when they say more (\"Keto · 5 carbs a day\"); a change of words alone fades the new stamp in. A null diet after one fades to \"NO DIET\" in grey. It draws `state.diet` as the measure slice gives it -- the off-scope rule (\"off GLP-1\" while on keto is still keto) is the ledger's. The inks default to the quartering-diet regimes' (keto #E0913C, carnivore #C9534B, fasting #4E9BD8, calories #3FA9A0, glp1 #B168C6, other #8E97A8, off #98A29B).",
@@ -36,6 +37,7 @@ export default measureExtraModule({
["`deck.diet.overlap`", `${DIET_OVERLAP[0]}–${DIET_OVERLAP[1]}, the share of each older tag hidden behind the one in front · default 0 (side by side, the slam and the dim). Above 0 the tags FAN sideways the way the goal stack's notes pile: the newest in front at the left, landing from above like a goal note, each older one a place to the right behind it with its own small turn, keeping its colours (the depth is the overlap and the shadow), showing its regime word and date in the strip beside the one in front; the one past \`tags\` slides off the back. The fan is narrower by what hides. An older tag's word and date need ${DIET_BACK_MIN} design px of it, so it is refused past ${dietOverlapMax(false)} (${dietOverlapMax(true)} with \`days\`)`, "`umtool look <p> deck.diet.overlap=0.5`"],
["`deck.diet.days`", "`true` · `false`: the front tag's running count of days on its diet (to the in-record date at the playhead, the streak chain's \"Day N\"), in a column of its own -- the tag 300 design px wide · default `false`", "`umtool look <p> deck.diet.days=true`"],
["`deck.diet.colors`, `.labels`", "`{<regime>: #hex}` · `{<regime>: words ≤40}` · default the regimes' inks and names", "`umtool look <p> deck.diet.labels='{\"glp1\":\"Ozempic\"}'`"],
+ ["`deck.diet.flash`", "bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): with `form: \"tags\"`: the new front tag lights, in its ink, at a new diet or new words for it -- never the running day count, never the first tag; the stamp form does not flash; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away", "`umtool look <p> deck.diet.flash=false`"],
],
},
});
diff --git a/umtool/report-to-video/modules/goals.mjs b/umtool/report-to-video/modules/goals.mjs
@@ -22,15 +22,19 @@ export default measureExtraModule({
{ key: "max", type: "number", min: MEASURE_LIMITS.max[0], max: MEASURE_LIMITS.max[1], label: "Notes shown", default: 4 },
{ key: "color", type: "color", label: "Paper (default the palette's amber)" },
{ key: "countdown", type: "boolean", label: "Count a deadline down to the render date", default: true },
+ { key: "base", type: "boolean", label: "Say the weight he had stated when he set it", default: false },
+ { key: "flash", type: "boolean", label: "Flash its outline when its value changes (unset: deck.measure.flash)" },
],
docs: {
intro: "A sticky note per goal on a pile in a corner of the footage box, read off the schedule's `measure` slice (`render.chrome.deck.goals`, measure-extras.mjs): each goal or goalLoss event drops one, turned a little, onto the pile; the same goal in the same words (\"lose 100\") merges into its note with a count (\"×8\") and comes to the front; `max` notes show, the newest in front, with the goals set so far under them. A goal with a `deadline` counts down to `measure.asOfRender` (\"by Christmas · 50 days left · needs 226.5\"): Christmas is the next 25 Dec from the day he said it, \"next year\" a year on, a named year that year; words that name no date (\"by my birthday\") keep their label and no countdown. On whenever the cut has a measure slice with a goal on camera; `false` turns it off. Up for `hold` seconds after each goal (default 20), the pile as it stands each time. The four measure extras sit at anchors of the footage box by default, clear of the instrument panel's right column and of the top-left, where the streams' face cam most often is (the diet badge bottom-left, the goal stack bottom-right, the moving start top-right, the promise clock top-centre); `position` or `x`/`y` move one.",
rows: [
- ["`deck.goals`", "`true` · `false` · `{show, position, x, y, scale, hold, finale, max, color, countdown}` · default on with a measure slice", "`umtool look <p> deck.goals=false`"],
+ ["`deck.goals`", "`true` · `false` · `{show, position, x, y, scale, hold, finale, max, color, countdown, base}` · default on with a measure slice", "`umtool look <p> deck.goals=false`"],
["`deck.goals.position`, `.x`/`.y`, `.scale`", "`top-left` `top-right` `bottom-left` `bottom-right` `top-center` `bottom-center` · design px · 0.5–2 · default `bottom-right`, unset, 1", "`umtool look <p> deck.goals.position=bottom-left`"],
["`deck.goals.position=shelf`", "its shelf form (`deck.shelf`): the count of goals set in a column, then the notes fanned sideways like the diet's tags -- ordered by the dial's goal board (measure-goals.mjs \`goalsAt(goalBoard(schedule.measure), t)\`, so the shelf and the dial always agree): its headline -- the closest goal in force -- in front with \"+N more\" for the others in force, the rest by recency; a goal the board misses struck in red, MISSED on it, for the dial's 6 s; with no goal in force, the newest in front; a new goal landing from above as on the pile; each older one showing its goal's words in the strip beside it (all of each when there is room); a repeat comes to the front with its ×n. The fan takes the shelf's spare width (shelfLayout), up to its notes side by side. On the shelf it stays up from the first goal (`hold` unset). What the dial draws of the goal stays on the dial", "`umtool look <p> deck.shelf.items='[\"diet\",\"goals\"]' deck.goals.position=shelf`"],
["`deck.goals.max`, `.color`, `.countdown`", "1–8 notes · #hex paper · bool · default 4, the palette's amber, `true`", "`umtool look <p> deck.goals.max=6`"],
+ ["`deck.goals.base`", "bool · default `false`: each note also says the weight he had stated when he set the goal -- \"LOSE 100 (FROM 346.7)\", its qualifier kept (\"(FROM ≈390)\") -- the slice's own base for that goal, the one the gauge reckons its target from (measure-slice.mjs `goalBase`: the start of the run open when he set it, else the latest weight he gave by the goal's date, stated or remembered). A goal with no base (no weight by then, a target goal such as \"250 LB\", a base the scale's foot refuses) shows none -- never one made up. On a back card it is a line of its own, right-aligned like the label", "`umtool look <p> deck.goals.base=true`"],
["`deck.goals.hold`, `.finale`", "0 (up from the first goal on) or 2–600 s after each · `hide` `show` · default 20, `hide`", "`umtool look <p> deck.goals.hold=0`"],
+ ["`deck.goals.flash`", "bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the note that lands lights as a goal is set -- not the first note (the stack coming up), not the board's own changes; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away", "`umtool look <p> deck.goals.flash=false`"],
],
},
});
diff --git a/umtool/report-to-video/modules/measure-extras-settings.mjs b/umtool/report-to-video/modules/measure-extras-settings.mjs
@@ -6,10 +6,10 @@
// SETTINGS), so it imports only instruments.mjs (a leaf too: whether the
// instruments' column is on decides two defaults here).
//
-// render.chrome.deck.goals { show, position, x, y, scale, hold, finale, max, color, countdown }
+// render.chrome.deck.goals { show, position, x, y, scale, hold, finale, max, color, countdown, base, flash }
// render.chrome.deck.peak { show, position, x, y, scale, hold, finale, title, color, values }
// render.chrome.deck.promise { show, position, x, y, scale, hold, finale, label, verb, kept, broken, checks, speakers, claimVerb, claimColor }
-// render.chrome.deck.diet { show, position, x, y, scale, hold, finale, colors, labels, form, tags, overlap, days }
+// render.chrome.deck.diet { show, position, x, y, scale, hold, finale, colors, labels, form, tags, overlap, days, flash }
// render.chrome.deck.streak { show, position, x, y, scale, hold, finale, source, axis, title, color, colors, labels }
//
// Each is ON whenever the cut has a measure slice (the build writes one only
@@ -122,7 +122,9 @@ export const MEASURE_DEFAULTS = Object.freeze({
// The sticky notes pile in the bottom-right corner, up for `hold` seconds
// after each goal; `max` notes show, the newest in front; `color` is the
// paper (default the palette's amber).
- goals: Object.freeze({ ...COMMON, position: "bottom-right", hold: 20, max: 4, color: null, countdown: true }),
+ // `base`: each note also says the weight he had stated when he set it, "(FROM 346.7)" (the slice's goal base).
+ // `flash`: the update flash (update-flash.mjs) -- null follows deck.measure.flash, true/false for this module.
+ goals: Object.freeze({ ...COMMON, position: "bottom-right", hold: 20, max: 4, color: null, countdown: true, base: false, flash: null }),
// The moving start: up for `hold` seconds after each retelling.
peak: Object.freeze({ ...COMMON, position: "top-right", hold: 12, title: "The start keeps moving", color: null, values: "drift" }),
// The promise clock: up from the promise on, through the finale.
@@ -134,7 +136,7 @@ export const MEASURE_DEFAULTS = Object.freeze({
speakers: Object.freeze({}), claimVerb: "paid", claimColor: "#E37AB8", slot: "auto" }),
// The diet badge: up from the first diet on, re-stamped at every change.
// `form` "tags" (the default on the shelf): the last `tags` diets as dated tags, the newest slammed in at the left.
- diet: Object.freeze({ ...COMMON, position: "bottom-left", colors: Object.freeze({}), labels: Object.freeze({}), form: "stamp", tags: 3, overlap: 0, days: false }),
+ diet: Object.freeze({ ...COMMON, position: "bottom-left", colors: Object.freeze({}), labels: Object.freeze({}), form: "stamp", tags: 3, overlap: 0, days: false, flash: null }),
// The streak chain: bottom-centre, between the diet badge and the goal
// stack, so either or both can run. `title` null is the source's own word.
streak: Object.freeze({ ...COMMON, position: "bottom-center", source: "diet", axis: "date", title: null, color: null, colors: Object.freeze({}), labels: Object.freeze({}) }),
@@ -262,6 +264,10 @@ export function validateMeasureExtra(id, v, where = `render.chrome.deck.${id}`,
}
color(v.color, `${where}.color`, errors);
if (v.countdown !== undefined && typeof v.countdown !== "boolean") errors.push(`${where}.countdown must be true or false`);
+ if (v.base !== undefined && typeof v.base !== "boolean") errors.push(`${where}.base must be true or false`);
+ }
+ if (id === "goals" || id === "diet") {
+ if (v.flash !== undefined && v.flash !== null && typeof v.flash !== "boolean") errors.push(`${where}.flash must be true, false or null (deck.measure.flash)`);
}
if (id === "peak") {
text(v.title, L.text, `${where}.title`, errors, { nullable: false });
diff --git a/umtool/report-to-video/modules/odometer.mjs b/umtool/report-to-video/modules/odometer.mjs
@@ -31,6 +31,7 @@ export default defineModule({
{ key: "label", type: "text", label: "Over the wheels", default: ODOMETER_DEFAULTS.label },
{ key: "net", type: "boolean", label: "NET beside them", default: true },
{ key: "runs", type: "boolean", label: "How many runs", default: true },
+ { key: "flash", type: "boolean", label: "Flash its outline when its value changes (unset: deck.measure.flash)" },
],
docs: {
heading: "Lost odometer",
@@ -39,6 +40,7 @@ export default defineModule({
["`deck.odometer`", "`true` · an object of the knobs below · `false` off · absent: ON when the cut draws a measure (`deck.measure` set), else off", "`umtool look <p> deck.odometer=false`"],
["`deck.odometer.label`", "words over the wheels, ≤ 40 · default `POUNDS HE SAYS HE'S LOST`", "`umtool look <p> deck.odometer.label='\"…\"'`"],
["`deck.odometer.net`, `.runs`", "bool · default `true` each", "`umtool look <p> deck.odometer.net=false`"],
+ ["`deck.odometer.flash`", "bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the card lights as the pounds lost go up (or the runs change) and as NET changes; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away", "`umtool look <p> deck.odometer.flash=false`"],
],
},
region: "odometer",
diff --git a/umtool/report-to-video/modules/promise.mjs b/umtool/report-to-video/modules/promise.mjs
@@ -9,7 +9,7 @@ import path from "node:path";
import { promiseHtml } from "../chrome-measure-extras.mjs";
import { measureOf, promiseStates } from "../measure-extras.mjs";
-import { avatarEntryOf } from "../post-avatars.mjs";
+import { avatarEntryOf, handleKey } from "../post-avatars.mjs";
import { measureExtraModule } from "./measure-extras-module.mjs";
import { PROMISE_CHECKS, resolveMeasureExtra } from "./measure-extras-settings.mjs";
@@ -27,10 +27,13 @@ async function speakerOpts(ctx) {
for (const s of m?.state ?? []) for (const p of s?.promises ?? []) for (const c of p?.claims ?? []) if (c?.speaker) speakers.add(c.speaker);
const handles = {};
const avatars = {};
+ // A speaker's settings matched as a handle is -- without @, without regard to case -- so
+ // `speakers.MadamSavvy` serves the measure's "madamsavvy" (post-avatars.mjs handleKey).
+ const spCfg = (sp) => cfg?.speakers?.[sp] ?? Object.entries(cfg?.speakers ?? {}).find(([k]) => handleKey(k) === handleKey(sp))?.[1];
for (const sp of speakers) {
- const want = cfg?.speakers?.[sp]?.handle ?? sp;
+ const want = spCfg(sp)?.handle ?? sp;
const entry = avatarEntryOf(ctx.manifest, want) ?? avatarEntryOf(ctx.manifest, sp);
- handles[sp] = String(cfg?.speakers?.[sp]?.handle ?? entry?.[0] ?? sp).replace(/^@/, "");
+ handles[sp] = String(spCfg(sp)?.handle ?? entry?.[0] ?? sp).replace(/^@/, "");
if (entry?.[1]?.src && ctx.manifestDir) {
const src = path.resolve(ctx.manifestDir, entry[1].src);
const url = await ctx.asset(src, `avatar-${sp.replace(/[^A-Za-z0-9_-]/g, "_")}${path.extname(src) || ".jpg"}`).catch(() => null);
diff --git a/umtool/report-to-video/modules/rail.test.mjs b/umtool/report-to-video/modules/rail.test.mjs
@@ -28,10 +28,13 @@ test("the deck at a pitch: pips after the first hidden until the marker reaches
const s = estimateSchedule({ render: r, timeline: [clip("a"), clip("b"), clip("c")], posts: [], provenance: {} });
const { init, cues, pips } = deckCues(s, r);
assert.deepEqual(pips.map((p) => p.x), [48, 88, 128]);
- assert.deepEqual(init.pb1, { opacity: 0 });
+ // The marker stands on the first pip from the cut's first instant, so the one after it is up from frame 0: in init,
+ // not an instant cue at 0 that only frame 1 could show (cue-start.mjs settleFirstFrame).
+ assert.deepEqual(init.pb1, { opacity: 1 });
+ assert.ok(!cues.some((c) => c.k === "pb1"));
assert.deepEqual(init.pb2, { opacity: 0 });
assert.equal(init.pb0, undefined);
- assert.ok(cues.some((c) => c.k === "pb1" && c.to.opacity === 1));
+ assert.ok(cues.some((c) => c.k === "pb2" && c.to.opacity === 1 && c.at > 0));
const html = deckHtml(s, r, {});
assert.match(html, /\.fuse \{ position: absolute; left: 48px; top: -1px; width: 1824px;/);
assert.match(html, /<div class="pip" data-k="pb1" style="left:85px"><\/div>/);
diff --git a/umtool/report-to-video/modules/trail.mjs b/umtool/report-to-video/modules/trail.mjs
@@ -30,15 +30,22 @@ export default defineModule({
{ key: "mark", type: "number", min: 0, max: 2000, step: 1, label: "The line across", default: 300 },
{ key: "count", type: "boolean", label: "Count the \"under 300\" claims", default: true },
{ key: "label", type: "text", label: "Its title", default: TRAIL_DEFAULTS.label },
+ { key: "bounds", type: "enum", options: ["fit", "fixed"], label: "Axes: fit what is shown so far, or fixed to the whole cut", default: "fit" },
+ { key: "remembered", type: "boolean", label: "His remembered weights as points too (hollow, not joined)", default: true },
+ { key: "flash", type: "boolean", label: "Flash its outline when its value changes (unset: deck.measure.flash)" },
],
docs: {
heading: "Weight trail",
- intro: "At the foot of the instruments' column: every STATED weight the cut shows, placed by the date he was weighed (its `asOf`, else its date) across the span of them, a dot appearing at its event's `t` and the line between two neighbours drawn once both are said; a red ring on the latest said. The `mark` line (300) dashed across; with `count` and the mark at 300, `UNDER 300 · SAID n×` counts the measure's `totals.under300` rows as the cut reaches each.",
+ intro: "At the foot of the instruments' column: every weight the cut shows -- the STATED ones and (`remembered`) the remembered ones, \"≈390, as of Feb 2023\" -- placed by the date he was that weight (its `asOf`, else its date), a dot appearing at its event's `t`; the line joins neighbours by date among the stated ones once both are said (a remembered one is a hollow grey dot, never joined; a qualified one hollow). The axes FIT what has been said so far (trail-plan.mjs): each new weight outside them reflows the chart over 0.4 s -- the years, the bounds, every dot -- so the time axis advances with the story; a stretch with no statement longer than `gap` is a break in the time axis (a narrow dashed band, `//` at its foot, each side with its own years) and the line across it dotted, so a decade of nothing does not take the width from the dense run after it. A red ring on the latest said. The `mark` line (300) dashed across; with `count` and the mark at 300, `UNDER 300 · SAID n×` counts the measure's `totals.under300` rows as the cut reaches each.",
rows: [
["`deck.trail`", "`true` · an object of the knobs below · `false` off · absent: ON when the cut draws a measure (`deck.measure` set), else off", "`umtool look <p> deck.trail=false`"],
["`deck.trail.mark`", "a weight, or `null` · default `300`", "`umtool look <p> deck.trail.mark=300`"],
["`deck.trail.count`", "bool · default `true`", "`umtool look <p> deck.trail.count=false`"],
["`deck.trail.label`", "its title, ≤ 40 · default `WHAT HE SAYS HE WEIGHS, BY DATE`", "`umtool look <p> deck.trail.label='\"…\"'`"],
+ ["`deck.trail.bounds`", "`fit` · `fixed` · default `fit`: the axes fit the weights said so far and reflow as each lands; `fixed` lays every moment on the axes of all the cut's weights", "`umtool look <p> deck.trail.bounds=fixed`"],
+ ["`deck.trail.remembered`", "bool · default `true`: his remembered weights are points too, hollow and grey, not joined into the line", "`umtool look <p> deck.trail.remembered=false`"],
+ ["`deck.trail.gap`", "`auto` · days 30–3650 · `0` none · default `auto`: a stretch with no statement longer than a year (or 8× the median spacing, if longer) is a break in the time axis", "`umtool look <p> deck.trail.gap=540`"],
+ ["`deck.trail.flash`", "bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the card lights as each weight lands on it; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away", "`umtool look <p> deck.trail.flash=false`"],
],
},
region: "trail",
diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs
@@ -49,6 +49,8 @@ export const POST_TAKE_ENGINES = Object.freeze([...POST_NARRATION_ENGINES, "reco
* { kind: "recorded", voice } a person's own read, recorded on the bench
* { kind: "take", from: <take id> } DERIVED: a new take made from another
* steps [{ op, engine?, params?, ranAt, job? }] the processing that made a derived take
+ * (a convert's also `voice`, the stock target, and -- when the read's pitch was FOLLOWED rather than
+ * flattened to the stock voice's -- `pitch: "source" | "contour"` and `semitones`, as the editor ran them)
*
* A derived take never overwrites the one it came from. Its ops are the
* editor's (each a job, like tts): `enhance` (denoise, level, de-reverb) and
@@ -190,7 +192,7 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz",
const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow", "thread"]);
const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "takes", "pick", "approved", "off", "window"]);
const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read"]);
-const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job", "drop", "tempo", "spans", "pauses", "revoice"]);
+const STEP_KEYS = new Set(["op", "engine", "voice", "pitch", "semitones", "params", "ranAt", "job", "drop", "tempo", "spans", "pauses", "revoice"]);
// `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's;
// `engine`: the part's own when it is not the take's (a cast voice that names its engine: postThreadRead.mjs).
// `tempo`: the part's reading speed in the take's file against its first read (a `tempo` step's; absent: 1).
@@ -661,6 +663,9 @@ export function validatePostNarration(e) {
if (!isObj(st) || !(POST_DERIVE_OPS.includes(st.op) || POST_LOCAL_OPS.includes(st.op))) errors.push(`${tw}.steps[${k}].op must be one of ${[...POST_DERIVE_OPS, ...POST_LOCAL_OPS].join(", ")}`);
else {
for (const key of Object.keys(st)) if (!STEP_KEYS.has(key)) errors.push(`${tw}.steps[${k}].${key} is not a step key`);
+ // A convert's followed pitch, as the editor ran it.
+ if (st.pitch !== undefined && !["target", "source", "contour"].includes(st.pitch)) errors.push(`${tw}.steps[${k}].pitch must be target, source or contour`);
+ if (st.semitones !== undefined && !(fin(st.semitones) && Math.abs(st.semitones) <= 12)) errors.push(`${tw}.steps[${k}].semitones must be a number from -12 to 12`);
// A re-join's record: what it left out (a piece, "part <n>", "url").
if (st.drop !== undefined && !(Array.isArray(st.drop) && st.drop.length <= 200 && st.drop.every((d) => typeof d === "string"))) errors.push(`${tw}.steps[${k}].drop must be a list of what it left out`);
// A tempo step's record: each run of parts ("4-16", "21") and the tempo it reads at.
diff --git a/umtool/report-to-video/remembered-looks.test.mjs b/umtool/report-to-video/remembered-looks.test.mjs
@@ -0,0 +1,82 @@
+// THE DIAL'S REMEMBERED-WEIGHT LOOKS (`deck.dial.rememberedAs`; operator, 11 Nov: "max weight statements could be
+// shown better" -- the long grey second needle and its small words crossed the main needle and the readout and did
+// not say what the weight was). Three looks beside today's, each worded from the ledger entry's own fields.
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { CALLOUT_HOLD, dialHtml, heaviestOf, rememberedMode, rememberedWords } from "./chrome-instruments.mjs";
+import { estimateSchedule } from "./deck.mjs";
+import { validateDial } from "./instruments.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const MEASURE = JSON.parse(readFileSync(path.join(HERE, "fixtures", "measure-remembered", "measure.json"), "utf8"));
+const PALETTE = { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" };
+const renderAs = (as) => ({ width: 1920, height: 1080, fps: 30, transition: 0.4, palette: PALETTE,
+ chrome: { engine: "hyperframes", layout: "deck", deck: { dial: as === undefined ? true : { rememberedAs: as }, odometer: true, trail: true } } });
+const page = (as) => {
+ const r = renderAs(as);
+ const timeline = Array.from({ length: 3 }, (_, i) => ({ type: "clip", id: `c${i + 1}`, video: "v", start: 0, end: 10 }));
+ const html = dialHtml({ ...estimateSchedule({ slug: "m", title: "M", provenance: {}, render: r, timeline }), measure: MEASURE }, r, { fonts: {} });
+ return { html, data: JSON.parse(/<script id="dial-data" type="application\/json">(.*?)<\/script>/s.exec(html)[1]) };
+};
+
+test("the words are the ledger's: its qualifier, its asOf's month; HEAVIEST only for the record's highest above every stated weight", () => {
+ assert.equal(heaviestOf(MEASURE), 390);
+ assert.equal(heaviestOf({ totals: {} }), null);
+ const top = rememberedWords({ value: 390, qualifier: "≈", asOf: "2023-02-24" }, 390);
+ assert.deepEqual([top.value, top.when, top.kind, top.line], ["≈390", "FEB 2023", "HEAVIEST HE'S SAID", "HEAVIEST HE'S SAID: ≈390 (FEB 2023)"]);
+ const other = rememberedWords({ value: 368, qualifier: null, asOf: "2008-06-30" }, 390);
+ assert.deepEqual([other.kind, other.line], ["HE SAYS HE WAS", "HE SAYS HE WAS: 368 (JUN 2008)"]);
+ // No peak drift on the record: nothing is called his heaviest.
+ assert.equal(rememberedWords({ value: 390, qualifier: "≈", asOf: "2023-02-24" }, null).heaviest, false);
+ assert.equal(rememberedWords({ value: 390, qualifier: "≈", asOf: null }, 390).line, "HEAVIEST HE'S SAID: ≈390");
+});
+
+test("needle (the default) is today's dial; rim, readout and callout draw no long needle at rest and no floating as-of words", () => {
+ assert.equal(rememberedMode({}), "needle");
+ assert.deepEqual(validateDial({ rememberedAs: "rim" }), []);
+ assert.match(validateDial({ rememberedAs: "flag" }).join(), /rememberedAs must be "needle" or "rim" or "readout" or "callout"/);
+ const today = page(undefined);
+ assert.deepEqual(page("needle").html, today.html, "needle is the default, byte for byte");
+ assert.match(today.html, /data-k="gn"/);
+ assert.match(today.html, /class="asof" data-k="ga0"/);
+ for (const as of ["rim", "readout"]) {
+ const { html } = page(as);
+ assert.doesNotMatch(html, /data-k="gn"|class="asof"/, as);
+ assert.match(html, /data-k="gk0"/, `${as}: the rim marker`);
+ }
+ assert.match(page("rim").html, /class="rflag" data-k="gl0"[^>]*><span>HEAVIEST<\/span><b>≈390<\/b><span>FEB 2023<\/span>/);
+ assert.match(page("rim").html, /class="rflag" data-k="gl1"[^>]*><span>REMEMBERED<\/span><b>368<\/b><span>JUN 2008<\/span>/);
+ assert.match(page("readout").html, /class="rline" data-k="gr0"[^>]*>HEAVIEST HE'S SAID: ≈390 \(FEB 2023\)<|class="rline" data-k="gr0"[^>]*>HEAVIEST HE'S SAID: ≈390 \(FEB 2023\)</);
+ // The goal line moves under the remembered line in the readout look.
+ const goalTop = (html) => Number(/class="goalw" data-k="gw\d+" style="top:([\d.]+)px"/.exec(html)[1]);
+ assert.ok(goalTop(page("readout").html) > goalTop(today.html));
+});
+
+test("the rim's flag is never on the hub or the readout", () => {
+ const { html } = page("rim");
+ const at = /class="rflag" data-k="gl0" style="left:([\d.]+)px; top:([\d.]+)px"/.exec(html);
+ const [x, y] = [Number(at[1]), Number(at[2])];
+ // The dial's 540 face: centre 270, the readout's words from 60 px under it.
+ assert.ok(Math.hypot(x - 270, y - 270) > 80, `clear of the hub (${x}, ${y})`);
+ assert.ok(!(y > 270 + 40 && Math.abs(x - 270) < 128), `clear of the readout (${x}, ${y})`);
+});
+
+test("one at a time, the latest remembered; the callout sweeps a ghost needle and holds its label, then the flag", () => {
+ const rim = page("rim").data;
+ const up = (d, k) => d.cues.filter((c) => c.k === k && c.to.autoAlpha === 1).map((c) => c.at);
+ const down = (d, k) => d.cues.filter((c) => c.k === k && c.to.autoAlpha === 0).map((c) => c.at);
+ assert.deepEqual(up(rim, "gl0"), [3]);
+ assert.deepEqual(down(rim, "gl0"), [8], "gives way to the next remembered");
+ assert.deepEqual(up(rim, "gl1"), [8]);
+ const call = page("callout").data;
+ assert.deepEqual(up(call, "gl0"), [3 + CALLOUT_HOLD], "the flag after the hold");
+ assert.deepEqual(up(call, "gc0"), [3.25]);
+ assert.deepEqual(down(call, "gc0"), [3 + CALLOUT_HOLD]);
+ const gn = call.cues.filter((c) => c.k === "gn");
+ assert.ok(gn.some((c) => c.at === 3 && c.to.autoAlpha === 0.9), "the ghost needle comes up where the needle stands");
+ assert.ok(gn.some((c) => Math.abs(c.at - (3 + CALLOUT_HOLD)) < 1e-6 && c.to.autoAlpha === 0), "and goes after the hold");
+});
diff --git a/umtool/report-to-video/shelf.test.mjs b/umtool/report-to-video/shelf.test.mjs
@@ -10,11 +10,11 @@ import path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
-import { dietHtml, goalsHtml, shelfGoalStates, tagWords, tagWordSize } from "./chrome-measure-extras.mjs";
+import { backTextSize, dietHtml, GOALS_BACK, goalsHtml, shelfGoalStates, tagWords, tagWordSize } from "./chrome-measure-extras.mjs";
import { goalBoard, goalsAt } from "./measure-goals.mjs";
import { shelfHtml, shelfNoteGeometry } from "./chrome-shelf.mjs";
import { deckGeometry, entryShelfNotes, estimateSchedule, instrumentsGeometry, parseShelfNote, validateChrome } from "./deck.mjs";
-import { dietDays, dietStates, goalStates, dietTagsBox, GOALS_SHELF, goalsShelfWidth, measureExtraGeometry, measurePlacements, shelfLayout, streakStates } from "./measure-extras.mjs";
+import { dietDays, dietStates, goalBaseText, goalStates, dietTagsBox, GOALS_SHELF, goalsShelfWidth, measureExtraGeometry, measurePlacements, shelfLayout, streakStates } from "./measure-extras.mjs";
import { slotRect } from "./modules/layout.mjs";
import { moduleById, moduleProblems, scheduleSlices } from "./modules/index.mjs";
import { resolveMeasureExtra, validateMeasureExtra } from "./modules/measure-extras-settings.mjs";
@@ -258,7 +258,7 @@ test("goals on the shelf: the count and the fanned notes, the fan taking the she
const { html, items } = goalsHtml(schedule(), r, { fonts: {} });
assert.match(html, /<div class="gc"><div class="gn" data-k="s0\.c">1<\/div><div class="gl">goal set<\/div><\/div>/);
assert.match(html, /class="note" data-k="s\d+\.n\d+" style="z-index:19"><div class="tape"><\/div><div class="nf"/);
- assert.match(html, /<div class="nb"[^>]*><div class="bt">LOSE 100<\/div>/, "an older note shows its words beside the one in front");
+ assert.match(html, /<div class="nb"[^>]*><div class="bt"[^>]*>LOSE 100<\/div>/, "an older note shows its words beside the one in front");
// A block per state of the fan: each goal he sets, and each second the goal board alone changes (shelfGoalStates).
assert.equal(items.length, shelfGoalStates(schedule(), goalStates(schedule(), r)).length);
// Off the shelf: the pile in the footage, as it was.
@@ -286,3 +286,78 @@ test("goals on the shelf: the dial's goal board orders the fan -- its headline i
const { html } = goalsHtml(sched, r, { fonts: {} });
assert.match(html, new RegExp(`<div class="mo">\\+${end.active.length - 1} more</div>`));
});
+
+// ---------------------------------------------------------------------------
+// A BACK CARD (operator, 11 Nov): "LOSE 1…" for "LOSE 100" -- the right end is what tells one goal from another, so a
+// back card is never cut on the right: its words end at the card's right edge and their LEFT goes under the card in
+// front. And a goal may say the weight he had stated when he set it, "LOSE 100 (FROM 346.7)" (`goals.base`).
+// ---------------------------------------------------------------------------
+
+/** The page's CSS rule for `sel`, as written. */
+const ruleOf = (html, sel) => new RegExp(`\\n\\s*\\${sel} \\{([^}]*)\\}`).exec(html)?.[1] ?? "";
+
+test("a back card's words are right-aligned to its right edge and never cut with an ellipsis -- for 2, 3, 4 and 8 notes", () => {
+ for (const max of [2, 3, 4, 8]) {
+ const r = renderOf({ ...FAN, goals: { position: "shelf", max } });
+ const { html } = goalsHtml(schedule(), r, { fonts: {} });
+ if (!/class="nb"/.test(html)) continue; // room for every note side by side: no back strips at all
+ const nb = ruleOf(html, ".nb"), bt = ruleOf(html, ".bt"), bh = ruleOf(html, ".bh");
+ assert.match(nb, /align-items: flex-end/, `${max}: the words end at the right`);
+ assert.match(nb, /text-align: right/);
+ assert.match(nb, /left: 0; right: 0/, `${max}: the strip is the card's whole width, so an overflow goes LEFT, under the card in front`);
+ for (const [name, rule] of [["bt", bt], ["bh", bh]]) {
+ assert.doesNotMatch(rule, /ellipsis|max-width/, `${max}: .${name} is never cut on the right`);
+ }
+ // The ×n badge has the top of the strip to itself: the words start under it.
+ const padTop = Number(/padding: ([\d.]+)px/.exec(nb)[1]);
+ const ct = ruleOf(html, ".ct");
+ const badgeFoot = Number(/top: ([\d.]+)px/.exec(ct)[1]) + Number(/height: ([\d.]+)px/.exec(ct)[1]);
+ assert.ok(badgeFoot <= padTop, `${max}: the ×n badge (to ${badgeFoot} px) is above the words (from ${padTop} px)`);
+ }
+ // Sized to fit the strip when they can, 17 px at the least; past that the left goes under.
+ assert.equal(backTextSize("LOSE 40", 80), 22);
+ assert.equal(backTextSize("LOSE 100", 80), 20);
+ assert.equal(backTextSize("LOSE 100 LB OR SO", 80), GOALS_BACK.min);
+ assert.equal(backTextSize("X", 300), GOALS_BACK.max);
+});
+
+test("goals.base: off by default; on, each loss goal says the weight the slice reckons it from, its qualifier kept, never one made up", () => {
+ assert.deepEqual(validateMeasureExtra("goals", { base: true }), []);
+ assert.match(validateMeasureExtra("goals", { base: "yes" }).join(), /base must be true or false/);
+ const off = goalStates(schedule(), renderOf(FAN));
+ assert.ok(off.every((st) => st.notes.every((n) => n.base === null)), "off: no base");
+ const r = renderOf({ ...FAN, goals: { position: "shelf", base: true } });
+ // The slice's bases (measure-slice.mjs goalBase; the fixture predates them): w06 from a stated 346.7, w13 from a
+ // remembered ≈390, every other goal none.
+ const m = clone(MEASURE);
+ m.events.push({ t: null, row: "wb1", kind: "stated", value: 346.7, qualifier: null }, { t: null, row: "wb2", kind: "remembered", value: 390, qualifier: "≈" });
+ for (const st of m.state) {
+ if (st.goal?.row === "w06") st.goal.base = { value: 346.7, row: "wb1", from: "stated" };
+ if (st.goal?.row === "w13") st.goal.base = { value: 390, row: "wb2", from: "remembered" };
+ }
+ const sched = schedule({ measure: m });
+ const states = goalStates(sched, r);
+ // Each note's base is its own goal's state's `goal.base` -- the gauge's -- or none.
+ let withBase = 0;
+ for (const st of states) {
+ const e = m.events.find((x) => x.t === st.at && (x.kind === "goal" || x.kind === "goalLoss"));
+ const s = [...m.state].reverse().find((x) => x.t <= st.at + 1e-9 && x.goal?.row === e.row);
+ const top = st.notes.find((n) => n.key === st.top);
+ const want = s?.goal?.base ? goalBaseText(s.goal.base, m) : null;
+ assert.equal(top.base, want, `${e.row}: the slice's base or none`);
+ if (want) withBase += 1;
+ }
+ assert.equal(withBase, 2);
+ assert.ok(states.some((st) => st.notes.some((n) => n.base === "(FROM ≈390)")));
+ // The words: "(FROM 346.7)", a qualifier kept, nothing for no base.
+ const mm = { events: [{ row: "w21", qualifier: "≈" }, { row: "w7", qualifier: null }] };
+ assert.equal(goalBaseText({ value: 346.7, row: "w7" }, mm), "(FROM 346.7)");
+ assert.equal(goalBaseText({ value: 390, row: "w21" }, mm), "(FROM ≈390)");
+ assert.equal(goalBaseText(null, mm), null);
+ // Drawn on the front card under the goal, and on a back card as a line of its own, right-aligned with the words.
+ const { html } = goalsHtml(sched, r, { fonts: {} });
+ assert.match(html, /<div class="nt">[^<]+<\/div><div class="fr">\(FROM [≈<>]?[\d.]+\)<\/div>/);
+ assert.match(html, /<div class="bt"[^>]*>[^<]+<\/div><div class="bf">\(FROM [≈<>]?[\d.]+\)<\/div>/);
+ // Off: none of it.
+ assert.doesNotMatch(goalsHtml(schedule(), renderOf(FAN), { fonts: {} }).html, /class="(fr|bf)"/);
+});
diff --git a/umtool/report-to-video/stats.test.mjs b/umtool/report-to-video/stats.test.mjs
@@ -137,9 +137,11 @@ test("the page: one block per state, the numbers as the panel shows them, every
const schedule = estimateSchedule({ render: render(), timeline: ENTRIES, frameScan: OVERLAY });
const { init, cues } = statsCues(schedule);
assert.deepEqual(Object.keys(init).sort(), ["pn", "s0_0", "s0_1", "s1_0"]);
- // The first state shows at the clip's in, hides as the second shows.
+ // The first state shows at the clip's in -- here the cut's first instant, so it is up in init, on frame 0 (cue-start.mjs
+ // settleFirstFrame) -- and hides as the second shows.
const s00 = cues.filter((c) => c.k === "s0_0");
- assert.deepEqual(s00.map((c) => [c.at, c.from.autoAlpha, c.to.autoAlpha]), [[0, 0, 1], [6, 1, 0]]);
+ assert.equal(init.s0_0.autoAlpha, 1);
+ assert.deepEqual(s00.map((c) => [c.at, c.from.autoAlpha, c.to.autoAlpha]), [[6, 1, 0]]);
for (const c of cues) assert.ok(Object.keys(c.to).every((p) => p in c.from), JSON.stringify(c));
const html = statsHtml(schedule, render(), { fonts: { regular: "assets/DeckSans.ttf", bold: "assets/DeckSansBold.ttf" } });
diff --git a/umtool/report-to-video/threads.mjs b/umtool/report-to-video/threads.mjs
@@ -23,6 +23,7 @@ import { resolveFactcheck } from "./factcheck.mjs";
// The limits and the validators are common's (lib/report/panels.mjs, release
// 28): the threads draft task checks exactly what the build refuses.
import { THREADS_LIMITS, threadOf, threadsOn, validateThreadEntries, validateThreads } from "yt-dlp-transcript-common/lib/report/panels.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
export { THREADS_LIMITS, threadOf, threadsOn, validateThreadEntries, validateThreads };
@@ -172,7 +173,7 @@ export function planCues(init, events, instant = 0.001) {
freeAt.set(e.k, r4(at + dur));
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why });
}
- return cues;
+ return settleFirstFrame(init, cues);
}
/** A card's resting opacity before its thread plays, and after. */
diff --git a/umtool/report-to-video/trail-plan.mjs b/umtool/report-to-video/trail-plan.mjs
@@ -0,0 +1,149 @@
+// THE TRAIL'S PLAN (the by-date chart strip under the instruments, 11 Nov): which
+// weights it shows at each moment of the cut, and where each one stands then.
+//
+// Before this the strip laid every STATED weight of the whole cut on one fixed
+// pair of axes from the first frame: a remembered weight ("≈390, as of Feb
+// 2023", "368 as of Jun 2008") was never a point, a 2013 weigh-in sat pinned at
+// the left edge of a 2013–2026 axis for minutes, and one straight line crossed
+// a decade of nothing to the 2025–26 points squeezed into the last pixels.
+//
+// Now the chart is a sequence of STATES, one per moment a weight is said: the
+// points said so far -- stated ones, and remembered ones (`remembered`, hollow
+// and grey, never joined into the line) -- at their own dates (asOf, else the
+// day said) and values; the axes FIT what is shown (`bounds: "fit"`; "fixed"
+// pins them to the whole cut's points); and a stretch of time with no statement
+// longer than the gap threshold (`gap`) is not drawn as data: the time axis is
+// cut there into CLUSTERS, each with its own years, a narrow break between them
+// and a dotted connector across it, so the dense recent run gets the width. The
+// page (chrome-instruments.mjs trailHtml) moves everything from one state's
+// places to the next's over TRAIL_REFLOW seconds.
+//
+// PURE: the measure slice and a box in, plain data out.
+import { dayNumber } from "./measure-draw.mjs";
+
+/** Seconds a reflow takes: the axes and every point moving to the new state's places. */
+export const TRAIL_REFLOW = 0.4;
+
+/** `gap: "auto"`: a stretch is a break when longer than this many days, or `GAP_MEDIANS` times the median spacing. */
+export const GAP_FLOOR_DAYS = 365;
+export const GAP_MEDIANS = 8;
+
+const r2 = (v) => Math.round(v * 100) / 100;
+
+/**
+ * The trail's points, in the order the cut says them: `{ n, t, row, value, qualifier, day, kind }`, `kind`
+ * "stated" or "remembered" (only with `remembered`), `day` the day number of its asOf, else its date.
+ */
+export function trailPoints(measure, { remembered = true } = {}) {
+ const out = [];
+ for (const e of measure?.events ?? []) {
+ if (!Number.isFinite(e.t) || !Number.isFinite(Number(e.value))) continue;
+ if (e.kind !== "stated" && !(remembered && e.kind === "remembered")) continue;
+ const day = dayNumber(e.asOf ?? e.date);
+ if (!Number.isFinite(day)) continue;
+ out.push({ t: e.t, row: e.row ?? null, value: Number(e.value), qualifier: e.qualifier ?? null, day, kind: e.kind });
+ }
+ out.sort((a, b) => a.t - b.t);
+ return out.map((p, n) => ({ ...p, n }));
+}
+
+/** The gap threshold in days: `gap` a number of days, 0/false never, "auto" from the data (see GAP_FLOOR_DAYS). */
+export function gapThreshold(points, gap = "auto") {
+ if (gap === 0 || gap === false) return Infinity;
+ if (typeof gap === "number" && gap > 0) return gap;
+ const days = [...new Set(points.map((p) => p.day))].sort((a, b) => a - b);
+ const steps = days.slice(1).map((d, i) => d - days[i]).sort((a, b) => a - b);
+ const median = steps.length ? steps[Math.floor(steps.length / 2)] : 0;
+ return Math.max(GAP_FLOOR_DAYS, GAP_MEDIANS * median);
+}
+
+/** Days, sorted, cut into clusters where a step is longer than `thr`: `[{ first, last }]`. */
+export function clustersOf(days, thr) {
+ const ds = [...new Set(days)].sort((a, b) => a - b);
+ const out = [];
+ for (const d of ds) {
+ const c = out[out.length - 1];
+ if (c && d - c.last <= thr) c.last = d;
+ else out.push({ first: d, last: d });
+ }
+ return out;
+}
+
+const yearOf = (d) => new Date(d * 86400000).getUTCFullYear();
+const jan1 = (y) => Date.UTC(y, 0, 1) / 86400000;
+
+/**
+ * One state's places: the y bounds (`lo`/`hi`, tens of the unit around the values shown and the mark), the
+ * clusters along x (each `{ first, last, from, to, x0, x1 }`: its days, its padded span, its pixels), the breaks
+ * between them (`gaps`: `{ key, x }`), the year labels (`years`: `{ key, text, x, tick }`), and `X(day)` / `Y(v)`.
+ *
+ * `box` = `{ x0, x1, y0, y1, gapPx, yearPx }` in page pixels.
+ */
+export function trailLayout(points, box, { thr = Infinity, mark = null } = {}) {
+ const { x0, x1, y0, y1 } = box;
+ const gapPx = box.gapPx ?? 22;
+ const yearPx = box.yearPx ?? 34;
+ const vals = points.map((p) => p.value).concat(mark !== null && mark !== undefined ? [mark] : []);
+ const lo = vals.length ? Math.floor((Math.min(...vals) - 5) / 10) * 10 : 0;
+ const hi = vals.length ? Math.ceil((Math.max(...vals) + 5) / 10) * 10 : 10;
+ const cl = clustersOf(points.map((p) => p.day), thr);
+ const spread = cl.reduce((s, c) => s + (c.last - c.first), 0);
+ const pad = Math.max(20, 0.04 * spread);
+ for (const c of cl) {
+ const p = c.last - c.first < 1 ? Math.max(pad, 60) : pad;
+ c.from = c.first - p;
+ c.to = c.last + p;
+ }
+ const widthDays = cl.reduce((s, c) => s + (c.to - c.from), 0) || 1;
+ const scale = Math.max(0, x1 - x0 - gapPx * Math.max(0, cl.length - 1)) / widthDays;
+ let at = x0;
+ for (const c of cl) {
+ c.x0 = r2(at);
+ c.x1 = r2(at + (c.to - c.from) * scale);
+ at = c.x1 + gapPx;
+ }
+ const X = (d) => {
+ const c = cl.find((k) => d >= k.from - 1e-9 && d <= k.to + 1e-9) ?? null;
+ return c ? r2(c.x0 + (d - c.from) * scale) : null;
+ };
+ const Y = (v) => r2(y1 - ((v - lo) / Math.max(1, hi - lo)) * (y1 - y0));
+ const gaps = cl.slice(1).map((c, i) => ({ key: `${cl[i].last}_${c.first}`, x: r2((cl[i].x1 + c.x0) / 2) }));
+ // The years: each cluster's first year labelled at its first point (unless that year's 1 January is a tick in it),
+ // each 1 January inside a cluster's span a tick; then thinned left to right so no two labels are closer than
+ // `yearPx`, a cluster's own year first.
+ const cands = [];
+ for (const c of cl) {
+ const firstYear = yearOf(c.first);
+ if (jan1(firstYear) < c.from) cands.push({ key: `c${firstYear}`, text: String(firstYear), x: X(c.first), tick: false, lead: true });
+ for (let y = yearOf(c.from) + 1; jan1(y) <= c.to; y += 1) cands.push({ key: `t${y}`, text: String(y), x: X(jan1(y)), tick: true });
+ }
+ cands.sort((a, b) => a.x - b.x || (b.lead ? 1 : 0) - (a.lead ? 1 : 0));
+ const years = [];
+ for (const y of cands) if (!years.length || y.x - years[years.length - 1].x >= yearPx) years.push(y);
+ return { lo, hi, clusters: cl, gaps, years, X, Y };
+}
+
+/**
+ * The trail's states: one per moment a point is said (`at`), each with the points shown (`shown`, their `n`), its
+ * layout, each shown point's place (`pos`: n -> {x, y}) and the line's pairs (`pairs`: neighbours by date among the
+ * STATED points shown, `{ key, a, b, gap }`, `gap` when they straddle a break). `bounds: "fixed"` lays every state on
+ * the layout of all the cut's points (the strip as it was, but with its breaks).
+ *
+ * @param {ReturnType<typeof trailPoints>} points
+ */
+export function trailStates(points, box, { gap = "auto", mark = null, bounds = "fit" } = {}) {
+ const thr = gapThreshold(points, gap);
+ const all = bounds === "fixed" ? trailLayout(points, box, { thr, mark }) : null;
+ const times = [...new Set(points.map((p) => p.t))].sort((a, b) => a - b);
+ return times.map((at) => {
+ const shown = points.filter((p) => p.t <= at + 1e-9);
+ const layout = all ?? trailLayout(shown, box, { thr, mark });
+ const pos = new Map(shown.map((p) => [p.n, { x: layout.X(p.day), y: layout.Y(p.value) }]));
+ const stated = shown.filter((p) => p.kind === "stated").sort((a, b) => a.day - b.day || a.t - b.t);
+ const pairs = stated.slice(1).map((b, i) => {
+ const a = stated[i];
+ return { key: `${a.n}_${b.n}`, a: a.n, b: b.n, gap: b.day - a.day > thr };
+ });
+ return { at, shown: shown.map((p) => p.n), layout, pos, pairs, thr };
+ });
+}
diff --git a/umtool/report-to-video/trail-plan.test.mjs b/umtool/report-to-video/trail-plan.test.mjs
@@ -0,0 +1,118 @@
+// THE TRAIL'S PLAN (trail-plan.mjs; chrome-instruments.mjs trailHtml): the by-date chart shows every weight said
+// so far -- stated and remembered -- on axes that fit them and reflow as each lands, its time axis broken across
+// long empty stretches (rev9-a7, 11 Nov: a 2013 dot pinned at the left edge for minutes, 2008 and ≈390 never drawn,
+// one line across a decade to the 2025–26 points squeezed at the right).
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { trailHtml } from "./chrome-instruments.mjs";
+import { estimateSchedule } from "./deck.mjs";
+import { clustersOf, GAP_FLOOR_DAYS, gapThreshold, trailLayout, trailPoints, trailStates } from "./trail-plan.mjs";
+import { dayNumber } from "./measure-draw.mjs";
+import { validateTrail } from "./instruments.mjs";
+
+/** The a7 sequence: a 2013 weigh-in and a second 2013 weight; a remembered ≈390 (as of Feb 2023) above them; a
+ * remembered 368 as of 2008 -- before everything and above the old top; then the dense 2025–26 run. */
+const ev = (t, kind, value, date, extra = {}) => ({ t, kind, value, date, row: `r${t}`, scope: "weight", qualifier: null, asOf: null, ...extra });
+const EVENTS = [
+ ev(9, "stated", 346.7, "2013-03-09"),
+ ev(31, "stated", 342.9, "2013-03-21"),
+ ev(60, "remembered", 390, "2023-09-29", { asOf: "2023-02-24", qualifier: "≈" }),
+ ev(100, "remembered", 368, "2025-01-10", { asOf: "2008-06-30" }),
+ ev(175, "stated", 349, "2025-04-08"),
+ ev(204, "stated", 341, "2025-06-02"),
+ ev(225, "stated", 336, "2025-07-15"),
+ ev(230, "stated", 331.5, "2025-08-01"),
+ ev(280, "stated", 322, "2025-10-08"),
+ ev(293, "stated", 318, "2025-11-20"),
+ ev(320, "stated", 305, "2026-01-16"),
+ ev(324, "stated", 299, "2026-03-02"),
+ ev(337, "stated", 296, "2026-06-01", { qualifier: "≈" }),
+ ev(347, "goal", 250, "2026-07-01"),
+];
+const MEASURE = { unit: "lb", scale: { min: 220, max: 400 }, events: EVENTS, state: [{ t: 0 }], totals: {} };
+const BOX = { x0: 54, x1: 582, y0: 38, y1: 174, gapPx: 22, yearPx: 34 };
+
+test("the trail's points: stated and remembered, each at its own date (asOf first), in the cut's order", () => {
+ const pts = trailPoints(MEASURE);
+ assert.equal(pts.length, 13, "the goal is not a weight");
+ assert.deepEqual(pts.map((p) => p.kind).slice(0, 5), ["stated", "stated", "remembered", "remembered", "stated"]);
+ assert.equal(pts[3].day, dayNumber("2008-06-30"), "a remembered weight stands at the day it was his weight");
+ assert.equal(trailPoints(MEASURE, { remembered: false }).length, 11);
+});
+
+test("at every moment the chart shows exactly the weights said by then, on axes that contain all of them", () => {
+ const pts = trailPoints(MEASURE);
+ const states = trailStates(pts, BOX, { mark: 300 });
+ assert.equal(states.length, 13);
+ for (const st of states) {
+ const shown = pts.filter((p) => p.t <= st.at);
+ assert.equal(st.shown.length, shown.length, `at ${st.at}`);
+ for (const p of shown) {
+ assert.ok(st.layout.lo <= p.value && p.value <= st.layout.hi, `at ${st.at}: ${p.value} inside ${st.layout.lo}–${st.layout.hi}`);
+ const { x, y } = st.pos.get(p.n);
+ assert.ok(x !== null && x >= BOX.x0 && x <= BOX.x1, `at ${st.at}: ${p.value} on the x axis (${x})`);
+ assert.ok(y >= BOX.y0 && y <= BOX.y1, `at ${st.at}: ${p.value} on the y axis (${y})`);
+ }
+ }
+ // The first weigh-in alone: in the middle of the strip, not pinned to its left edge.
+ const one = states[0].pos.get(0).x;
+ assert.ok(one > BOX.x0 + 100 && one < BOX.x1 - 100, `a lone point stands mid-strip (${one})`);
+ // The remembered ≈390 raises the top; the 2008 one moves the start of time back and keeps 390 in.
+ assert.ok(states[1].layout.hi < 390 && states[2].layout.hi >= 390);
+ assert.ok(states[3].pos.get(3).x < states[3].pos.get(0).x, "2008 stands left of 2013");
+ // The axes advance with the story: no 2026 on the axis until a 2026 weight is said.
+ const years = (st) => st.layout.years.map((y) => y.text);
+ assert.ok(!years(states[4]).includes("2026"));
+ assert.ok(years(states.at(-1)).includes("2026"));
+});
+
+test("the gap rule: a stretch longer than a year (or 8× the median spacing) breaks the time axis; the dense run gets the width", () => {
+ const pts = trailPoints(MEASURE);
+ // The median step between the dates here is 57 days: 8× is 456, past the year's floor.
+ assert.equal(gapThreshold(pts), 456);
+ assert.equal(gapThreshold([0, 7, 14, 21, 28].map((day) => ({ day }))), GAP_FLOOR_DAYS, "weekly statements: the year's floor rules");
+ assert.equal(gapThreshold(pts, 540), 540);
+ assert.equal(gapThreshold(pts, 0), Infinity);
+ // Spacing of 100 days: 8× is 800, past the floor.
+ const sparse = [0, 100, 200, 300, 400].map((day) => ({ day }));
+ assert.equal(gapThreshold(sparse), 800);
+ assert.deepEqual(clustersOf([1, 2, 500, 900, 901], 365), [{ first: 1, last: 2 }, { first: 500, last: 500 }, { first: 900, last: 901 }]);
+ const last = trailStates(pts, BOX, { mark: 300 }).at(-1);
+ // 2008 | 2013 | 2023 | 2025–26: three breaks, each a narrow band.
+ assert.equal(last.layout.clusters.length, 4);
+ assert.equal(last.layout.gaps.length, 3);
+ const dense = last.layout.clusters.at(-1);
+ assert.ok(dense.x1 - dense.x0 > 0.5 * (BOX.x1 - BOX.x0), `the 2025–26 run has most of the width (${dense.x1 - dense.x0} px)`);
+ // The line: stated neighbours only -- the remembered never joined -- dotted across a break.
+ const byN = new Map(pts.map((p) => [p.n, p]));
+ for (const pr of last.pairs) assert.ok(byN.get(pr.a).kind === "stated" && byN.get(pr.b).kind === "stated");
+ const across = last.pairs.find((pr) => byN.get(pr.a).value === 342.9);
+ assert.equal(across.gap, true, "2013 to 2025 is a dotted connector, not data");
+ assert.ok(last.pairs.filter((pr) => !pr.gap).length >= 8);
+ // gap: 0 -- one cluster, no breaks.
+ assert.equal(trailStates(pts, BOX, { gap: 0, mark: 300 }).at(-1).layout.gaps.length, 0);
+ // bounds: "fixed" -- every moment on the whole cut's axes.
+ const fixed = trailStates(pts, BOX, { bounds: "fixed", mark: 300 });
+ assert.equal(fixed[0].layout.hi, fixed.at(-1).layout.hi);
+});
+
+test("the page: points pop in where their moment puts them and move with every reflow, seek-safe; the knobs validate", () => {
+ const timeline = Array.from({ length: 4 }, (_, i) => ({ type: "clip", id: `c${i + 1}`, video: "v", start: 0, end: 100 }));
+ const render = { width: 1920, height: 1080, fps: 30, transition: 0.4, palette: { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" },
+ chrome: { engine: "hyperframes", layout: "deck", deck: { dial: true, odometer: true, trail: true } } };
+ const schedule = { ...estimateSchedule({ slug: "m", title: "M", provenance: {}, render, timeline }), measure: MEASURE };
+ const html = trailHtml(schedule, render, { fonts: {} });
+ const data = JSON.parse(/<script id="trail-data" type="application\/json">(.*?)<\/script>/s.exec(html)[1]);
+ assert.match(html, /class="pt rem q" data-k="p2"/, "the remembered ≈390: hollow, grey, its qualifier dashed");
+ assert.match(html, /class="seg gap" data-k="s1_4"/, "2013 → 2025 dotted");
+ assert.ok(!/data-k="s\d+_2"|data-k="s2_\d+"/.test(html), "the remembered are never joined");
+ // p0 (the 2013 weigh-in) moves when the 2013 second weight lands, and again when 2008 pushes time back.
+ const moves = data.cues.filter((c) => c.k === "p0" && "x" in c.to).map((c) => c.at);
+ assert.ok(moves.includes(31) && moves.includes(100), `p0 reflows at 31 and 100 (${moves})`);
+ // Every cue states its from (seek-safe), and nothing changes at 0 that frame 0 cannot show.
+ assert.ok(data.cues.every((c) => Object.keys(c.to).every((k) => k in c.from)));
+ assert.deepEqual(validateTrail({ bounds: "fixed", remembered: false, gap: 540 }), []);
+ assert.match(validateTrail({ gap: 10 }).join(), /gap must be "auto", 0 \(no breaks\) or 30 to 3650 days/);
+ assert.match(validateTrail({ bounds: "loose" }).join(), /bounds must be "fit" or "fixed"/);
+});
diff --git a/umtool/report-to-video/update-flash.mjs b/umtool/report-to-video/update-flash.mjs
@@ -0,0 +1,84 @@
+// THE UPDATE FLASH (operator, 11 Nov: "whenever a widget gets updated, have it
+// show a subtle border flash or something to indicate that at a glance"): at
+// the moment a measure widget's shown value changes, a thin outline just inside
+// its edge lights over FLASH_MOTION.up and decays over FLASH_MOTION.down, in the
+// widget's own colour -- no size change, no layout shift. Widgets that change on
+// the same event flash together (each reads the same event times).
+//
+// What counts as a change, per widget (each page picks its own times):
+// the dial a new stated weight, a remembered one, a goal in force changing
+// the odometer the pounds lost going up (or its runs), NET changing
+// the trail each weight landing on the chart
+// the diet a new diet (a new front tag) -- never the running day count
+// the goals a goal set (a note landing) -- not the board's own changes
+// Never on frame 0, never while the deck is away (the intro, a card, the
+// finale's hand-over), never on a widget's first appearance (its own entrance
+// marks that) unless it is the dial, which stands from the start.
+//
+// OFF by default: `render.chrome.deck.measure.flash: true` turns it on for
+// every widget; a widget's own `flash` (true/false) overrides that for it.
+import { deckChoreography } from "./deck.mjs";
+
+/** Seconds: the outline's rise and its decay. */
+export const FLASH_MOTION = Object.freeze({ up: 0.15, down: 0.7 });
+
+/** Is the flash on for a widget: its own `flash` when it says, else `deck.measure.flash`. */
+export function flashOn(render, own = null) {
+ if (typeof own === "boolean") return own;
+ return render?.chrome?.deck?.measure?.flash === true;
+}
+
+/** The spans the deck is away (deckChoreography's visibility): `[{ from, to }]`, `to` Infinity when it stays away. */
+export function deckAwaySpans(schedule, render) {
+ let vis = [];
+ try {
+ vis = deckChoreography(schedule, render).visibility;
+ } catch {
+ return [];
+ }
+ const out = [];
+ let open = null;
+ for (const v of [...vis].sort((a, b) => a.at[0] - b.at[0])) {
+ if (v.hide && open === null) open = v.at[0];
+ else if (!v.hide && open !== null) { out.push({ from: open, to: v.at[1] }); open = null; }
+ }
+ if (open !== null) out.push({ from: open, to: Infinity });
+ return out;
+}
+
+/**
+ * The moments a widget flashes: its change `times`, sorted, one per 0.05 s, none before frame 1 and none while the
+ * deck is away (`away`, deckAwaySpans).
+ */
+export function flashTimes(times, { fps = 30, away = [] } = {}) {
+ const frame = 1 / (Number(fps) > 0 ? Number(fps) : 30);
+ const out = [];
+ for (const t of [...times].filter(Number.isFinite).sort((a, b) => a - b)) {
+ if (t < frame - 1e-9) continue;
+ if (away.some((s) => t >= s.from - 1e-6 && t < s.to)) continue;
+ if (out.length && t - out[out.length - 1] < 0.05) continue;
+ out.push(t);
+ }
+ return out;
+}
+
+/** The outline's cue events (compileCues / cueList shape): up, then down, at each time. */
+export function flashEvents(k, times) {
+ const { up, down } = FLASH_MOTION;
+ return times.flatMap((t) => [
+ { k, at: t, dur: up, to: { opacity: 1 }, ease: "power1.out" },
+ { k, at: t + up, dur: down, to: { opacity: 0 }, ease: "power2.out" },
+ ]);
+}
+
+/** A cueList's adds for the outline `k` (its init: hidden). */
+export function flashCues(L, k, times) {
+ L.set(k, { opacity: 0 });
+ for (const e of flashEvents(k, times)) L.add(e.k, e.at, e.dur, e.to, e.ease);
+}
+
+/** The outline's look: a thin line in `color` just inside the box (`inset` negative: just outside), a soft glow; `radius` its corners (CSS). */
+export function flashCss(sel, color, { radius = "0px", width = 2, inset = "0px" } = {}) {
+ return `${sel} { position: absolute; inset: ${inset}; border-radius: ${radius}; border: ${width}px solid ${color};
+ box-shadow: 0 0 ${width * 5}px ${color}, inset 0 0 ${width * 3}px ${color}; opacity: 0; pointer-events: none; }`;
+}
diff --git a/umtool/report-to-video/update-flash.test.mjs b/umtool/report-to-video/update-flash.test.mjs
@@ -0,0 +1,130 @@
+// THE UPDATE FLASH (update-flash.mjs; operator, 11 Nov): a measure widget's outline lights at the moment its
+// shown value changes -- exactly that widget, exactly then -- and never on frame 0, over the intro, or on a widget's
+// first appearance. Off by default: a cut renders as it did.
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { estimateSchedule } from "./deck.mjs";
+import { dialHtml, odometerHtml, trailHtml } from "./chrome-instruments.mjs";
+import { dietHtml, goalsHtml, shelfGoalStates } from "./chrome-measure-extras.mjs";
+import { dietStates, goalStates } from "./measure-extras.mjs";
+import { measureTrack } from "./measure-draw.mjs";
+import { validateMeasureSettings } from "./measure-slice.mjs";
+import { validateDial } from "./instruments.mjs";
+import { validateMeasureExtra } from "./modules/measure-extras-settings.mjs";
+import { trailPoints } from "./trail-plan.mjs";
+import { FLASH_MOTION, flashOn, flashTimes } from "./update-flash.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const DIAL = JSON.parse(readFileSync(path.join(HERE, "fixtures", "measure-dial", "measure.json"), "utf8"));
+const EXTRAS = JSON.parse(readFileSync(path.join(HERE, "fixtures", "measure-extras", "measure.json"), "utf8"));
+const FPS = 30;
+const PALETTE = { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" };
+const deckOf = (deck) => ({ width: 1920, height: 1080, fps: FPS, transition: 0.4, palette: PALETTE, chrome: { engine: "hyperframes", layout: "deck", deck } });
+const INSTR = { dial: true, odometer: true, trail: true, qr: { show: false }, finale: { video: "side", totals: false } };
+const ON = deckOf({ ...INSTR, measure: { flash: true } });
+const OFF = deckOf(INSTR);
+
+/** The instruments' fixture cut: 9 clips, the last the finale -- optionally opening on the intro. */
+function cut(render, { intro = false } = {}) {
+ const timeline = Array.from({ length: 9 }, (_, i) => ({
+ type: "clip", id: `c${i + 1}`, video: "vidx", start: 10 * i, end: 10 * i + (i === 8 ? 14 : 8), cite: 1, section: 0,
+ quote: "q", onscreen: { title: `Clip ${i + 1}` }, ...(i === 8 ? { layout: "finale" } : {}),
+ }));
+ if (intro) timeline.unshift({ type: "intro", id: "brand-intro", style: "boot-dark", seconds: 4.75, heading: "Intro" });
+ return { ...estimateSchedule({ slug: "m", title: "M", provenance: {}, render, timeline }), measure: DIAL };
+}
+const dataOf = (html, id) => JSON.parse(new RegExp(`<script id="${id}-data" type="application/json">(.*?)</script>`, "s").exec(html)[1]);
+/** The moments an outline `k` lights: its rising cues. */
+const lit = (data, k = "fl") => data.cues.filter((c) => c.k === k && c.to.opacity === 1).map((c) => c.at);
+const near = (a, b) => a.length === b.length && a.every((x, i) => Math.abs(x - b[i]) < 0.02);
+
+test("off by default: no outline on any widget, and the pages are the pages they were", () => {
+ const s = cut(OFF);
+ for (const [id, html] of [["dial", dialHtml(s, OFF, {})], ["odometer", odometerHtml(s, OFF, {})], ["trail", trailHtml(s, OFF, {})]]) {
+ assert.doesNotMatch(html, /data-k="fl"/, id);
+ assert.equal(lit(dataOf(html, id)).length, 0, id);
+ }
+ assert.equal(flashOn(OFF), false);
+ assert.equal(flashOn(ON), true);
+ assert.equal(flashOn(ON, false), false, "a widget's own false beats the measure's true");
+ assert.equal(flashOn(OFF, true), true);
+});
+
+test("a value change at t lights exactly the widget whose value changed, at t -- and nothing else does", () => {
+ const s = cut(ON);
+ const track = measureTrack(DIAL);
+ const frame = 1 / FPS;
+ const want = (times) => flashTimes(times, { fps: FPS });
+ const dialT = want([...track.current.slice(1), ...track.remembered, ...track.goals.slice(1)].map((x) => x.t));
+ const odoT = want([...track.lost.slice(1), ...track.net.slice(1)].map((x) => x.t));
+ const trailT = want(trailPoints(DIAL).map((p) => p.t));
+ const got = { dial: lit(dataOf(dialHtml(s, ON, {}), "dial")), odometer: lit(dataOf(odometerHtml(s, ON, {}), "odometer")), trail: lit(dataOf(trailHtml(s, ON, {}), "trail")) };
+ assert.ok(near(got.dial, dialT), `dial ${got.dial} vs ${dialT}`);
+ assert.ok(near(got.odometer, odoT), `odometer ${got.odometer} vs ${odoT}`);
+ assert.ok(near(got.trail, trailT), `trail ${got.trail} vs ${trailT}`);
+ assert.ok(got.dial.length && got.odometer.length && got.trail.length);
+ // A moment only the odometer changes at (a loss claim, no weight stated): the odometer lights, the dial does not.
+ const onlyOdo = odoT.find((t) => !dialT.some((d) => Math.abs(d - t) < 0.02) && !trailT.some((d) => Math.abs(d - t) < 0.02));
+ assert.ok(onlyOdo !== undefined, "the fixture has a loss claim with no weight stated with it");
+ assert.ok(!got.dial.some((t) => Math.abs(t - onlyOdo) < 0.02));
+ // A stated weight lights the dial and the trail together, at the same instant.
+ const both = dialT.find((t) => trailT.some((d) => Math.abs(d - t) < 0.02));
+ assert.ok(both !== undefined && got.trail.some((t) => Math.abs(t - both) < 0.02));
+ // Up over 0.15 s, down over 0.7 s; never before frame 1.
+ const d = dataOf(dialHtml(s, ON, {}), "dial");
+ const up = d.cues.find((c) => c.k === "fl" && c.to.opacity === 1);
+ const down = d.cues.find((c) => c.k === "fl" && c.to.opacity === 0);
+ assert.equal(up.dur, FLASH_MOTION.up);
+ assert.equal(down.dur, FLASH_MOTION.down);
+ assert.ok(Object.values(got).flat().every((t) => t >= frame));
+ assert.deepEqual(d.init.fl, { opacity: 0 }, "dark on frame 0");
+});
+
+test("never over the intro: a change said while the deck is away does not light anything", () => {
+ const s = cut(ON, { intro: true });
+ const introEnd = s.segments[1].start;
+ for (const [id, html] of [["dial", dialHtml(s, ON, {})], ["odometer", odometerHtml(s, ON, {})], ["trail", trailHtml(s, ON, {})]]) {
+ const times = lit(dataOf(html, id));
+ assert.ok(times.every((t) => t >= introEnd), `${id}: ${times} after ${introEnd}`);
+ }
+ // The fixture's changes at 2 and 3.75 s fall inside the 4.75 s intro: they are dropped, not moved.
+ assert.ok(!lit(dataOf(dialHtml(s, ON, {}), "dial")).some((t) => t < introEnd));
+});
+
+test("the goal stack and the diet tags: a goal set / a new diet lights the card that lands -- never the first", () => {
+ const FAN = { dial: true, odometer: true, trail: true, shelf: { items: ["diet", "goals"] }, diet: { position: "shelf", form: "tags", overlap: 0.6, days: true }, goals: { position: "shelf" }, streak: false, measure: { flash: true } };
+ const r = deckOf(FAN);
+ const sched = { kind: "deck", fps: FPS, total: 740, transition: 0.4, segments: [{ id: "a", start: 0, duration: 740, end: 740 }], measure: EXTRAS };
+ const shelf = shelfGoalStates(sched, goalStates(sched, r));
+ const g = dataOf(goalsHtml(sched, r, { fonts: {} }).html, "goals");
+ const gLit = g.cues.filter((c) => /\.fl$/.test(c.k) && c.to.opacity === 1);
+ const wantG = shelf.filter((st, j) => j > 0 && st.top).map((st) => st.at);
+ assert.ok(near(gLit.map((c) => c.at), wantG), `goals ${gLit.map((c) => c.at)} vs ${wantG}`);
+ assert.ok(!gLit.some((c) => c.k.startsWith("s0.")), "the first goal is the stack's entrance");
+ // A board-only change (met, missed) is not a goal set: no outline.
+ assert.ok(shelf.some((st) => !st.top), "the fixture's board changes on its own") ;
+ const states = dietStates(sched, r);
+ const d = dataOf(dietHtml(sched, r, { fonts: {} }).html, "diet");
+ const dLit = d.cues.filter((c) => /\.fl$/.test(c.k) && c.to.opacity === 1).map((c) => c.at);
+ const wantD = states.filter((st, j) => j > 0 && st.tags[0]?.id !== states[j - 1].tags[0]?.id).map((st) => st.at);
+ assert.ok(near(dLit, wantD), `diet ${dLit} vs ${wantD}`);
+ // The running day count changes far more often than the diet: it never lights the tag.
+ assert.ok(dLit.length < d.cues.filter((c) => /\.y\d+$/.test(c.k)).length);
+ // Off: nothing.
+ const off = deckOf({ ...FAN, measure: undefined });
+ assert.doesNotMatch(goalsHtml(sched, off, { fonts: {} }).html, /class="fl"/);
+ assert.doesNotMatch(dietHtml(sched, off, { fonts: {} }).html, /class="fl"/);
+});
+
+test("the knobs: deck.measure.flash and each widget's own flash validate", () => {
+ assert.deepEqual(validateMeasureSettings({ flash: true }), []);
+ assert.match(validateMeasureSettings({ flash: "on" }).join(), /measure\.flash must be true or false/);
+ assert.deepEqual(validateDial({ flash: false }), []);
+ assert.match(validateDial({ flash: 1 }).join(), /dial\.flash must be true or false/);
+ assert.deepEqual(validateMeasureExtra("goals", { flash: true }), []);
+ assert.match(validateMeasureExtra("diet", { flash: "x" }).join(), /flash must be true, false or null/);
+});
diff --git a/umtool/report-to-video/vertical-deck.test.mjs b/umtool/report-to-video/vertical-deck.test.mjs
@@ -266,7 +266,10 @@ const MAIN = {
deck: "546848c82d65e45e4d1a4ac4c7a9c3c8",
dial: "f7e21e4a3622703975f746d39cbcb738",
odometer: "8425983d217408dddcb6ee794881c6c4",
- trail: "3512192be69f8b9bc33aec6e7b41a088",
+ // Re-pinned on lane/frame-zero (11 Nov): the trail's axes fit the weights said so far and reflow, its remembered
+ // weights are points, its time axis breaks over long empty stretches (trail-plan.mjs) -- the page is new by design.
+ // Main's was 3512192be69f8b9bc33aec6e7b41a088.
+ trail: "39c3694f4e26963277d9b22ebfd0f60b",
dialFinale: "52866e4d87e15bd55afe8c1a703414a3",
geometry: "182959796c281f769766df3d02962904",
bare: "7ce1f7a66452adec21575bcdbba900f1",