Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 333785d02676ed2318bbf85930b196de310c1106
parent 80b83aaaa21802969e38e983add2494942aa259a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri,  6 Nov 2026 02:03:06 -0500

Merge lane/rev9-fixes (first six): the measure modules dodge post cards and chapter bands by the real card layout; the promise clock's PAID/AS OF dates; a post item's `excerpt` (verbatim spans read, the rest shown dimmed); a beeped slur's word timing never blocks on a held lane; `umtool look chrome.layout=deck` and `--unset render.<legacy key>`; a project's shadow channels fall back to the corpus (operator, 5 Nov: "all modules", "Involve MadamSavvy as a character")

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/docs/cli.md | 4++--
Mumtool/docs/knobs.md | 6++++++
Mumtool/docs/report-video.md | 14++++++++++++++
Mumtool/lib/projects/report.mjs | 30+++++++++++++++++++++++++++---
Mumtool/lib/report/knobsCli.mjs | 42++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/knobsCli.test.mjs | 31+++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Aumtool/lib/report/postExcerpt.test.mjs | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postNarrationCli.mjs | 61++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mumtool/lib/report/postReel.mjs | 26++++++++++++++++++--------
Mumtool/lib/report/postSlurs.test.mjs | 44++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postsCli.mjs | 22++++++++++++++++++++--
Mumtool/report-to-video/build-video.mjs | 26+++++++++++++++++++-------
Aumtool/report-to-video/channels-layers.test.mjs | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/chrome-measure-extras.mjs | 92++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mumtool/report-to-video/chrome-story.mjs | 17++++++++++++++++-
Mumtool/report-to-video/cues.mjs | 44+++++++++++++++++++++++++++++++++++---------
Mumtool/report-to-video/deck.mjs | 31++++++++++++++++++++++++++++++-
Mumtool/report-to-video/measure-extras.mjs | 196+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/report-to-video/measure-extras.test.mjs | 96++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/report-to-video/modules/measure-extras-module.mjs | 17+++++++++++++----
Mumtool/report-to-video/modules/measure-extras-settings.mjs | 12+++++++++++-
Mumtool/report-to-video/narrate-via-editor.mjs | 14+++++++++++++-
Mumtool/report-to-video/post-item.mjs | 93++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/report-to-video/post-narration.mjs | 9+++++----
Mumtool/report-to-video/sources.mjs | 80++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
26 files changed, 1169 insertions(+), 88 deletions(-)

diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -34,7 +34,7 @@ Inbox cannot disagree about what is wrong with one. | `walk <project> [--take <take>] [--all] [--json]` | the clip bench's **walk**: every clip in walk order with its window, verdict and whether a fetched file holds it, and (→) the ones the walk visits — fetched and needing a verdict; `--all` every fetched one; `--take` walks a take (a draft too); the bench's address to start at | | `link <project> <site>/<report>` · `link <project> --clear` | the manifest names the article it is the video of (settles `link-ambiguous`) | | `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); `key=` clears one ([knobs.md](knobs.md#marks)) | -| `look <project> key=value …` | the cut's **knobs**: `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys ([knobs.md](knobs.md)) | +| `look <project> key=value … [--unset render.<key>]…` | the cut's **knobs**: `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2** | | `variants <project> [--take <t>] [--list] [--json]` | **Make variants**: the encode ladder of the build (or of a take's); `--list` what was made and the build's sync report, each clip's lag (past a frame flagged) ([knobs.md](knobs.md)) | | `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain | | `build <project> --run [--url URL] [--replace] [--preset P] [--only ID] [--skip-fetch]` | **runs** it as the app's build job (POST `/api/report/build` on `--url`, else `UMTOOL_URL`, else `http://localhost:3050`), prints its log as it grows, **Ctrl-C** cancels the job (twice leaves it running); `--replace` stamps a deliverable newer than the manifest aside; exit 1 unless the job is done (release 36) | @@ -101,7 +101,7 @@ Inbox cannot disagree about what is wrong with one. | `posts progress <project> [auto\|on\|off\|default] [--json]` | the cut's **progress bar** default (`render.posts.progress`, `updatePostProgressRender`; [report-video.md](report-video.md#the-progress-bar)); bare, which items draw it | | `timeline <project> threads [--json]` · `timeline <project> threads --write [--conversation <id>]` | **the cut's conversations** ([report-video.md](report-video.md#thread-reads), `post-conversation.mjs`): each tree of two post items or more — its root, its items' places, whether they play as one run (one scene) or are split by other entries, a reply placed before the post it answers, an item re-reading a post its run already read (with `posts set-item <p> <item> thread.parent.<i>=context`). `--write` gathers each (or the one holding `<id>`: its root, a post, an item, a `thread.group` name) at its first item's place in TREE order (a manual thread: in DATE order) — a post after what it answers, sibling branches by date, each depth first — in ONE write (one undo point); never across a section boundary (gathered within each section, and said) | | `posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**) | -| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--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= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said "at <handle>", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) | +| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--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= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said "at <handle>", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans. | | `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** | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -708,6 +708,7 @@ background jumped at the cut. A segment built full range before the pin is rebui |---|---|---|---| | `hold` — the item's whole length in seconds (1–120; absent: the pacing rule, the item is its read) | post bench, **hold** | `umtool posts set-item <p> <item> hold=12` (`hold=off`) | `POST /api/report/post-item {project, op: "set", id, patch: {hold}, token}` | | `mediaLayout` — `grid`: its 2-4 images at once (one picture of the read); absent: one after another, cycling | post bench, **images** | `layout=grid` (`layout=sequence`) | same, `patch: {mediaLayout}` | +| `excerpt` — a long post READ IN PART: one or more verbatim spans of its words (1–8, each found in the text after the one before it; refused otherwise). The read is the spans joined with " … " (a narrated item's script is redrafted from it when it is set or cleared, so the next `posts narrate <p> <item> --take` reads it; `posts narrate --all --draft-scripts` drafts from it; an un-narrated item's reading time counts its words); the card still shows the WHOLE post, the words it does not read dimmed (`.xcut`, 38 %) -- it never hides that text was cut. Absent: the whole post | -- | `umtool posts set-item <p> <item> excerpt='["I bought your shitty coffee.","I look forward to you felting me"]'` (`excerpt=off`) | same, `patch: {excerpt}` | | `redact` — other authors (the posts it answers, the one it quotes, a repost's original): absent, the privacy rule (blurred unless a subject or gold/grey verified); `false` shows them (judged public); `true` blurs even the verified | post bench, **other authors** | `redact=off` · `redact=on` · `redact=auto` | same, `patch: {redact}` | | `quoted.paraphrase`, `parents[i].paraphrase` — your short retelling (≤ 600 characters) of a long context post (the post it quotes, the posts it answers, nearest first): the card (render, Play, the bench, the recording page) draws it in place of that post's words, in the same style, with a small **paraphrased** label beside its date; its read counts the paraphrase's words; the author stays under the blur rule; its `text` is never touched. Absent or empty: its own words | post bench, the context block's **Paraphrase** (its words shown above it; **clear**), then **Save** | `quoted.paraphrase="He reviewed three of the videos."` · `parent.0.paraphrase="…"` (`=off`) | same, `patch: {quoted: {paraphrase}, parents: {"0": {paraphrase}}}` | | `media[i].start`, `media[i].end` — a video's or a GIF's in and out, its own seconds (at least 0.5 s apart) | post bench, **in / out**, **In at playhead**, **Out at playhead**, **Whole**; or the attachment's LANE (one per video or GIF, under the player): its whole length as a waveform (a flat line for a GIF or a silent video), the in and out its two handles (drag one, or click near it; never closer than 0.5 s, never past the file), the part the item plays dashed, the playhead; the bench's clock follows a moving edge, so the player shows its frame. Focused: `[` `]` the in, `,` `.` the out (0.05 s; Shift 0.5 s), `←` `→` the edge last moved (0.1 s; Shift 1 s). The number fields follow at once; **Save** writes them (the take's patch on `?inTake=<t>`) | `media.0.start=1.5 media.0.end=6` · `media.0.trim=off` | same, `patch: {media: {"0": {start, end}}}` | @@ -1749,6 +1750,7 @@ A chain per run along a time axis by in-record date (`render.chrome.deck.streak` | `deck.streak.position`, `.x`/`.y`, `.scale` | an anchor in the footage box · design px · 0.5–2 · default `bottom-center`, unset, 1 | `umtool look <p> deck.streak.position=bottom-left` | | `deck.streak.hold`, `.finale` | 0 (up from the first run on) or 2–600 s · `hide` `show` · default 0, `hide` | `umtool look <p> deck.streak.hold=15` | | `deck.streak.title`, `.color`, `.colors`, `.labels` | ≤40 · #hex · `{<regime>: #hex}` · `{<regime>: words}` · default the source's word, the accent, the regimes' inks and names | `umtool look <p> deck.streak.title='Every diet'` | +| `deck.streak.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.streak.onPosts=hide` | ### Diet badge @@ -1760,6 +1762,7 @@ The diet he names as a rubber stamp in a corner of the footage box (`render.chro | `deck.diet.position`, `.x`/`.y`, `.scale` | an anchor in the footage box · design px · 0.5–2 · default `bottom-left`, unset, 1 | `umtool look <p> deck.diet.position=top-right` | | `deck.diet.hold`, `.finale` | 0 (up from the first diet on) or 2–600 s · `hide` `show` · default 0, `hide` | `umtool look <p> deck.diet.hold=15` | | `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.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` | ### Moving start @@ -1771,6 +1774,7 @@ The weight he says he started at, as he retells it (`render.chrome.deck.peak`, m | `deck.peak.position`, `.x`/`.y`, `.scale` | an anchor in the footage box · design px · 0.5–2 · default `top-right`, unset, 1 | `umtool look <p> deck.peak.scale=0.9` | | `deck.peak.hold`, `.finale` | 0 (stays up) or 2–600 s · `hide` `show` · default 12, `hide` | `umtool look <p> deck.peak.hold=0` | | `deck.peak.title`, `.values`, `.color` | ≤40 · `drift` `all` · #hex · default "The start keeps moving", `drift`, #FF5A4E | `umtool look <p> deck.peak.values=all` | +| `deck.peak.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.peak.onPosts=hide` | ### Goal stack @@ -1782,6 +1786,7 @@ A sticky note per goal on a pile in a corner of the footage box, read off the sc | `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.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.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.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` | ### Thread rail @@ -1876,5 +1881,6 @@ A days-since counter for a promise (`render.chrome.deck.promise`, measure-extras | `deck.promise.hold`, `.finale` | 0 (stays up) or 2–600 s · `hide` `show` · default 0, `show` | `umtool look <p> deck.promise.finale=hide` | | `deck.promise.label`, `.verb`, `.kept`, `.broken`, `.checks` | ≤40 each · `label` `quote` · default the row's display, "offered", "Posted", "None posted", `label` | `umtool look <p> deck.promise.label='scale video'` | | `deck.promise.speakers`, `.claimVerb`, `.claimColor` | `{<speaker>: {handle, color}}` · ≤40 · #hex · default `{}` (the postAvatars handle), "paid", #E37AB8 | `umtool look <p> deck.promise.speakers='{"madamsavvy":{"handle":"MadamSavvy"}}'` | +| `deck.promise.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.promise.onPosts=hide` | <!-- modules:end --> diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1866,6 +1866,20 @@ preference: cut the same moment from a live mirror (via a `CHANNELS_DIR` shadow directory — but check the archive's alignment statement first, because mirrors are not assumed to share a clock), or convert the clip to a quote card. +### A project's own channels tree, and the corpus behind it + +A project that names its own channels tree (`provenance.channelsDir`, or a +`.shadow-channels/` beside its manifest, which `make-shadow-channels.sh` builds) reads +it FIRST -- and the real corpus (`transcripts/channels`, `CHANNELS_DIR`) for anything +the tree lacks: a channel's posts archive (post items: `timeline insert post:…`, +`posts reel`, `posts add`), a clip's `transcript.cues.json` (umtool's checks, the +bench, the build's cue source) and a cached window (the build's corpus tier, the clip +bench). So a shadow made before a channel was added to the corpus no longer needs that +channel copied into it. Each kind that falls back says so once per run +(`posts: … read from …`, `cues: …`, `windows: …`). `provenance.channelsFallback: false` +(or `CHANNELS_FALLBACK=0` in the environment) turns the fallback off: the shadow alone, +as before (sources.mjs `channelsLayersFor`). + ## The ledger, and why it must be adjudicated `ledger[]` is the claim set the rail and the closing cards read. Beside the diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -7,11 +7,15 @@ // and neither parses JSON. import { postItemSeconds } from "umtool-report-to-video/post-item"; import { readdir, readFile, stat } from "node:fs/promises"; +import { existsSync } from "node:fs"; import path from "node:path"; import { DEFAULT_VARIANT, cachedWindowsFor, fetchSpans } from "umtool-report-to-video/build-video"; import { SHADOW_CHANNELS as SOURCES_SHADOW_CHANNELS, channelsDirFor as sourcesChannelsDirFor, + channelsFallbackOn, + channelsLayersFor as sourcesChannelsLayersFor, + noteChannelsFallback, corpusWindowsOf, ffprobeSource, } from "umtool-report-to-video/sources"; @@ -90,6 +94,15 @@ export function channelsDirFor(dir, manifest, { shadowExists = false } = {}) { return sourcesChannelsDirFor(dir, manifest, { shadowExists, fallback: GLOBAL_CHANNELS_DIR() }); } +/** + * The channels trees this project reads, in order (sources.mjs channelsLayersFor): + * its own (channelsDirFor) and the global corpus behind it, unless the fallback + * is off (`provenance.channelsFallback: false`, CHANNELS_FALLBACK=0). + */ +export function channelsLayersFor(dir, manifest, { shadowExists = false } = {}) { + return sourcesChannelsLayersFor(dir, manifest, { shadowExists, fallback: GLOBAL_CHANNELS_DIR() }); +} + export const hasShadowChannels = (dir) => stat(path.join(dir, SHADOW_CHANNELS)).then((s) => s.isDirectory(), () => false); @@ -558,7 +571,9 @@ export const clipWindowDirs = async ( if (Number.isFinite(duration) && duration > 0) return { duration }; return file ? probeContainer(file) : null; }; - const windows = (await corpusWindowsOf({ video: e.video, slug: chan, channelsDir: root, probe })).filter((w) => + // The corpus behind the project's channels tree, for a video its tree has no window of (channelsLayersFor). + const behind = channelsDir && channelsFallbackOn(m) && path.resolve(GLOBAL_CHANNELS_DIR()) !== path.resolve(root) ? GLOBAL_CHANNELS_DIR() : null; + const windows = (await corpusWindowsOf({ video: e.video, slug: chan, channelsDir: root, probe, fallbackChannelsDir: behind })).filter((w) => readable(w.path), ); if (windows.length) out.push({ video: e.video, windows }); @@ -601,13 +616,22 @@ export async function noCuesFix(m, e, file) { return `Build it: pnpm ops build-cues --json '${json}' --wait`; } -export const cuePathFor = (m, e, channelsDir) => { +export const cuePathFor = (m, e, channelsDir, fallbackChannelsDir = channelsDir && channelsFallbackOn(m) ? GLOBAL_CHANNELS_DIR() : null) => { const chan = channelFor(m, e); // A clip with its own media (`src`, `cues`) names no corpus video: there is // no cue file to find, and path.join(undefined) would throw. if (!chan || e.video == null) return null; // The record's directory: a Twitch v<n> is data/<n>/ (release 23 F1b). - return path.join(resolveVideoDirSync(channelsDir ?? GLOBAL_CHANNELS_DIR(), chan, e.video), "transcript.cues.json"); + const own = path.join(resolveVideoDirSync(channelsDir ?? GLOBAL_CHANNELS_DIR(), chan, e.video), "transcript.cues.json"); + // The corpus behind the project's channels tree (channelsLayersFor), when its own has no cue file for it. + if (fallbackChannelsDir && path.resolve(fallbackChannelsDir) !== path.resolve(channelsDir ?? GLOBAL_CHANNELS_DIR()) && !existsSync(own)) { + const behind = path.join(resolveVideoDirSync(fallbackChannelsDir, chan, e.video), "transcript.cues.json"); + if (existsSync(behind)) { + noteChannelsFallback("cues", `cues: ${chan}/${e.video} has no transcript.cues.json under ${channelsDir} -- read from ${fallbackChannelsDir} (the corpus behind the project's channels tree)`); + return behind; + } + } + return own; }; // --------------------------------------------------------------------------- diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs @@ -28,6 +28,7 @@ import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { FX_ENTRY_FIELDS, + LEGACY_RENDER_KEYS, LOOK_KEYS, manifestToken, updateClaimKnobs, @@ -37,6 +38,7 @@ import { updateFactcheck, updateMarks, updateRender, + updateRenderKeys, updateVariants, } from "./manifest.mjs"; import { CLAIM_KNOBS, STAMP_KNOB_DEFAULTS, VARIANTS_DEFAULT, rawMarksOf, stampingEntryId, variantsOf } from "./knobs.mjs"; @@ -106,7 +108,10 @@ export const SET_USAGE = [ ].join("\n"); export const LOOK_USAGE = [ - "usage: umtool look <project> key=value … [--json]", + "usage: umtool look <project> key=value … [--unset render.<key>]… [--json]", + " chrome.layout=deck: the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck)", + " --unset render.<key>: drop a legacy render key (rail chromeEngine railEngine chromeRegions claimSchedule wordmark", + " title finale cut) -- with chrome.layout=deck in ONE write (the deck refuses the old rail beside it), an undo point first", " factcheck.stamp.scale (0.5–2) .motion (slam|pop|fade|none) .opacity (0.3–1) .seconds .show .position", " factcheck.verdicts.<VERDICT>.stampLabel | .tallyLabel | .label | .color", " factcheck.tally.showAt (always|first: a cell hidden until its first count lands, then popped in;", @@ -169,6 +174,10 @@ const splitArgs = (args) => { if (a === "--take" || a === "--mark") { flags.set(a, args[i + 1] ?? ""); i += 1; + } else if (a === "--unset") { + // Repeatable: every legacy render key named (`--unset render.rail --unset render.title`). + flags.set(a, [...(flags.get(a) ?? []), args[i + 1] ?? ""]); + i += 1; } else if (a.startsWith("--")) flags.set(a, true); else words.push(a); } @@ -414,12 +423,41 @@ export async function lookCommand(args, { root = REPORTS_ROOT, out = (s) => cons const json = flags.has("--json"); try { const [projectArg, ...rest] = words; - if (!projectArg || !rest.length || flags.has("--help")) { + if (!projectArg || (!rest.length && !flags.has("--unset")) || flags.has("--help")) { err(LOOK_USAGE); return 2; } const project = await projectOf(projectArg, root); const pairs = parseAssignments(rest); + // THE DECK ON, LEGACY KEYS OFF (updateRenderKeys): `chrome.layout=deck` (render.chrome created when the cut has + // none) and `--unset render.<key>`, in one write with an undo point -- before any deck.* key, which needs the chrome. + const chromeOn = pairs.filter(([k]) => k === "chrome.layout" || k === "chrome.engine"); + const unsetArgs = flags.get("--unset") ?? []; + if (chromeOn.length || unsetArgs.length) { + const unset = unsetArgs.map((u) => { + const m = /^render\.([A-Za-z]+)$/.exec(String(u)); + if (!m) throw new CliError(`--unset takes render.<key> (one of ${LEGACY_RENDER_KEYS.map((k) => `render.${k}`).join(", ")}): not "${u}"`); + if (!LEGACY_RENDER_KEYS.includes(m[1])) throw new CliError(`--unset takes the legacy render keys only (${LEGACY_RENDER_KEYS.join(", ")}): not ${m[1]}`); + return m[1]; + }); + const chrome = chromeOn.length ? Object.fromEntries(chromeOn.map(([k, v]) => [k.slice("chrome.".length), v])) : null; + const token = await manifestToken(project.dir); + const { result, editNotes } = await withEditNotes(project, () => updateRenderKeys(project.dir, { unset, chrome }, { token })); + const msg = [ + ...(result.unset.length ? [`unset ${result.unset.map((k) => `render.${k}`).join(", ")}`] : []), + ...(result.absent.length ? [`(not set: ${result.absent.map((k) => `render.${k}`).join(", ")})`] : []), + ...(chrome ? [`chrome.layout: ${result.chrome?.layout}${result.created ? " (render.chrome created: engine hyperframes, an empty deck)" : ""}`] : []), + ...(result.snapshot?.rel ? [`undo point: ${result.snapshot.rel}`] : []), + ]; + if (json && !pairs.some(([k]) => k !== "chrome.layout" && k !== "chrome.engine")) { + out(JSON.stringify({ ok: true, ...result, editNotes }, null, 2)); + return 0; + } + if (!json) out(msg.join("; ")); + const left = rest.filter((w) => !/^chrome\.(layout|engine)=/.test(w)); + if (!left.length) return 0; + return lookCommand([projectArg, ...left, ...(json ? ["--json"] : [])], { root, out, err }); + } const fc = pairs.filter(([k]) => k.startsWith("factcheck.")); const deck = pairs.filter(([k]) => k.startsWith("deck.")); const variants = pairs.filter(([k]) => k === "variants"); diff --git a/umtool/lib/report/knobsCli.test.mjs b/umtool/lib/report/knobsCli.test.mjs @@ -230,3 +230,34 @@ test("umtool set blur.*: on, caption (text whatever it parses as), strength, a s assert.equal("blur" in (await read(dir)).timeline[1], false); assert.match(lines.at(-1), /c02: blur none/); }); + +test("umtool look chrome.layout=deck --unset render.<key>: the deck turned on and the legacy keys dropped in ONE write, an undo point first", async () => { + const dir = path.join(ROOT, "legacy"); + await mkdir(dir, { recursive: true }); + const legacy = { + ...MANIFEST, slug: "legacy", + render: { width: 1920, height: 1080, fps: 30, rail: { width: 680 }, chromeEngine: "hyperframes", railEngine: "table", chromeRegions: ["panel"], claimSchedule: "pinned", wordmark: "X", title: { size: 1 }, finale: { open: 1 }, cut: { a: 1 } }, + }; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(legacy, null, 2) + "\n"); + const { lines, run } = runner(lookCommand); + // The deck beside the old rail is refused (the build's own sentence); the manifest untouched. + assert.equal(await run("legacy", "chrome.layout=deck"), 1); + assert.match(lines.join("\n"), /render\.chrome \(the deck\) and render\.rail cannot both be set/); + assert.equal((await read(dir)).render.chrome, undefined); + // A key that is not a legacy one is refused, and named. + assert.equal(await run("legacy", "--unset", "render.palette"), 2); + assert.match(lines.at(-1), /legacy render keys only/); + // In one write: the rail and the old engine keys gone, the deck on (render.chrome created). + assert.equal(await run("legacy", "chrome.layout=deck", ...["rail", "chromeEngine", "railEngine", "chromeRegions", "claimSchedule", "wordmark", "title", "finale", "cut"].flatMap((k) => ["--unset", `render.${k}`])), 0, lines.join("\n")); + const m = await read(dir); + assert.deepEqual(m.render, { width: 1920, height: 1080, fps: 30, chrome: { engine: "hyperframes", layout: "deck", deck: {} } }); + assert.match(lines.at(-1), /unset render\.rail, render\.chromeEngine.*chrome\.layout: deck \(render\.chrome created.*undo point: revisions\//); + const { readdir } = await import("node:fs/promises"); + assert.ok((await readdir(path.join(dir, "revisions"))).some((f) => /render-keys/.test(f)), "an undo point of its own"); + // deck.* keys in the same command land after the chrome exists. + const fresh = path.join(ROOT, "fresh"); + await mkdir(fresh, { recursive: true }); + await writeFile(path.join(fresh, "video.manifest.json"), JSON.stringify({ ...MANIFEST, slug: "fresh", render: { width: 1920, height: 1080, fps: 30 } }, null, 2) + "\n"); + assert.equal(await run("fresh", "chrome.layout=deck", "deck.sectionTitle=true"), 0, lines.join("\n")); + assert.deepEqual((await read(fresh)).render.chrome.deck, { sectionTitle: true }); +}); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -59,12 +59,12 @@ import { variantsProblems, verdictOfInput, } from "./knobs.mjs"; import { validateNarration } from "umtool-report-to-video/narration"; -import { validatePostItem, validatePostItems } from "umtool-report-to-video/post-item"; +import { postReadText, validatePostItem, validatePostItems } from "umtool-report-to-video/post-item"; import { threadReadErrors } from "umtool-report-to-video/post-thread"; import { planContext } from "umtool-report-to-video/post-conversation"; import { followKnobs } from "umtool-report-to-video/read-follow"; import { AVATARS_DIR, avatarEntryOf, handleKey, validatePostAvatars } from "umtool-report-to-video/post-avatars"; -import { POST_NARRATION_DEFAULTS, validatePostNarrationRender } from "umtool-report-to-video/post-narration"; +import { POST_NARRATION_DEFAULTS, draftScript, validatePostNarrationRender } from "umtool-report-to-video/post-narration"; import { termWords, validatePostsRender } from "umtool-report-to-video/post-redact"; import { parseMuteFrom } from "./playback.mjs"; import { isMeasureLedger, ledgerRowOf, ledgerRowReferences } from "./ledgerRows.mjs"; @@ -1639,6 +1639,69 @@ export class RenderRefused extends Error { } /** + * The legacy render keys a cut that moves to the deck may drop (`umtool look + * <p> --unset render.<key>`): the old branch's rail, its chrome engine and + * regions, its claim schedule, wordmark, title, finale and cut blocks. Only + * these: anything else is the look's writers'. + */ +export const LEGACY_RENDER_KEYS = Object.freeze(["rail", "chromeEngine", "railEngine", "chromeRegions", "claimSchedule", "wordmark", "title", "finale", "cut"]); + +/** + * TURN THE DECK ON, DROP LEGACY RENDER KEYS (`umtool look <p> chrome.layout=deck + * --unset render.<key>`): in ONE write, with an undo point first (an auto + * snapshot, "render-keys"): `unset` the LEGACY_RENDER_KEYS to remove, then + * `chrome` -- `{ layout?, engine? }` -- merged into render.chrome, which is + * created when the cut has none (engine "hyperframes", an empty deck). The + * chrome, when there is one after, is checked as the build reads it + * (validateChrome over the look preset) -- so a deck with the old rail + * beside it is refused unless that same write drops the rail. + * + * @param {string} dir + * @param {{ unset?: string[], chrome?: { layout?: string, engine?: string } | null }} patch + * @param {{ token?: string | null }} [opts] + * @returns {Promise<{ unset: string[], absent: string[], chrome: Record<string, unknown> | null, created: boolean, token: string | null, snapshot: unknown }>} + */ +export async function updateRenderKeys(dir, { unset = [], chrome = null } = {}, { token = null } = {}) { + const bad = unset.filter((k) => !LEGACY_RENDER_KEYS.includes(k)); + if (bad.length) throw new Error(`--unset takes the legacy render keys only (${LEGACY_RENDER_KEYS.join(", ")}): not ${bad.join(", ")}`); + if (chrome !== null && !isObj(chrome)) throw new Error("chrome must be { layout?, engine? }"); + for (const k of Object.keys(chrome ?? {})) if (!["layout", "engine"].includes(k)) throw new Error(`chrome.${k}: only chrome.layout and chrome.engine are set here (the deck's own keys: deck.<key>=…)`); + if (chrome?.layout !== undefined && chrome.layout !== "deck") throw new Error('chrome.layout must be "deck"'); + if (chrome?.engine !== undefined && chrome.engine !== "hyperframes") throw new Error('chrome.engine must be "hyperframes"'); + if (!unset.length && !chrome) throw new Error("nothing to write: name --unset render.<key> or chrome.layout=deck"); + return withManifestLock(async () => { + const current = await manifestToken(dir); + if (token !== null && current !== token) throw new StaleToken(token, current); + const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); + const render = isObj(manifest.render) ? { ...manifest.render } : {}; + const removed = []; + const absent = []; + for (const k of unset) { + if (k in render) { + delete render[k]; + removed.push(k); + } else absent.push(k); + } + let created = false; + if (chrome) { + created = !isObj(render.chrome); + render.chrome = { ...(created ? { engine: "hyperframes", layout: "deck", deck: {} } : render.chrome), ...chrome }; + } + manifest.render = render; + if (isObj(render.chrome)) { + const seen = effectiveManifest(manifest); + const { chrome: seenChrome, ...seenRest } = seen.render ?? {}; + const errors = validateChrome(seenChrome, seenRest); + if (errors.length) throw new ChromeRefused(errors); + } + if (!removed.length && !chrome) return { unset: [], absent, chrome: render.chrome ?? null, created: false, token: current, snapshot: null }; + const snapshot = await autoSnapshot(dir, "render-keys", { every: 0 }); + const nextToken = await writeManifestAtomic(dir, manifest); + return { unset: removed, absent, chrome: render.chrome ?? null, created, token: nextToken, snapshot }; + }); +} + +/** * Patch the look. Each key of `patch` is one of LOOK_KEYS; `null` removes the * key (the build's default again). `qr: true` turns the code back on (removes * a `false`; an object of settings is kept), `qr: false` turns it off. @@ -2480,7 +2543,7 @@ export async function insertEntries(dir, afterId, specs, { token = null, op = "i } /** The knobs of a post item a write may set (post-item.mjs; knobs.md, "A post item"). */ -export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "panel", "redact", "follow", "thread", "scene", "progress", "pictureOnly"]); +export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "panel", "redact", "follow", "thread", "scene", "progress", "pictureOnly", "excerpt"]); /** A post item attachment's knobs: its trim, its sound, its crop, the push-in, its transcript, its censoring blur. */ export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words", "blur", "enter"]); /** A context post's knobs (`quoted`, `parents[i]`): the operator's paraphrase of its words. */ @@ -2493,7 +2556,7 @@ const POST_REF_FIELDS = Object.freeze(["id", "author", "handle", "badge", "date" * is `{ hold?, mediaLayout?, redact?, scene?: false | "join", follow?: false | { on?, dim?, ease? }, thread?: { parent?, quoted?, carry?, * reveal?, shrink?, dim?, seconds?, pan? }, media?: { <i>: { start?, end?, mute?, * crop?, push?, words?, blur? } }, quoted?: { paraphrase? }, parents?: { <i>: - * { paraphrase? } } }`; a null clears a knob (the default again), and so + * { paraphrase? } }, excerpt?: [span…] | null }`; a null clears a knob (the default again), and so * does an empty paraphrase (the context's own words again; its `text` is * never touched). One structural write, refused in the build's words * (validatePostItem). @@ -2648,6 +2711,15 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { if (patch.links !== undefined) patchRefs("links", patch.links); const errors = validatePostItem(e); if (errors.length) throw new StructureRefused(errors); + // THE EXCERPT (post-item.mjs): a narrated item's script is redrafted from what is now read -- the spans joined, + // or the whole post again -- so the next take (`posts narrate --take`) reads it; its takes of the old script + // are kept (a take whose script is not the item's is not the one that plays until it is re-taken). + if ("excerpt" in patch && isObj(e.narration)) { + const d = draftScript(postReadText(e)); + if (d.script) e.narration.script = d.script; + if (e.excerpt) e.narration.excerpt = true; + else delete e.narration.excerpt; + } // NEVER NARRATE HIDDEN TEXT (post-thread.mjs): a change to what the card shows that leaves a part of its read // off the screen is refused, with the fix (one it had before is the guard's, not this write's). if ("thread" in patch || "follow" in patch || "parents" in patch || "links" in patch || "linksAdd" in patch) { diff --git a/umtool/lib/report/postExcerpt.test.mjs b/umtool/lib/report/postExcerpt.test.mjs @@ -0,0 +1,87 @@ +// A post item's EXCERPT (post-item.mjs; rev 9, 6 Nov): a long post read in part -- verbatim spans of its words, in +// order -- the read the spans joined with " … ", the card the whole post with the unread words dimmed. Its writer +// (`umtool posts set-item <p> <item> excerpt='[…]'`) and its script (`posts narrate --all --draft-scripts`). +// Made-up posts only. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { postsCommand } from "./postsCli.mjs"; +import { + excerptCutWords, excerptErrors, excerptRanges, postCardHtml, postReadText, readSeconds, validatePostItem, +} from "umtool-report-to-video/post-item"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-excerpt-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const REPORTS = path.join(ROOT, "reports"); +const TEXT = "I bought your coffee. You have my name and my address. Also a long aside about scrubs nobody needs. I look forward to the video."; +const item = (o = {}) => ({ type: "post", id: "p-1", post: "savvy-x/1", platform: "x", author: "A Person", handle: "aperson", date: "2026-10-23T10:00:00.000Z", text: TEXT, ...o }); +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") }; +}; +async function project(name, timeline) { + const dir = path.join(REPORTS, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "", channelSlug: "savvy-x" }, + render: { width: 1920, height: 1080, fps: 30 }, timeline, + }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + +test("the excerpt: spans found in order, the read joined with \" … \", the unread words dimmed on the whole card", () => { + const e = item({ excerpt: ["I bought your coffee.", "I look forward to the video."] }); + assert.deepEqual(validatePostItem(e), []); + assert.deepEqual(excerptRanges(TEXT, e.excerpt), [{ start: 0, end: 21 }, { start: TEXT.indexOf("I look"), end: TEXT.length }]); + assert.equal(postReadText(e), "I bought your coffee. … I look forward to the video."); + assert.ok(readSeconds(e) < readSeconds(item()), "it reads in less time than the whole post"); + const cut = excerptCutWords(e); + assert.ok(cut.has(4) && !cut.has(0) && !cut.has(3), "words 0-3 read; 4 on dimmed"); + const html = postCardHtml(e, { width: 1248, height: 702 }); + assert.match(html, /data-post-cut=""/); + for (const w of ["scrubs", "address", "coffee", "video"]) assert.ok(html.includes(w), `the card shows "${w}" (the whole post)`); + assert.equal(postCardHtml(item(), { width: 1248, height: 702 }).includes("data-post-cut"), false, "no excerpt: nothing dimmed"); + // Refused: a span not in the text, spans out of order, an empty list. + assert.match(excerptErrors(item({ excerpt: ["I bought your tea."] }))[0], /is not in the post's words \(an excerpt is verbatim\)/); + assert.match(excerptErrors(item({ excerpt: ["I look forward", "I bought"] }))[0], /before the span ahead of it/); + assert.match(excerptErrors(item({ excerpt: [] }))[0], /must be a list of the post's own words/); +}); + +test("posts set-item excerpt='[…]': written through the item writer, the narrated script redrafted from it; excerpt=off reads the whole post again", async () => { + const p = await project("x", [item({ narration: { script: "I bought your coffee. You have my name and my address. Also a long aside about scrubs nobody needs. I look forward to the video." } })]); + let r = await cli(["set-item", "x", "p-1", `excerpt=["I bought your coffee.","I look forward to the video."]`]); + assert.equal(r.code, 0, r.err); + let e = (await manifest(p)).timeline[0]; + assert.deepEqual(e.excerpt, ["I bought your coffee.", "I look forward to the video."]); + assert.equal(e.narration.script, "I bought your coffee. … I look forward to the video."); + assert.equal(e.narration.excerpt, true); + assert.equal(e.text, TEXT, "the post's words are never rewritten"); + // A span that is not verbatim is refused in the build's words; the manifest untouched. + r = await cli(["set-item", "x", "p-1", `excerpt=["I bought your tea."]`]); + assert.notEqual(r.code, 0); + assert.match(r.err + r.out, /not in the post's words/); + assert.deepEqual((await manifest(p)).timeline[0].excerpt, ["I bought your coffee.", "I look forward to the video."]); + r = await cli(["set-item", "x", "p-1", "excerpt=nope"]); + assert.notEqual(r.code, 0); + assert.match(r.err + r.out, /JSON list/); + r = await cli(["set-item", "x", "p-1", "excerpt=off"]); + assert.equal(r.code, 0, r.err); + e = (await manifest(p)).timeline[0]; + assert.equal(e.excerpt, undefined); + assert.equal(e.narration.excerpt, undefined); + assert.match(e.narration.script, /scrubs nobody needs/); +}); + +test("posts narrate --all --draft-scripts drafts an excerpted item from its spans", async () => { + const p = await project("d", [item({ excerpt: ["I bought your coffee.", "I look forward to the video."] })]); + const r = await cli(["narrate", "d", "--all", "--draft-scripts"]); + assert.equal(r.code, 0, r.err); + const e = (await manifest(p)).timeline[0]; + assert.equal(e.narration.script, "I bought your coffee. … I look forward to the video."); + assert.equal(e.narration.excerpt, true); +}); diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -26,7 +26,7 @@ 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 { postItemPlan } from "umtool-report-to-video/post-item"; +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"; import { projectRedaction } from "./postRedaction.mjs"; @@ -290,7 +290,26 @@ export function mixPatchOf(pairs, { cut = false } = {}) { * the project, measured, appended (and picked) through the writer. Returns * the take and the write's result. */ -export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, render = {}, emit = () => {}, editor = null, ask = null, askOp = null, redaction = undefined } = {}) { +/** The longest a take waits for its beep's word timing (the editor's transcription) before it defers it. */ +export const BEEP_TIMING_DEADLINE_MS = 5 * 60 * 1000; + +/** + * Is the editor's transcription lane HELD (render mode, a TTS session)? Its + * transcribe job would wait for a worker until it is released. Unknown (no + * token, the editor not answering): false -- the timing's own deadline bounds it. + */ +export async function transcriptionLaneHeld() { + try { + const { editorLanes } = await import("./renderMode.mjs"); + const { editorConfig } = await import("./fetchWindows.mjs"); + const lanes = editorLanes(editorConfig()); + return lanes ? await lanes.isHeld("transcription") : false; + } catch { + return false; + } +} + +export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, render = {}, emit = () => {}, editor = null, ask = null, askOp = null, redaction = undefined, laneHeld = null, timingDeadlineMs = BEEP_TIMING_DEADLINE_MS } = {}) { const k = postNarrationKnobs(e, render); const words = String(script ?? e.narration?.script ?? "").trim(); if (!words) throw new NarrateError(`${e.id} has no script to read (--script "…", or --all --draft-scripts)`); @@ -317,13 +336,32 @@ export async function makeTake(project, e, { script = null, note = null, engine // done, the read is synthesized again with the slur left out -- a published take never says one it cannot cover. let slurs = said.slurs; let timed = null; + let deferred = null; if (slurs === "said" && red?.slurs?.on && red.slurs.voice === "beep") { + // NEVER BLOCK ON THE LANE (rev 9, 6 Nov): with the transcription lane held -- as it is while Orpheus runs -- + // the editor's transcribe job would wait for a worker until it is released, and this take with it. The take is + // kept as read (it says the slur; the build refuses to play it until its words are timed) and the timing is + // left for after the release: `posts narrate <p> <item> --words`. + // (A caller that hands in its own transcribe op -- a test's stub -- is asked about no lane unless it says.) + const held = laneHeld ?? (askOp ? async () => false : transcriptionLaneHeld); + if (await held()) { + deferred = { words: `umtool posts narrate ${project.id} ${e.id} --words` }; + emit("note", { message: `${e.id}: its read says a slur the cut beeps, and the editor's transcription lane is held -- its words are NOT timed now (that would wait for the release). After releasing the lane run: ${deferred.words} (the build refuses this take until then)` }); + } + } + if (!deferred && slurs === "said" && red?.slurs?.on && red.slurs.voice === "beep") { try { - timed = await timeTakeWords(project, rel, words, { askOp, emit }); + timed = await timeTakeWords(project, rel, words, { askOp, emit, deadlineMs: timingDeadlineMs }); } catch (err) { - emit("note", { message: `${e.id}: its read could not be word-timed for the beep (${err instanceof Error ? err.message : err}) -- synthesized again with the slur left out` }); - ({ jobId, result } = await askTts(ttsBody(spokenRead(words, e, red, { voice: "skip" }).text), { ...(editor ? { editor } : {}), emit })); - slurs = "skip"; + if (err?.name === "OpDeadline") { + // Waited its bound: kept as read, timed later -- never an unbounded wait. + deferred = { words: `umtool posts narrate ${project.id} ${e.id} --words` }; + emit("note", { message: `${e.id}: ${err.message} -- the take is kept as read; time its words later: ${deferred.words} (the build refuses this take until then)` }); + } else { + emit("note", { message: `${e.id}: its read could not be word-timed for the beep (${err instanceof Error ? err.message : err}) -- synthesized again with the slur left out` }); + ({ jobId, result } = await askTts(ttsBody(spokenRead(words, e, red, { voice: "skip" }).text), { ...(editor ? { editor } : {}), emit })); + slurs = "skip"; + } } } const m = await measureTake(out); @@ -339,7 +377,7 @@ export async function makeTake(project, e, { script = null, note = null, engine }; const patch = { addTake: take, ...(script !== null && script !== e.narration?.script ? { script: words } : {}) }; const { result: wrote, editNotes } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, patch, { token: await manifestToken(project.dir) })); - return { take, result: wrote, editNotes }; + return { take, result: wrote, editNotes, ...(deferred ? { deferred } : {}) }; } /** @@ -348,14 +386,14 @@ export async function makeTake(project, e, { script = null, note = null, engine * scriptWordTimes) -- `posts narrate --words`' way, before the take is kept. * Throws when the editor cannot, or hears no words. */ -async function timeTakeWords(project, rel, script, { askOp = null, emit = () => {} } = {}) { +async function timeTakeWords(project, rel, script, { askOp = null, emit = () => {}, deadlineMs = null } = {}) { const { recognizedOf, wordsFileOf } = await import("./postFxCli.mjs"); const { scriptWordTimes } = await import("umtool-report-to-video/word-zoom"); const ask = askOp ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp; const abs = path.join(project.dir, ...rel.split("/")); const outFile = path.join(project.dir, ...wordsFileOf(rel).split("/")); emit("note", { message: `timing ${rel}'s words for the beep (the editor's transcription)…` }); - await ask("/api/ops/transcribe", { path: abs, words: true, out: outFile }, { emit }); + await ask("/api/ops/transcribe", { path: abs, words: true, out: outFile }, { emit, ...(deadlineMs !== null ? { deadlineMs } : {}) }); const heard = recognizedOf(JSON.parse(await readFile(outFile, "utf8")), 0); if (!heard.length) throw new Error("the transcription came back with no word timings"); return scriptWordTimes(script, heard).words; @@ -427,9 +465,10 @@ export async function narrateCommand(project, words, flags, { json = false, dryR const patches = []; for (const e of tl) { if (!force && typeof e.narration?.script === "string" && e.narration.script) continue; - const d = draftScript(e.text); + // What is read: its excerpt's spans (post-item.mjs postReadText), else the whole post. + const d = draftScript(postReadText(e)); if (!d.script) continue; - patches.push({ id: e.id, patch: { script: d.script, excerpt: null } }); + patches.push({ id: e.id, patch: { script: d.script, excerpt: excerptSpansOf(e) ? true : null } }); } if (dryRun || !patches.length) { out(json ? JSON.stringify({ ok: true, dryRun, patches }, null, 2) : `${dryRun ? "would draft" : "nothing to draft:"} ${patches.length} script(s)${patches.length ? "" : " (every post item has one; --force redrafts them)"}`); diff --git a/umtool/lib/report/postReel.mjs b/umtool/lib/report/postReel.mjs @@ -39,7 +39,8 @@ import path from "node:path"; import { promisify } from "node:util"; import { POST_MEDIA_MAX, POST_PARENTS_FILL, authorRedaction, cardAuthors, subjectsOf } from "umtool-report-to-video/post-item"; import { ARCHIVE_AVATARS_DIR, ARCHIVE_AVATARS_FILE, AVATARS_DIR, AVATAR_EXT_RE, avatarEntryOf, handleKey } from "umtool-report-to-video/post-avatars"; -import { channelsDirFor, readManifest } from "../projects/report.mjs"; +import { channelsDirFor, channelsLayersFor, readManifest } from "../projects/report.mjs"; +import { firstLayerWith } from "umtool-report-to-video/sources"; import { withEditNotes } from "./edit-guard.mjs"; import { addArchiveAvatars, insertEntries, manifestToken } from "./manifest.mjs"; import { deckPlatformOf } from "./postsCli.mjs"; @@ -421,14 +422,21 @@ export async function postsReel(project, o) { if (o.limit !== null && o.limit !== undefined && !(Number.isInteger(o.limit) && o.limit > 0)) throw new Error("--limit takes a whole number of posts"); const manifest = await readManifest(project.dir); if (!manifest) throw new Error(`${project.id} has no manifest`); - const channelsDir = o.channelsDir ?? channelsDirFor(project.dir, manifest); + const layers = o.channelsDir ? [o.channelsDir] : channelsLayersFor(project.dir, manifest); + const channelsDir = layers[0] ?? channelsDirFor(project.dir, manifest); const rows = []; const handles = []; + // Each channel from the first tree that holds its posts: the project's, else the corpus behind it. + const rootOf = new Map(); + const root = async (slug) => { + if (!rootOf.has(slug)) rootOf.set(slug, layers.length > 1 ? await firstLayerWith(layers, [slug, "posts"], { kind: "posts" }) : channelsDir); + return rootOf.get(slug); + }; for (const c of channels) { - const got = await readPostsArchive(channelsDir, c); - if (!got.length) throw new Error(`${c} has no posts archive under ${channelsDir} (channels/${c}/posts/*.jsonl) — is it a social channel?`); + const got = await readPostsArchive(await root(c), c); + if (!got.length) throw new Error(`${c} has no posts archive under ${layers.join(" or ")} (channels/${c}/posts/*.jsonl) — is it a social channel?`); rows.push(...got); - const h = await channelHandle(channelsDir, c); + const h = await channelHandle(await root(c), c); if (h) handles.push(h); } // Every channel's rows by id, for the parents, the quoted post and a repost's original. @@ -437,7 +445,7 @@ export async function postsReel(project, o) { const captures = new Map(); const capture = async (slug, id) => { const k = `${slug}/${id}`; - if (!captures.has(k)) captures.set(k, await captureOf(channelsDir, slug, id)); + if (!captures.has(k)) captures.set(k, await captureOf(await root(slug), slug, id)); return captures.get(k); }; // "With media": the post's capture (or a repost's original's) holds an attachment. @@ -475,7 +483,8 @@ export async function postsReel(project, o) { dropped += made.dropped; } // The authors' pictures: the archive's, for every author the cards draw unblurred that the cut has none of. - const store = await archiveAvatars(channelsDir, channels); + 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); 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 }; @@ -505,7 +514,8 @@ export async function postsReel(project, o) { */ export async function postItemFromArchive(project, manifest, slug, postId, { id = null, channelsDir = null } = {}) { if (!SLUG_RE.test(slug)) throw new Error(`"${slug}" is not a channel slug`); - const dir = channelsDir ?? channelsDirFor(project.dir, manifest); + // The project's channels tree first, the corpus behind it for a channel it lacks (sources.mjs channelsLayersFor). + const dir = channelsDir ?? await firstLayerWith(channelsLayersFor(project.dir, manifest), [slug, "posts"], { kind: "posts" }); const rows = await readPostsArchive(dir, slug); const index = new Map(rows.map((r) => [r.id, r])); const row = index.get(String(postId)); diff --git a/umtool/lib/report/postSlurs.test.mjs b/umtool/lib/report/postSlurs.test.mjs @@ -199,6 +199,50 @@ test("a beep take: said, then word-timed so the render can beep it; when it cann assert.match(notes.join("\n"), /could not be word-timed for the beep \(no parakeet worker\)/); }); +test("a beep take with the transcription lane HELD: never waits on it -- kept as read, the timing deferred to `posts narrate --words`; a timing past its deadline likewise", async () => { + const script = `Hello, you ${F}. Welcome.`; + const p = await project("held", [item("1", { narration: { script } })], { posts: { slurs: { voice: "beep" } } }); + const asked = []; + const notes = []; + let transcribed = 0; + // A transcribe op that would wait forever while the lane is held (a promise that never settles): never asked. + const askOp = async () => { transcribed += 1; return new Promise(() => {}); }; + const r = await makeTake(p, (await manifest(p)).timeline[0], { ask: asker(asked), askOp, laneHeld: async () => true, emit: (_e, f) => notes.push(f.message) }); + assert.equal(transcribed, 0, "the held lane is never waited on"); + assert.equal(asked.length, 1, "one read, the slur said (for the beep)"); + assert.equal(r.take.slurs, "said"); + assert.equal(r.take.words, undefined); + assert.deepEqual(r.deferred, { words: "umtool posts narrate held p-1 --words" }); + assert.match(notes.join("\n"), /transcription lane is held -- its words are NOT timed now .* umtool posts narrate held p-1 --words/); + assert.equal((await manifest(p)).timeline[0].narration.takes.length, 1, "the take is kept"); + // Not held, but the transcription takes longer than its bound: the same deferral, never an unbounded wait. + const q = await project("slow", [item("1", { narration: { script } })], { posts: { slurs: { voice: "beep" } } }); + const notes2 = []; + const { OpDeadline } = await import("umtool-report-to-video/narrate-via-editor"); + const slowOp = async (route, _body, o) => { assert.equal(o.deadlineMs, 50); throw new OpDeadline(route, "t-9", 50); }; + const r2 = await makeTake(q, (await manifest(q)).timeline[0], { ask: asker([]), askOp: slowOp, laneHeld: async () => false, timingDeadlineMs: 50, emit: (_e, f) => notes2.push(f.message) }); + assert.equal(r2.take.slurs, "said"); + assert.deepEqual(r2.deferred, { words: "umtool posts narrate slow p-1 --words" }); + assert.match(notes2.join("\n"), /did not finish within 0 s .* time its words later/); +}); + +test("askEditorOp's deadline: a job still queued past it is given up on (OpDeadline), never polled forever", async () => { + const { askEditorOp, OpDeadline } = await import("umtool-report-to-video/narrate-via-editor"); + const http = await import("node:http"); + const srv = http.createServer((req, res) => { + res.setHeader("content-type", "application/json"); + if (req.method === "POST") return res.end(JSON.stringify({ ok: true, jobId: "j-1" })); + res.end(JSON.stringify({ ok: true, job: { status: "queued", queue: { position: 1, queued: 1 } } })); + }); + await new Promise((ok) => srv.listen(0, "127.0.0.1", ok)); + const url = `http://127.0.0.1:${srv.address().port}`; + try { + await assert.rejects(askEditorOp("/api/ops/transcribe", { path: "/x.wav" }, { editor: { url, token: "t" }, pollMs: 10, deadlineMs: 60 }), (e) => e instanceof OpDeadline && /did not finish/.test(e.message)); + } finally { + srv.close(); + } +}); + test("umtool take … --uncensored: the slur filter off in the take's patch, its label and take.json say so", async () => { const p = await project("u", [item("1", { text: `you ${F}` })]); await mkdir(path.join(p.dir, "out", "clips-raw"), { recursive: true }); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -103,6 +103,7 @@ export const POSTS_USAGE = [ " the channels merged in time order, de-duplicated by post id; a post already in the cut is skipped, so a re-run", " adds only what is new -- in ONE write (one undo point), at the end unless --after.", " umtool posts set-item <project> <item> [hold=<s>|off] [layout=sequence|grid] [redact=on|off|auto] [scene=off|join|auto] [follow=on|off|auto] [follow.dim=<0.2-1>] [follow.ease=<s>]", + " [excerpt='[\"<span>\", …]'|off] read only these verbatim spans (in the post's order, joined \" … \"); the card shows the whole post, the rest dimmed", " [thread.parent[.<i>]=auto|full|excerpt|context|carry|hidden] [thread.quoted=auto|full|excerpt|context|hidden]", " [thread.carry=auto|on|off] [thread.reveal=on|off] [thread.shrink=<0.3-1>] [thread.dim=<0.15-1>]", " [thread.seconds=<0-3>] [thread.pan=<0.1-3>] [thread=auto]", @@ -396,8 +397,11 @@ export async function addPostFromArchive(project, { slug, postId, attach = null, if (!SLUG_RE.test(slug) || !POST_ID_RE.test(postId)) throw new CliError(`not <archive-channel>/<postId>: ${slug}/${postId}`); const manifest = await readManifest(project.dir); if (!manifest) throw new CliError(`${project.id} has no manifest`); - // The corpus the project reads (provenance.channelsDir), else the global one. - const channelsDir = channelsDirFor(project.dir, manifest); + // The corpus the project reads (provenance.channelsDir), else the global one -- and the global one behind a + // project's own tree for a channel that tree lacks (sources.mjs channelsLayersFor). + const { channelsLayersFor } = await import("../projects/report.mjs"); + const { firstLayerWith } = await import("umtool-report-to-video/sources"); + const channelsDir = await firstLayerWith(channelsLayersFor(project.dir, manifest), [slug, "posts"], { kind: "posts" }) ?? channelsDirFor(project.dir, manifest); const found = await findPostRow(channelsDir, slug, postId); if (!found.row) { throw new Error( @@ -939,6 +943,20 @@ export function postItemPatchOf(pairs) { const raw = pair.slice(eq + 1); const v = raw.toLowerCase(); if (k === "hold") out.hold = OFF.has(v) || v === "" ? null : Number(raw); + // Its EXCERPT (post-item.mjs): excerpt='["span", "span"]' -- verbatim spans of the post, in order -- or off. + else if (k === "excerpt") { + if (OFF.has(v) || v === "") out.excerpt = null; + else { + let spans; + try { + spans = JSON.parse(raw); + } catch { + throw new CliError(`excerpt= takes a JSON list of the post's own words, e.g. excerpt='["I bought your shitty coffee.","I look forward to you felting me"]' (or off)`); + } + if (!Array.isArray(spans) || !spans.every((x) => typeof x === "string")) throw new CliError("excerpt= takes a JSON list of strings (verbatim spans of the post, in order)"); + out.excerpt = spans; + } + } else if (k === "layout") out.mediaLayout = v === "sequence" ? null : v; else if (k === "redact") out.redact = v === "auto" || v === "" ? null : onOff(v, k); // Its progress bar (post-progress.mjs): on, off or auto (60 s of read or more); default: the cut's. diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -144,7 +144,7 @@ import { cutArgs } from "yt-dlp-transcript-common/lib/evidenceClip.mjs"; // Where a clip's media is ALREADY on disk -- the build's raw cache, the // editor's corpus windows, the saved source -- asked before anything fetches. import { - SHADOW_CHANNELS, WIN_EPS as SRC_EPS, audioUse, channelsDirFor, findContainingWindow, rawWindowName, + SHADOW_CHANNELS, WIN_EPS as SRC_EPS, audioUse, channelsDirFor, channelsLayersFor, findContainingWindow, rawWindowName, resolveLocalSource, } from "./sources.mjs"; // A clip whose media is a file beside the manifest (`src`, `cues`). @@ -1045,7 +1045,7 @@ export function virtualEntry(entry, clock) { * so `--no-network`'s up-front pass and the clip's own fetch probe a saved * container once between them. */ -export function localSources({ rawDir, channelsDir, channelSlug = null, probe } = {}) { +export function localSources({ rawDir, channelsDir, channelSlug = null, probe, fallbackChannelsDir = null, log = undefined } = {}) { const memo = new Map(); const slugOf = (entry) => entry.channel ?? channelSlug ?? null; return { @@ -1059,7 +1059,7 @@ export function localSources({ rawDir, channelsDir, channelSlug = null, probe } if (memo.has(key)) return memo.get(key); const hit = await resolveLocalSource( { video: entry.video, slug, from: span.from, to: span.to }, - { rawDir, channelsDir, exact, probe, audio }, + { rawDir, channelsDir, exact, probe, audio, fallbackChannelsDir, log }, ); // Hits only: a miss is about to be fetched into the raw cache, and the // next clip asking for the same span must find that file. @@ -6643,12 +6643,24 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // bench reads for this project (sources.mjs channelsDirFor): the manifest's // own `provenance.channelsDir`, a `.shadow-channels/` beside it, else the // corpus the cue reader defaults to. - const channelsDir = opts.channelsDir ?? channelsDirFor(manifestDir, whole, { - shadowExists: await stat(path.join(manifestDir, SHADOW_CHANNELS)).then((st) => st.isDirectory(), () => false), - fallback: DEFAULT_CHANNELS_DIR, - }); + const shadowExists = await stat(path.join(manifestDir, SHADOW_CHANNELS)).then((st) => st.isDirectory(), () => false); + const channelsDir = opts.channelsDir ?? channelsDirFor(manifestDir, whole, { shadowExists, fallback: DEFAULT_CHANNELS_DIR }); + // THE SHADOW FIRST, THE CORPUS AFTER (sources.mjs channelsLayersFor): a project's own channels tree, and the + // corpus behind it for any cue file or cached window it lacks -- each kind said once; off with + // provenance.channelsFallback: false or CHANNELS_FALLBACK=0. + const layers = opts.channelsDir ? [opts.channelsDir] : channelsLayersFor(manifestDir, whole, { shadowExists, fallback: DEFAULT_CHANNELS_DIR }); + if (layers.length > 1) { + CUES = createCueSource({ + siteOrigin: opts.siteOrigin ?? process.env.SITE_ORIGIN ?? siteOriginFromManifest(whole), + resolveSiteIds: opts.resolveSiteIds === true, + prefer: opts.cueSource ?? "auto", + log: (m) => EMIT("log", { message: m }), + channelsDirs: layers, + }); + } dirs.local = localSources({ rawDir: dirs.rawDir, channelsDir, channelSlug: provenance?.channelSlug ?? null, probe: opts.probe, + fallbackChannelsDir: layers[1] ?? null, log: (m) => EMIT("note", { message: m }), }); FX_CHANNELS_DIR = channelsDir; // Read only for a cut that plays post items: a cut without them publishes nothing it could blank. diff --git a/umtool/report-to-video/channels-layers.test.mjs b/umtool/report-to-video/channels-layers.test.mjs @@ -0,0 +1,83 @@ +// The shadow first, the corpus after (sources.mjs channelsLayersFor; rev 9, 6 Nov): a project's own channels tree +// (`provenance.channelsDir`, a `.shadow-channels/`) read first, the real corpus behind it for anything it lacks -- +// posts, cue files, cached windows -- each kind said once; off with `provenance.channelsFallback: false` or +// CHANNELS_FALLBACK=0. Temp dirs only. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; + +import { + channelsFallbackOn, channelsLayersFor, firstLayerWith, resetChannelsFallbackNotes, resolveLocalSource, +} from "./sources.mjs"; +import { createCueSource } from "./cues.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-channels-layers-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const PROJECT = path.join(ROOT, "project"); +const SHADOW = path.join(PROJECT, ".shadow-channels"); +const CORPUS = path.join(ROOT, "transcripts", "channels"); +const put = async (file, body = "x") => { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, body); +}; + +test("channelsLayersFor: the project's tree, then the corpus -- unless the manifest or the environment turns it off", () => { + const declared = { provenance: { channelsDir: ".shadow-channels" } }; + assert.deepEqual(channelsLayersFor(PROJECT, declared, { fallback: CORPUS, env: {} }), [SHADOW, CORPUS]); + assert.deepEqual(channelsLayersFor(PROJECT, {}, { shadowExists: true, fallback: CORPUS, env: {} }), [SHADOW, CORPUS]); + assert.deepEqual(channelsLayersFor(PROJECT, {}, { fallback: CORPUS, env: {} }), [CORPUS], "no tree of its own: the corpus alone"); + assert.deepEqual(channelsLayersFor(PROJECT, { provenance: { channelsDir: ".shadow-channels", channelsFallback: false } }, { fallback: CORPUS, env: {} }), [SHADOW]); + assert.deepEqual(channelsLayersFor(PROJECT, declared, { fallback: CORPUS, env: { CHANNELS_FALLBACK: "0" } }), [SHADOW]); + assert.equal(channelsFallbackOn({}, {}), true); +}); + +test("firstLayerWith: the first tree holding the path -- a later one said ONCE per kind; none: the first (its own miss)", async () => { + resetChannelsFallbackNotes(); + await put(path.join(SHADOW, "him-x", "posts", "a.jsonl")); + await put(path.join(CORPUS, "her-x", "posts", "a.jsonl")); + const said = []; + const log = (m) => said.push(m); + assert.equal(await firstLayerWith([SHADOW, CORPUS], ["him-x", "posts"], { kind: "posts", log }), SHADOW); + assert.equal(await firstLayerWith([SHADOW, CORPUS], ["her-x", "posts"], { kind: "posts", log }), CORPUS); + assert.equal(await firstLayerWith([SHADOW, CORPUS], ["her-x", "posts"], { kind: "posts", log }), CORPUS); + assert.equal(said.length, 1, "said once"); + assert.match(said[0], /posts: her-x\/posts is not in .*shadow-channels -- read from .*transcripts\/channels/); + assert.equal(await firstLayerWith([SHADOW, CORPUS], ["nobody-x", "posts"], { kind: "posts", log }), SHADOW); + assert.equal(await firstLayerWith([SHADOW], ["her-x", "posts"], { kind: "posts", log }), SHADOW, "the fallback off: the shadow alone"); +}); + +test("resolveLocalSource: a cached window the project's tree lacks is read from the corpus behind it (corpus tiers only)", async () => { + resetChannelsFallbackNotes(); + await put(path.join(CORPUS, "chan", "data", "vid9", "clips", "10.00-30.00.mp4")); + const said = []; + const hit = await resolveLocalSource({ video: "vid9", slug: "chan", from: 12, to: 20 }, { channelsDir: SHADOW, fallbackChannelsDir: CORPUS, log: (m) => said.push(m), probe: async () => null }); + assert.equal(hit?.kind, "corpus-window"); + assert.equal(hit.path, path.join(CORPUS, "chan", "data", "vid9", "clips", "10.00-30.00.mp4")); + assert.match(said[0], /windows: chan\/vid9 12-20 is not in .* -- read from /); + assert.equal(await resolveLocalSource({ video: "vid9", slug: "chan", from: 12, to: 20 }, { channelsDir: SHADOW, probe: async () => null }), null, "no fallback: the shadow alone, as before"); +}); + +test("createCueSource channelsDirs: a cue file the project's tree lacks is read from the corpus behind it, said once", async () => { + const cues = { cues: [{ start: 0, end: 1, text: "hi" }], duration: 1 }; + await put(path.join(CORPUS, "chan", "data", "vid7", "transcript.cues.json"), JSON.stringify(cues)); + await put(path.join(SHADOW, "chan", "data", "vid8", "transcript.cues.json"), JSON.stringify({ ...cues, duration: 2 })); + const said = []; + const src = createCueSource({ channelsDirs: [SHADOW, CORPUS], prefer: "local", log: (m) => said.push(m), cacheDir: path.join(ROOT, "cache") }); + assert.equal((await src.load("chan", "vid8")).duration, 2, "the shadow's own"); + assert.equal((await src.load("chan", "vid7")).duration, 1, "the corpus behind it"); + await src.load("chan", "vid7"); + assert.equal(said.filter((m) => /^cues:/.test(m)).length, 1); + // The shadow alone (the fallback off): a miss, as before. + const alone = createCueSource({ channelsDirs: [SHADOW], prefer: "local", cacheDir: path.join(ROOT, "cache") }); + await assert.rejects(alone.load("chan", "vid7"), /no local cues for chan\/vid7/); +}); + +test("cuePathFor: a clip's cue file from the corpus when the project's tree has none", async () => { + const { cuePathFor } = await import("../lib/projects/report.mjs"); + const m = { provenance: { channelSlug: "chan" } }; + assert.equal(cuePathFor(m, { video: "vid8" }, SHADOW, CORPUS), path.join(SHADOW, "chan", "data", "vid8", "transcript.cues.json")); + assert.equal(cuePathFor(m, { video: "vid7" }, SHADOW, CORPUS), path.join(CORPUS, "chan", "data", "vid7", "transcript.cues.json")); + assert.equal(cuePathFor(m, { video: "vid7" }, SHADOW, null), path.join(SHADOW, "chan", "data", "vid7", "transcript.cues.json"), "off: the shadow's path"); +}); diff --git a/umtool/report-to-video/chrome-measure-extras.mjs b/umtool/report-to-video/chrome-measure-extras.mjs @@ -16,7 +16,7 @@ import { rgba } from "./chrome-deck.mjs"; import { compileCues, cuePageHtml, esc, INSTANT, joinSpans, r4, spanEvents } from "./chrome-cues.mjs"; import { daysBetween, daysLeftText, daysText, dietStates, goalStates, measureExtraGeometry, measureOf, MEASURE_BOXES, - monthYear, peakStates, promiseStates, shortDate, streakStates, upSpans, weightText, + MEASURE_DODGE_MOVE, measurePlacements, monthYear, peakStates, promiseStates, shortDate, streakStates, upSpans, weightText, } from "./measure-extras.mjs"; import { MEASURE_RED, resolveMeasureExtra } from "./modules/measure-extras-settings.mjs"; @@ -59,10 +59,82 @@ function stateCues(states, spans, { overlap = 0, own = () => [] } = {}, initExtr return compileCues(init, ev); } -const page = (id, schedule, opts, { geo, fps }, css, body, init, cues, ids) => cuePageHtml({ - id, W: geo.width, H: geo.height, fps, fonts: opts.fonts, gsapSrc: opts.gsap, css: `${displayFace(opts.fonts)}\n ${css}`, - body, init, cues, whole: { total: schedule.total, from: opts.from, duration: opts.duration, ids }, primeWindow: true, -}); +/** + * Where the mover stands over time: `[{ at, to: "home" | "hide" | { x, y, size } }]`, + * one step wherever that changes. Moves may overlap (a post item's span + * crossfades into the next one's, a chapter band rises inside a post): while + * any move that hides is on, it is hidden; else it stands where the latest + * move to start puts it; with none, at home. + */ +export function moverSteps(moves) { + const cuts = [...new Set(moves.flatMap((m) => [m.from, m.to]))].sort((a, b) => a - b); + const steps = []; + let was = "home"; + for (const at of cuts) { + const on = moves.filter((m) => m.from <= at + 1e-6 && m.to > at + 1e-6); + let to = "home"; + if (on.some((m) => !m.rect)) to = "hide"; + else if (on.length) { + const m = on.reduce((x, y) => (y.from >= x.from ? y : x)); + to = { x: m.rect.x, y: m.rect.y, size: m.size }; + } + if (JSON.stringify(to) !== JSON.stringify(was)) steps.push({ at, to }); + was = to; + } + return steps; +} + +/** + * The mover's cues (measure-extras.mjs measurePlacements, through + * moverSteps): the module's box `mv` slides to each slot clear of a post card + * or a chapter band (scaled from its corner) and back, or fades out and in + * when nothing fits -- each change over MEASURE_DODGE_MOVE, or half the time + * to the next. + */ +export function moverCues(place) { + const { home } = place; + const init = { mv: { x: 0, y: 0, scale: 1, autoAlpha: 1 } }; + const steps = moverSteps(place.moves); + const ev = []; + let alpha = 1; + let pos = { x: 0, y: 0, scale: 1 }; + steps.forEach((st, i) => { + const next = steps[i + 1]?.at ?? Infinity; + const d = Math.max(INSTANT, Math.min(MEASURE_DODGE_MOVE, (next - st.at) / 2)); + if (st.to === "hide") { + if (alpha !== 0) ev.push({ k: "mv", at: st.at, dur: d, to: { autoAlpha: 0 }, ease: "power1.in" }); + alpha = 0; + return; + } + const want = st.to === "home" ? { x: 0, y: 0, scale: 1 } : { x: st.to.x - home.x, y: st.to.y - home.y, scale: st.to.size }; + const moved = JSON.stringify(want) !== JSON.stringify(pos); + if (alpha === 0) { + // Hidden: put it in place at once, then fade it in there. + if (moved) ev.push({ k: "mv", at: st.at, dur: INSTANT, to: want, ease: "none" }); + ev.push({ k: "mv", at: st.at, dur: d, to: { autoAlpha: 1 }, ease: "power1.out" }); + } else if (moved) ev.push({ k: "mv", at: st.at, dur: d, to: want, ease: "power2.inOut" }); + alpha = 1; + pos = want; + }); + return compileCues(init, ev); +} + +/** + * A module's page: its box drawn in its region (its home, and every slot it + * moves clear to), inside the mover `mv`. + */ +const page = (id, schedule, opts, { fps }, css, body, init, cues, ids, render) => { + const place = measurePlacements(schedule, render)[id]; + const { home, region } = place; + const mover = moverCues(place); + return cuePageHtml({ + id, W: region.width, H: region.height, fps, fonts: opts.fonts, gsapSrc: opts.gsap, + css: `${displayFace(opts.fonts)}\n #mv { position: absolute; left: ${home.x - region.x}px; top: ${home.y - region.y}px; width: ${home.width}px; height: ${home.height}px; transform-origin: 0 0; }\n ${css}`, + body: `<div id="mv" data-k="mv">\n ${body}\n </div>`, + init: { ...init, ...mover.init }, cues: [...cues, ...mover.cues], + whole: { total: schedule.total, from: opts.from, duration: opts.duration, ids }, primeWindow: true, + }); +}; // --------------------------------------------------------------------------- // GOALS: the sticky notes. @@ -157,7 +229,7 @@ export function goalsHtml(schedule, render, opts = {}) { 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}`)), items }; + return { html: page("goals", schedule, opts, F, css, body, init, cues, states.map((_, j) => `s${j}`), render), items }; } // --------------------------------------------------------------------------- @@ -284,7 +356,7 @@ export function peakHtml(schedule, render, opts = {}) { ${marks.join("")} ${blocks.join("\n ")} </div>`; - return { html: page("peak", schedule, opts, F, css, body, init, cues, states.map((_, j) => `s${j}`)), items }; + return { html: page("peak", schedule, opts, F, css, body, init, cues, states.map((_, j) => `s${j}`), render), items }; } // --------------------------------------------------------------------------- @@ -416,7 +488,7 @@ export function promiseHtml(schedule, render, opts = {}) { const body = `<div id="pn" data-k="pn"> ${blocks.join("\n ")} </div>`; - return { html: page("promise", schedule, opts, F, css, body, init, cues, states.map((_, j) => `s${j}`)), items }; + return { html: page("promise", schedule, opts, F, css, body, init, cues, states.map((_, j) => `s${j}`), render), items }; } // --------------------------------------------------------------------------- @@ -498,7 +570,7 @@ export function dietHtml(schedule, render, opts = {}) { const body = `<div id="pn" data-k="pn"> ${blocks.join("\n ")} </div>`; - return { html: page("diet", schedule, opts, F, css, body, init, cues, states.map((_, j) => `s${j}`)), items }; + return { html: page("diet", schedule, opts, F, css, body, init, cues, states.map((_, j) => `s${j}`), render), items }; } // --------------------------------------------------------------------------- @@ -659,5 +731,5 @@ export function streakHtml(schedule, render, opts = {}) { ${chains} ${blocks.join("\n ")} </div>`; - return { html: page("streak", schedule, opts, F, css, body, allCues.init, allCues.cues, states.map((_, j) => `s${j}`)), items }; + return { html: page("streak", schedule, opts, F, css, body, allCues.init, allCues.cues, states.map((_, j) => `s${j}`), render), items }; } diff --git a/umtool/report-to-video/chrome-story.mjs b/umtool/report-to-video/chrome-story.mjs @@ -206,6 +206,21 @@ export function chapterGeometry(render, { feed = false } = {}) { return footageBox(render, { feed }); } +/** The lower chapter band's height, design px (1920 wide). */ +export const CHAPTER_LOWER_HEIGHT = 220; + +/** + * What a chapter bumper covers in the frame while it is up: the lower band + * across the footage box's foot (`style: "lower"`), else the whole footage + * box (the card). What the measure extras move clear of. + */ +export function chapterCover(render, { feed = false } = {}) { + const f = chapterGeometry(render, { feed }); + if (resolveChapter(render).style !== "lower") return { ...f }; + const h = pxOf(render)(CHAPTER_LOWER_HEIGHT); + return { x: f.x, y: f.y + f.height - h, width: f.width, height: h }; +} + /** One chapter window's page. `window` is the snapped `{ segment, from, to }`. */ export function chapterHtml(schedule, render, window, opts = {}) { const C = resolveChapter(render); @@ -225,7 +240,7 @@ export function chapterHtml(schedule, render, window, opts = {}) { const css = ` .chapter { position: absolute; visibility: hidden; opacity: 0; display: flex; flex-direction: column; ${lower - ? `left: 0; right: 0; bottom: 0; height: ${px(220)}px; padding: ${px(26)}px ${px(48)}px; justify-content: center; + ? `left: 0; right: 0; bottom: 0; height: ${px(CHAPTER_LOWER_HEIGHT)}px; padding: ${px(26)}px ${px(48)}px; justify-content: center; background: linear-gradient(to top, ${rgba(pal.bg, 0.94)}, ${rgba(pal.bg, 0.0)});` : `inset: 0; align-items: center; justify-content: center; text-align: center; padding: ${px(60)}px; background: ${rgba(pal.bg, 0.92)};`} } diff --git a/umtool/report-to-video/cues.mjs b/umtool/report-to-video/cues.mjs @@ -229,7 +229,10 @@ export function createJsonCache({ } export function createCueSource({ - channelsDir = DEFAULT_CHANNELS_DIR, + channelsDir: ownChannelsDir = DEFAULT_CHANNELS_DIR, + // The trees to read local cues from, in order (sources.mjs channelsLayersFor: the project's, then the corpus + // behind it). Absent: `channelsDir` alone. + channelsDirs = null, siteOrigin = null, cacheDir = DEFAULT_CACHE_DIR, fetchImpl = globalThis.fetch, @@ -240,6 +243,9 @@ export function createCueSource({ resolveSiteIds = false, } = {}) { const { getJson } = createJsonCache({ cacheDir, fetchImpl, log }); + const layers = Array.isArray(channelsDirs) && channelsDirs.length ? channelsDirs : [ownChannelsDir]; + const channelsDir = layers[0]; + let saidFallback = false; async function channelEntry(origin, channelSlug) { const corpus = await getJson(`${origin}/corpus.json`); @@ -368,7 +374,7 @@ export function createCueSource({ ); } - async function checkChannelReachable(channelSlug) { + async function checkChannelReachable(channelsDir, channelSlug) { const channelDir = path.join(channelsDir, channelSlug); const dataDir = path.join(channelDir, "data"); const fail = (detail) => { @@ -441,21 +447,41 @@ export function createCueSource({ if (!link.isDirectory()) fail(`${dataDir} is neither a directory nor a symlink`); } - function assertChannelReachable(channelSlug) { - // One check per channel per run, cached as a promise so a rejection replays - // for every clip of that channel instead of re-statting for each. - let pending = checkedChannels.get(channelSlug); + function assertChannelReachable(channelsDir, channelSlug) { + // One check per channel per tree per run, cached as a promise so a rejection + // replays for every clip of that channel instead of re-statting for each. + const key = `${channelsDir}\u0000${channelSlug}`; + let pending = checkedChannels.get(key); if (!pending) { - pending = checkChannelReachable(channelSlug); - checkedChannels.set(channelSlug, pending); + pending = checkChannelReachable(channelsDir, channelSlug); + checkedChannels.set(key, pending); } return pending; } async function fromLocal(channelSlug, videoId) { + // The project's tree first; a later layer (the corpus behind it) only when that one has no cue file for it. + let lastErr = null; + for (let i = 0; i < layers.length; i += 1) { + try { + const got = await fromLocalIn(layers[i], channelSlug, videoId); + if (i > 0 && !saidFallback) { + saidFallback = true; + log(`cues: ${channelSlug}/${videoId} is not under ${layers[0]} -- read from ${layers[i]} (the corpus behind the project's channels tree; said once per run)`); + } + return got; + } catch (err) { + if (err?.code !== "ENOENT" && err?.code !== "ENOTDIR") throw err; + lastErr = err; + } + } + throw lastErr; + } + + async function fromLocalIn(channelsDir, channelSlug, videoId) { // Throws a CueLookupError — which carries no `code`, so `load`'s ENOENT // fallback rethrows it rather than reaching for the archive. - await assertChannelReachable(channelSlug); + await assertChannelReachable(channelsDir, channelSlug); // The record's DIRECTORY: a Twitch record's v<n> lives in data/<n>/ // (release 23 F1); every other id is its own directory, with no read. const p = path.join(await resolveVideoDir(channelsDir, channelSlug, videoId), "transcript.cues.json"); diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -23,7 +23,7 @@ import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs"; import { attributionParts, deckSubtitle, deckSubtitleLines, formatDeckDate } from "./attribution.mjs"; -import { postDeckText, postItemSeconds } from "./post-item.mjs"; +import { panelEntry, postDeckText, postItemSeconds, postLayout } from "./post-item.mjs"; import { videoDip, videoEnter, videoHidesChrome, videoSeconds } from "./video-entry.mjs"; import { claimOf, marksOf, originalUrlAt, resolveFactcheck, roundStamps, stampSchedule, stampsWithFinale, tallyOf, tallyVerdicts, validateFactcheck, @@ -1440,11 +1440,40 @@ export function deckSchedule({ doc, { words: measure.words ?? null, clock, gaps, asOf: measure.asOf ?? null }, ); + // Where each post item's card stands while it is up (postCovers): the + // measure extras move clear of it (measure-extras.mjs measurePlacements). + const covers = postCovers(entries, doc.segments, render, { feed: doc.layout === "feed" }); + if (covers.length) doc.covers = covers; } return doc; } /** + * The boxes each POST ITEM draws over the footage while it is up, in the + * frame: `[{ segment, from, to, rects: [{x, y, width, height}] }]` -- its card, + * and its attachments' slot and strip when it has them, as post-item.mjs + * postLayout lays them in the post box (the footage box the segment is framed + * in: build-video deckFraming; the feed's in a feed cut), with the cut's panel + * rule on (panelEntry) -- the layout the card page draws, the one check-joins' + * cardRegion reads. `from`/`to` the segment's span in the cut. + */ +export function postCovers(entries, segments, render, { feed = false } = {}) { + const box = feed ? feedGeometry(render).footage : deckGeometry(render).footage; + const r = (v) => Math.round(v); + const out = []; + entries.forEach((e, i) => { + const seg = segments[i]; + if (e?.type !== "post" || !seg || seg.id !== e.id) return; + const L = postLayout(panelEntry(e, render), { width: box.width, height: box.height }); + const rects = [L.card, L.slot, L.strip] + .filter((b) => b && [b.x, b.y, b.width, b.height].every(Number.isFinite)) + .map((b) => ({ x: r(box.x + b.x), y: r(box.y + b.y), width: r(b.width), height: r(b.height) })); + if (rects.length) out.push({ segment: e.id, from: seg.start, to: Math.round((seg.start + seg.duration) * 1000) / 1000, rects }); + }); + return out; +} + +/** * The deck's claim checks (`deck.claims`, claims.mjs) in the cut's clock: * `{ dates, items }`, or null when the deck carries none (or none in this * cut). THE arithmetic -- the build's schedule and umtool's preview both come diff --git a/umtool/report-to-video/measure-extras.mjs b/umtool/report-to-video/measure-extras.mjs @@ -26,7 +26,8 @@ // number; a null diet after one is "NO DIET" (the producer has applied the // off-scope rule: this only draws state.diet). import { deckGeometry, feedGeometry } from "./deck.mjs"; -import { resolveMeasureExtra } from "./modules/measure-extras-settings.mjs"; +import { chapterCover, chapterWindows } from "./chrome-story.mjs"; +import { MEASURE_EXTRAS, MEASURE_POSITIONS, resolveMeasureExtra } from "./modules/measure-extras-settings.mjs"; const r4 = (v) => Math.round(v * 10000) / 10000; const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); @@ -336,7 +337,8 @@ export const PROMISE_OUTCOMES = Object.freeze(["kept", "refunded", "withdrawn"]) /** * The promise clock's states: `{ at, rows: [row], asOf }`, one row (the latest * promise): `{ row, what, said, days, to, kept, outcome: { kind, date } | null, - * claim: { speaker, date, paidOn } | null, word: { text, date, speaker, his } | + * claim: { speaker, date, paidOn } | null (the first claim with a `paidOn`, else + * the first), `to` the latest of the promise's own rows' dates so far, word: { text, date, speaker, his } | * null, fresh }` -- `to` the date the days are counted to, `claim` another * party's (her) latest claim on it (CONTRACT addendum: "PAID 23 OCT BY * @MadamSavvy"), `word` the latest words said about it -- his check, her @@ -364,14 +366,15 @@ export function promiseStates(schedule, render) { const o = isObj(p.outcome) && PROMISE_OUTCOMES.includes(p.outcome.kind) ? p.outcome : null; return o ? { kind: o.kind, date: o.date ?? null } : p.kept === true ? { kind: "kept", date: null } : null; }; - const rowsAt = (s, dateNow, freshRow) => (Array.isArray(s?.promises) ? s.promises : []) + const rowsAt = (s, freshRow) => (Array.isArray(s?.promises) ? s.promises : []) .filter((p) => p && p.said) .slice(-1) .map((p) => { const ev = byRow.get(p.row); const outcome = outcomeOf(p); const claims = Array.isArray(p.claims) ? p.claims.filter((c) => isObj(c)) : []; - const c = claims[claims.length - 1] ?? null; + // "PAID <date>": the first claim that says when she paid (`paidOn`), else the first claim. + const c = claims.find((x) => typeof x.paidOn === "string" && x.paidOn) ?? claims[0] ?? null; // His checks named by the state (an older slice has no events for the words: the row's). const checks = Array.isArray(p.checks) ? p.checks : []; let word = lastWord.get(p.row) ?? null; @@ -382,7 +385,12 @@ export function promiseStates(schedule, render) { } // Kept stops the count on the day it was kept. const stop = outcome?.kind === "kept" && outcome.date ? outcome.date : null; - const to = stop ?? (dateNow && dateNow > p.said ? dateNow : p.said); + // AS OF: the latest of the promise's OWN rows so far -- the promise, its + // checks, the claims on it, its outcome -- never a later date another row + // showed earlier in cut order. + const own = [p.said, ...checks.map((r) => byRow.get(r)?.date), ...claims.map((x) => x.date), outcome?.date].filter((d) => typeof d === "string" && /^\d{4}-\d{2}-\d{2}$/.test(d)); + const latest = own.reduce((a, b) => (b > a ? b : a), p.said); + const to = stop ?? latest; return { row: p.row, what: cfg.label ?? ev?.display ?? p.what ?? "promise", @@ -397,11 +405,9 @@ export function promiseStates(schedule, render) { }; }); const out = []; - let dateNow = null; let lastSig = null; let lastS = null; for (const { e, s } of steps) { - if (e.date && (!dateNow || e.date > dateNow)) dateNow = e.date; if (e.t < first.e.t) continue; let fresh = null; if ((e.kind === "promiseCheck" || e.kind === "promiseClaim" || e.kind === "promiseOutcome") && e.promise) { @@ -411,7 +417,7 @@ export function promiseStates(schedule, render) { fresh = e.row; } } - const rows = rowsAt(s, dateNow, fresh); + const rows = rowsAt(s, fresh); lastS = s; if (!rows.length) continue; const sig = JSON.stringify(rows); @@ -428,7 +434,7 @@ export function promiseStates(schedule, render) { const from = fin ? Math.max(lastAt + 0.5, fin.from) : lastAt + PROMISE_SETTLE; const asOf = m.asOfRender; if (asOf && from < total - 0.2) { - const base = rowsAt(lastS, dateNow, null); + const base = rowsAt(lastS, null); const target = base.map((r) => (r.kept && r.outcome?.date ? r.days : Math.max(0, daysBetween(r.said, asOf) ?? 0))); const toOf = (r) => (r.kept && r.outcome?.date ? r.to : asOf); const steps2 = Math.max(0, ...target.map((d, i) => d - base[i].days)); @@ -691,3 +697,175 @@ export function measureExtraGeometry(id, render, { feed = false } = {}) { y = Math.max(0, Math.min(g.H - height, Math.round(y))); return { x, y, width, height }; } + +// --------------------------------------------------------------------------- +// MOVING CLEAR: post items' cards and chapter bands. +// --------------------------------------------------------------------------- +// +// While a post item's card (the deck schedule's `covers`, deck.mjs postCovers: +// the card, slot and strip as postLayout lays them) or a chapter band +// (chrome-story.mjs chapterCover, over chapterWindows) is up where a module +// stands, the module moves to a slot clear of it -- the anchors of the footage +// box in its preference order, a size down if it must (MEASURE_DODGE_SCALES), +// never onto another measure module that is up then -- or hides when nothing +// fits (`onPosts` / `onChapters`: "dodge" | "hide" | "show"). One pure answer +// for all five, so two modules never dodge into one slot; each module's page +// and region read their own part of it. + +/** The sizes a dodging module may take, largest first; below the last it hides. */ +export const MEASURE_DODGE_SCALES = Object.freeze([1, 0.85, 0.7, 0.6, 0.5]); + +/** How long a module takes to move clear, and back. */ +export const MEASURE_DODGE_MOVE = 0.3; + +/** The order the five are placed in (the first takes a free slot first): the promise clock, then the rest. */ +const DODGE_ORDER = Object.freeze(["promise", "goals", "peak", "diet", "streak"]); + +const intersects = (a, b) => a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height; +const within = (a, b) => a.x >= b.x && a.y >= b.y && a.x + a.width <= b.x + b.width && a.y + a.height <= b.y + b.height; +const overlapsSpan = (spans, from, to) => spans.some((sp) => sp.in < to - 1e-6 && sp.out > from + 1e-6); + +/** A module's box at an anchor of the footage box and a size (its own `scale` times `size`). */ +export function anchorRect(id, render, anchor, size = 1, { feed = false } = {}) { + const cfg = resolveMeasureExtra(id, render) ?? resolveMeasureExtra(id, { chrome: { deck: {} } }); + const g = deckGeometry(render); + const f = feed ? feedGeometry(render).footage : g.footage; + const k = (g.W / 1920) * (cfg.scale ?? 1) * size; + const box = MEASURE_BOXES[id]; + const width = Math.min(even(box.width * k), even(f.width)); + const height = Math.min(even(box.height * k), even(f.height)); + const inset = Math.round(24 * (g.W / 1920)); + const [v, h] = anchor.split("-"); + const x = h === "left" ? f.x + inset : h === "right" ? f.x + f.width - inset - width : f.x + (f.width - width) / 2; + const y = v === "top" ? f.y + inset : f.y + f.height - inset - height; + return { x: Math.round(x), y: Math.round(y), width, height }; +} + +/** The anchors a module tries when it moves: its own first, then the same edge, then the rest. */ +function anchorsFor(position) { + const [v] = position.split("-"); + const same = MEASURE_POSITIONS.filter((p) => p !== position && p.startsWith(v)); + const other = MEASURE_POSITIONS.filter((p) => p !== position && !p.startsWith(v)); + return [position, ...same, ...other]; +} + +/** When a module is up: its states' times through upSpans. */ +function upOf(id, schedule, render) { + const cfg = resolveMeasureExtra(id, render); + if (!cfg) return []; + const states = id === "goals" ? goalStates(schedule, render) + : id === "peak" ? peakStates(schedule, render) + : id === "promise" ? promiseStates(schedule, render) + : id === "diet" ? dietStates(schedule, render) + : streakStates(schedule, render).states; + return upSpans(states.map((s) => s.at), cfg, schedule); +} + +/** + * What covers the footage when: `[{ kind: "post" | "chapter", from, to, rects }]`, + * the post items' cards (the schedule's `covers`) and the chapter bands. + */ +export function measureCovers(schedule, render) { + const feed = schedule?.layout === "feed"; + const out = []; + for (const c of Array.isArray(schedule?.covers) ? schedule.covers : []) { + if (Number.isFinite(c?.from) && Number.isFinite(c?.to) && Array.isArray(c.rects) && c.rects.length) out.push({ kind: "post", from: c.from, to: c.to, rects: c.rects }); + } + const chapters = render?.chrome?.chapter ? chapterWindows(schedule, render) : []; + if (chapters.length) { + const band = chapterCover(render, { feed }); + for (const w of chapters) out.push({ kind: "chapter", from: w.from, to: w.to, rects: [band] }); + } + return out.sort((a, b) => a.from - b.from); +} + +/** + * Every measure module's placement over the cut: `{ [id]: { home, region, + * moves: [{ from, to, rect | null, size }] } }` -- `home` where it stands, + * each move a span it stands elsewhere (`rect` at `size`) or is hidden + * (`rect` null), `region` the box its frames are drawn in (home and every + * slot it moves to). A module with nothing to move clear of: its home alone. + */ +export function measurePlacements(schedule, render) { + const feed = schedule?.layout === "feed"; + const covers = schedule ? measureCovers(schedule, render) : []; + const out = {}; + for (const id of MEASURE_EXTRAS) { + const home = measureExtraGeometry(id, render, { feed }); + out[id] = { home, region: home, moves: [], up: covers.length && schedule && resolveMeasureExtra(id, render) ? upOf(id, schedule, render) : [] }; + } + // Two extras whose homes overlap (the clip box is smaller beside the + // instruments' column) while both are up: the later in DODGE_ORDER moves + // clear of the earlier, as of a cover of its own. + if (schedule) { + for (const id of MEASURE_EXTRAS) if (!out[id].up.length && resolveMeasureExtra(id, render)) out[id].up = upOf(id, schedule, render); + DODGE_ORDER.forEach((a, i) => { + for (const b of DODGE_ORDER.slice(i + 1)) { + if (!resolveMeasureExtra(a, render) || !resolveMeasureExtra(b, render) || !intersects(out[a].home, out[b].home)) continue; + for (const sa of out[a].up) for (const sb of out[b].up) { + const from = Math.max(sa.in, sb.in); + const to = Math.min(sa.out, sb.out); + if (to - from > 1e-3) covers.push({ kind: "module", only: b, from, to, rects: [out[a].home] }); + } + } + }); + covers.sort((x, y) => x.from - y.from); + } + for (const c of covers) { + const hit = (r) => c.rects.some((b) => intersects(r, b)); + const active = DODGE_ORDER.filter((id) => resolveMeasureExtra(id, render) && overlapsSpan(out[id].up, c.from, c.to) && (!c.only || c.only === id)); + // The modules that stay where they are take their homes first. + const taken = []; + const toMove = []; + for (const id of active) { + const cfg = resolveMeasureExtra(id, render); + const mode = c.kind === "post" ? cfg.onPosts : c.kind === "chapter" ? cfg.onChapters : "dodge"; + if (mode === "show" || !hit(out[id].home)) taken.push(out[id].home); + else toMove.push({ id, cfg, mode }); + } + // Every other extra up in the span keeps its place: no slot onto it. + for (const id of DODGE_ORDER) { + if (active.includes(id) || !resolveMeasureExtra(id, render) || !overlapsSpan(out[id].up, c.from, c.to)) continue; + taken.push(out[id].home); + } + const footage = feed ? feedGeometry(render).footage : deckGeometry(render).footage; + for (const { id, cfg, mode } of toMove) { + let move = null; + if (mode === "dodge") { + const pinned = Number.isFinite(cfg.x) && Number.isFinite(cfg.y); + const anchors = anchorsFor(pinned ? "top-left" : cfg.position); + search: for (const size of MEASURE_DODGE_SCALES) { + for (const a of anchors) { + const r = anchorRect(id, render, a, size, { feed }); + if (!within(r, footage) || hit(r) || taken.some((t) => intersects(t, r))) continue; + move = { from: c.from, to: c.to, rect: r, size }; + break search; + } + } + } + if (!move) move = { from: c.from, to: c.to, rect: null, size: 1 }; + else taken.push(move.rect); + out[id].moves.push(move); + } + } + for (const id of MEASURE_EXTRAS) { + const p = out[id]; + // Two moves that meet, to the same place: one. + const merged = []; + for (const m of p.moves.sort((a, b) => a.from - b.from)) { + const last = merged[merged.length - 1]; + const same = last && JSON.stringify(last.rect) === JSON.stringify(m.rect) && last.size === m.size; + if (same && m.from - last.to < MEASURE_DODGE_MOVE * 2 + 0.05) last.to = Math.max(last.to, m.to); + else merged.push({ ...m }); + } + p.moves = merged; + const rects = [p.home, ...merged.map((m) => m.rect).filter(Boolean)]; + const x0 = Math.min(...rects.map((r) => r.x)); + const y0 = Math.min(...rects.map((r) => r.y)); + const x1 = Math.max(...rects.map((r) => r.x + r.width)); + const y1 = Math.max(...rects.map((r) => r.y + r.height)); + p.region = { x: x0, y: y0, width: even(x1 - x0), height: even(y1 - y0) }; + delete p.up; + } + return out; +} diff --git a/umtool/report-to-video/measure-extras.test.mjs b/umtool/report-to-video/measure-extras.test.mjs @@ -9,12 +9,12 @@ import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; -import { goalsHtml, dietHtml, peakHtml, promiseHtml, spreadLabels, stampSize, streakHtml } from "./chrome-measure-extras.mjs"; +import { goalsHtml, dietHtml, moverCues, moverSteps, peakHtml, promiseHtml, spreadLabels, stampSize, streakHtml } from "./chrome-measure-extras.mjs"; import { cuePageHtml } from "./chrome-cues.mjs"; import { estimateSchedule, validateChrome } from "./deck.mjs"; import { frameKeys } from "./frame-keys.mjs"; import { - daysBetween, deadlineDate, dietRuns, dietStates, goalStates, goalText, lostRunsRuns, measureExtraGeometry, peakStates, pledgeRuns, + daysBetween, deadlineDate, dietRuns, dietStates, goalStates, goalText, lostRunsRuns, measureExtraGeometry, measurePlacements, peakStates, pledgeRuns, promiseStates, streakStates, upSpans, } from "./measure-extras.mjs"; import { deckOverlays, moduleById, moduleProblems, playModules, scheduleSlices } from "./modules/index.mjs"; @@ -95,7 +95,10 @@ test("peak: a tick per telling of a start in the drift, a count per retelling, t test("promise: the days to the clip's in-record date, her claim and the outcome, the words flashed, then counted on to the render date", () => { const states = promiseStates(schedule(), RENDER); - assert.deepEqual(states.map((s) => s.rows[0].days), [0, 1, 8, 8, 11, 12, 13]); + // AS OF is the promise's own rows' latest date: the goal said on 31 Oct between them moves nothing. + // (The goal's state at 720.09 is its own only because her words stop flashing there.) + assert.deepEqual(states.map((s) => s.rows[0].days), [0, 1, 1, 8, 11, 12, 13]); + assert.deepEqual(states.map((s) => s.rows[0].to), ["2026-10-23", "2026-10-24", "2026-10-24", "2026-10-31", "2026-11-03", "2026-11-05", "2026-11-05"]); assert.equal(states[0].at, 712.18, "from the promise on"); assert.equal(states[0].rows[0].what, "scale video"); assert.equal(states[0].rows[0].claim, null); @@ -122,6 +125,18 @@ test("promise: the days to the clip's in-record date, her claim and the outcome, const kept = promiseStates(schedule(m), RENDER); assert.equal(kept.at(-1).rows[0].kept, true); assert.equal(kept.at(-1).rows[0].days, 8, "stopped on 31 Oct"); + // PAID: the first claim that carries a paidOn (s01 23 Oct), not the latest claim's date. + const paid = clone(MEASURE); + for (const s of paid.state) for (const p of s.promises ?? []) { + if (p.claims?.length) p.claims = [{ row: "s01", speaker: "madamsavvy", date: "2026-10-23", paidOn: "2026-10-23" }, { row: "s02", speaker: "madamsavvy", date: "2026-10-24" }, { row: "s03", speaker: "madamsavvy", date: "2026-10-25" }]; + } + const ps = promiseStates(schedule(paid), RENDER); + assert.deepEqual(ps[1].rows[0].claim, { speaker: "madamsavvy", date: "2026-10-23", paidOn: "2026-10-23" }); + assert.equal(ps[1].rows[0].to, "2026-10-25", "AS OF: the latest of its own rows, the claims' too"); + // No paidOn anywhere: the first claim, by its date. + const unpaid = clone(paid); + for (const s of unpaid.state) for (const p of s.promises ?? []) for (const c of p.claims ?? []) delete c.paidOn; + assert.equal(promiseStates(schedule(unpaid), RENDER)[1].rows[0].claim.date, "2026-10-23"); // An older slice's `kept: true` reads as kept. const old = clone(MEASURE); for (const s of old.state) for (const p of s.promises ?? []) { delete p.outcome; p.kept = true; } @@ -290,3 +305,78 @@ test("a deck cut without a measure slice renders exactly as before: none of the assert.deepEqual(validateChrome(chrome, rest), []); } }); + +// --------------------------------------------------------------------------- +// Moving clear of post items' cards and chapter bands (rev 9 fixes, 6 Nov). +// --------------------------------------------------------------------------- + +test("postCovers: a post item's card (and slot) as postLayout lays it in the footage box, over its segment's span", async () => { + const { postCovers, deckGeometry } = await import("./deck.mjs"); + const { postLayout, panelEntry } = await import("./post-item.mjs"); + const post = { type: "post", id: "p1", platform: "x", author: { handle: "a", name: "A" }, date: "2026-10-23", text: "Ok I bought your coffee." }; + const covers = postCovers([{ type: "clip", id: "c1" }, post], [{ id: "c1", start: 0, duration: 5 }, { id: "p1", start: 4.6, duration: 9 }], RENDER); + assert.equal(covers.length, 1); + const f = deckGeometry(RENDER).footage; + const L = postLayout(panelEntry(post, RENDER), { width: f.width, height: f.height }); + assert.deepEqual(covers[0], { segment: "p1", from: 4.6, to: 13.6, rects: [{ x: f.x + L.card.x, y: f.y + L.card.y, width: L.card.width, height: L.card.height }] }); +}); + +test("measurePlacements: over a post card a module moves to a free slot (a size down if it must), hides when none fits; over a chapter band likewise", () => { + const f = { x: 173, y: 2, width: 1574, height: 886 }; + // A card down the middle, leaving ~300 px each side. + const card = { x: 476, y: 38, width: 968, height: 814 }; + const sched = schedule(MEASURE, { covers: [{ segment: "p1", from: 715, to: 725, rects: [card] }] }); + const p = measurePlacements(sched, RENDER); + const moveAt = (id, t) => p[id].moves.find((m) => m.from <= t && m.to > t) ?? null; + // The promise clock (640 wide, up from 712) cannot fit beside the card: hidden there. + assert.deepEqual(moveAt("promise", 720), { from: 715, to: 725, rect: null, size: 1 }); + // The diet badge (bottom-left, 440 wide) moves to a slot clear of the card, a size down. + const d = moveAt("diet", 720); + assert.ok(d.rect && d.size < 1, JSON.stringify(d)); + assert.ok(d.rect.x + d.rect.width <= card.x || d.rect.x >= card.x + card.width, "clear of the card"); + assert.ok(d.rect.x >= f.x && d.rect.x + d.rect.width <= f.x + f.width, "inside the footage box"); + // Its region holds home and the slot. + assert.ok(p.diet.region.x <= d.rect.x && p.diet.region.y <= d.rect.y); + // A module whose home is clear stays: none. + const free = measurePlacements(schedule(MEASURE, { covers: [{ segment: "p1", from: 715, to: 725, rects: [{ x: 700, y: 300, width: 400, height: 200 }] }] }), RENDER); + assert.equal(free.diet.moves.length, 0); + // onPosts: "hide" hides, "show" stays. + assert.equal(measurePlacements(sched, withDeck({ diet: { onPosts: "hide" } })).diet.moves[0].rect, null); + assert.equal(measurePlacements(sched, withDeck({ diet: { onPosts: "show" } })).diet.moves.length, 0); + // A chapter band (lower) at the foot of the footage: the bottom modules move up. + const chap = withDeck({}); + chap.chrome = { ...chap.chrome, chapter: { style: "lower", seconds: 3, list: [{ at: "a", title: "Part one" }] } }; + const cp = measurePlacements(schedule(MEASURE, { segments: [{ id: "a", start: 700, duration: 40, end: 740 }] }), chap); + const band = cp.diet.moves.find((m) => m.from === 700); + assert.ok(band?.rect && band.rect.y + band.rect.height <= f.y + f.height - Math.round(220), JSON.stringify(band)); + // Nothing to move clear of: home alone. + assert.deepEqual(measurePlacements(schedule(), RENDER).diet.region, measureExtraGeometry("diet", RENDER)); +}); + +test("moverSteps: overlapping moves (two post items crossfading, a band inside a post) are one step function -- hide wins, else the latest", () => { + const r = { x: 10, y: 10, width: 100, height: 50 }; + assert.deepEqual(moverSteps([{ from: 1, to: 5, rect: null }, { from: 4.6, to: 9, rect: null }]), [{ at: 1, to: "hide" }, { at: 9, to: "home" }]); + assert.deepEqual(moverSteps([{ from: 1, to: 5, rect: r, size: 0.6 }, { from: 2, to: 3, rect: null }]), [ + { at: 1, to: { x: 10, y: 10, size: 0.6 } }, { at: 2, to: "hide" }, { at: 3, to: { x: 10, y: 10, size: 0.6 } }, { at: 5, to: "home" }, + ]); + // The cues: a hidden mover is put in place at once, then faded in. + const { cues } = moverCues({ home: { x: 0, y: 0, width: 100, height: 50 }, moves: [{ from: 1, to: 5, rect: null }, { from: 4.6, to: 9, rect: r, size: 0.6 }] }); + assert.ok(cues.every((c, i, a) => i === 0 || c.at >= a[i - 1].at)); + assert.equal(cues[0].to.autoAlpha, 0); + assert.deepEqual(cues.find((c) => c.to.x === 10).to, { x: 10, y: 10, scale: 0.6 }); +}); + +test("measurePlacements beside the instruments' column (the clip box 1248×702): extras whose homes overlap move clear of each other while both are up", () => { + const r = withDeck({ dial: true }); + const p = measurePlacements(schedule(), r); + const homes = Object.fromEntries(IDS.map((id) => [id, measureExtraGeometry(id, r)])); + const box = { x: 24, y: 94, width: 1248, height: 702 }; + for (const id of IDS) assert.ok(homes[id].x >= box.x && homes[id].x + homes[id].width <= box.x + box.width, `${id} inside the clip box`); + // diet and streak overlap at home: the streak (later in the order) moves, the diet stays. + assert.equal(p.diet.moves.length, 0); + assert.ok(p.streak.moves.length > 0); + for (const m of p.streak.moves.filter((x) => x.rect)) { + assert.ok(!(m.rect.x < homes.diet.x + homes.diet.width && homes.diet.x < m.rect.x + m.rect.width && m.rect.y < homes.diet.y + homes.diet.height && homes.diet.y < m.rect.y + m.rect.height), "never onto the diet badge"); + assert.ok(m.rect.x >= box.x && m.rect.x + m.rect.width <= box.x + box.width, "inside the clip box"); + } +}); diff --git a/umtool/report-to-video/modules/measure-extras-module.mjs b/umtool/report-to-video/modules/measure-extras-module.mjs @@ -7,10 +7,10 @@ // file says only what is its own. import path from "node:path"; -import { measureExtraGeometry, measureOf } from "../measure-extras.mjs"; +import { measureExtraGeometry, measureOf, measurePlacements } from "../measure-extras.mjs"; import { assertRegion, defineModule } from "./contract.mjs"; import { - MEASURE_DEFAULTS, MEASURE_FINALE, MEASURE_LIMITS, MEASURE_POSITIONS, resolveMeasureExtra, + MEASURE_AVOID, MEASURE_DEFAULTS, MEASURE_FINALE, MEASURE_LIMITS, MEASURE_POSITIONS, resolveMeasureExtra, } from "./measure-extras-settings.mjs"; import { settingsOf } from "./settings.mjs"; @@ -23,6 +23,8 @@ const commonUi = (id) => [ { key: "scale", type: "number", min: MEASURE_LIMITS.scale[0], max: MEASURE_LIMITS.scale[1], step: 0.05, label: "Scale", default: 1 }, { key: "hold", type: "number", min: MEASURE_LIMITS.hold[0], max: MEASURE_LIMITS.hold[1], label: "Seconds up after each event (0: stays up)", ...(MEASURE_DEFAULTS[id].hold !== null ? { default: MEASURE_DEFAULTS[id].hold } : {}) }, { key: "finale", type: "enum", options: MEASURE_FINALE, label: "Over the finale", default: MEASURE_DEFAULTS[id].finale }, + { key: "onPosts", type: "enum", options: MEASURE_AVOID, label: "Over a post item's card", default: "dodge" }, + { key: "onChapters", type: "enum", options: MEASURE_AVOID, label: "Over a chapter band", default: "dodge" }, ]; /** @@ -49,7 +51,13 @@ export function measureExtraModule(spec) { validate: settingsOf(id).validate, resolve: (render) => resolveMeasureExtra(id, render), ui: [...commonUi(id), ...(spec.ui ?? [])], - docs: { heading: spec.title, intro: spec.docs.intro, rows: spec.docs.rows }, + docs: { + heading: spec.title, intro: spec.docs.intro, + rows: [ + ...spec.docs.rows, + [`\`deck.${id}.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.${id}.onPosts=hide\``], + ], + }, region: id, workers: "narrow", noun: `the ${spec.title.toLowerCase()}'s`, @@ -71,7 +79,8 @@ export function measureExtraModule(spec) { regions(schedule, { render, outDir, frames = null }) { return [assertRegion({ name: id, frames: frames ?? path.join(outDir, "chrome", `${id}-frames`), - ...measureExtraGeometry(id, render, { feed: schedule.layout === "feed" }), + // Its home, and every slot it moves clear to (a post card, a chapter band: measurePlacements). + ...measurePlacements(schedule, render)[id].region, })]; }, preview: (_slice, { render }) => ({ region: id, geometry: measureExtraGeometry(id, render) }), diff --git a/umtool/report-to-video/modules/measure-extras-settings.mjs b/umtool/report-to-video/modules/measure-extras-settings.mjs @@ -31,6 +31,13 @@ /** The anchors in the footage box a module may sit at (`position`). */ export const MEASURE_POSITIONS = Object.freeze(["top-left", "top-right", "bottom-left", "bottom-right", "top-center", "bottom-center"]); +/** + * What a module does when a post item's card (`onPosts`) or a chapter band + * (`onChapters`) is up where it stands: moves to a slot clear of it (a size + * down if it must, hidden when nothing fits), hides, or stays (drawn over it). + */ +export const MEASURE_AVOID = Object.freeze(["dodge", "hide", "show"]); + /** What a module does over the finale's window (`finale`): hidden under it, or drawn over it. */ export const MEASURE_FINALE = Object.freeze(["hide", "show"]); @@ -72,7 +79,7 @@ export const MEASURE_LIMITS = Object.freeze({ quote: 160, }); -const COMMON = Object.freeze({ show: true, position: "top-left", x: null, y: null, scale: 1, hold: null, finale: "hide" }); +const COMMON = Object.freeze({ show: true, position: "top-left", x: null, y: null, scale: 1, hold: null, finale: "hide", onPosts: "dodge", onChapters: "dodge" }); /** Each module's settings and their defaults. */ export const MEASURE_DEFAULTS = Object.freeze({ @@ -166,6 +173,9 @@ export function validateMeasureExtra(id, v, where = `render.chrome.deck.${id}`) errors.push(`${where}.hold must be 0 (up from its first event on) or from ${L.hold[0]} to ${L.hold[1]} seconds`); } if (v.finale !== undefined && !MEASURE_FINALE.includes(v.finale)) errors.push(`${where}.finale must be "hide" or "show"`); + for (const k of ["onPosts", "onChapters"]) { + if (v[k] !== undefined && !MEASURE_AVOID.includes(v[k])) errors.push(`${where}.${k} must be "dodge", "hide" or "show"`); + } if (id === "goals") { if (v.max !== undefined && !(Number.isInteger(v.max) && numIn(v.max, L.max[0], L.max[1]))) { errors.push(`${where}.max must be a whole number from ${L.max[0]} to ${L.max[1]}`); diff --git a/umtool/report-to-video/narrate-via-editor.mjs b/umtool/report-to-video/narrate-via-editor.mjs @@ -266,7 +266,17 @@ export function opResultIn(lines) { * line, null when the op writes none and `out` is given). An op the editor * has no engine for throws OpNotInstalled. */ -export async function askEditorOp(route, body, { editor = editorFromEnv(), emit = () => {}, pollMs = POLL_MS, onJob = () => {} } = {}) { +/** An op that did not finish by its deadline (`askEditorOp`'s `deadlineMs`): its job may still be in the editor's queue. */ +export class OpDeadline extends Error { + constructor(route, jobId, ms) { + super(`the editor's ${route} job ${jobId} did not finish within ${Math.round(ms / 1000)} s (it may still be queued there)`); + this.name = "OpDeadline"; + this.jobId = jobId; + } +} + +export async function askEditorOp(route, body, { editor = editorFromEnv(), emit = () => {}, pollMs = POLL_MS, onJob = () => {}, deadlineMs = null } = {}) { + const started = Date.now(); const headers = { authorization: `Bearer ${editor.token}`, "content-type": "application/json" }; const reach = async (url, init) => { try { @@ -309,6 +319,8 @@ export async function askEditorOp(route, body, { editor = editorFromEnv(), emit place = line; } if (status === "queued" || status === "running") { + // A caller that must not wait unbounded (a beep's word timing behind a held lane) gives up here. + if (deadlineMs !== null && Date.now() - started >= deadlineMs) throw new OpDeadline(route, jobId, deadlineMs); await sleep(pollMs); continue; } diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -129,9 +129,87 @@ export const ownPictureOnly = (entry) => isPictureOnly(entry, { text: cardText(e /** Whether a context post (a parent, the quoted post) is picture-only (post-picture.mjs). */ export const refPictureOnly = (ref) => isPictureOnly(ref); -/** Seconds to read the post itself (the rule above, its first line). */ +// --------------------------------------------------------------------------- +// THE EXCERPT (rev 9, 6 Nov): a long post read in part. `entry.excerpt` is one +// or more VERBATIM spans of the post's words, in order; the read (the +// narration script drafted for it, an un-narrated card's reading time) is +// those spans joined with " … ", and the card still shows the WHOLE post -- +// the spans read lit, the rest dimmed -- so it never hides that text was cut. +// --------------------------------------------------------------------------- + +/** The excerpt's join: what stands between two spans in the read. */ +export const POST_EXCERPT_JOIN = " … "; +/** At most this many spans. */ +export const POST_EXCERPT_MAX = 8; + +/** The excerpt's spans (`entry.excerpt`, the strings), or null when it has none. */ +export const excerptSpansOf = (entry) => (Array.isArray(entry?.excerpt) && entry.excerpt.length && entry.excerpt.every((x) => typeof x === "string" && x.trim()) ? entry.excerpt : null); + +/** + * Where each span stands in `text`, in order -- `[{ start, end }]` (character + * offsets; each found at or after the end of the one before) -- or null when a + * span is not in the text there. + */ +export function excerptRanges(text, spans) { + const t = str(text); + const out = []; + let from = 0; + for (const sp of spans) { + const at = t.indexOf(sp, from); + if (at < 0) return null; + out.push({ start: at, end: at + sp.length }); + from = at + sp.length; + } + return out; +} + +/** What is READ of a post: its excerpt's spans joined with " … ", else the card's words whole. */ +export function postReadText(entry) { + const spans = excerptSpansOf(entry); + return spans && excerptRanges(cardText(entry), spans) ? spans.map((x) => x.trim()).join(POST_EXCERPT_JOIN) : cardText(entry); +} + +/** The card's word indices (cardTokens') that the excerpt does NOT read (drawn dimmed), or null with no excerpt. */ +export function excerptCutWords(entry) { + const spans = excerptSpansOf(entry); + const text = cardText(entry); + const ranges = spans ? excerptRanges(text, spans) : null; + if (!ranges) return null; + const cut = new Set(); + let at = 0; + for (const t of cardTokens(text)) { + const len = (t.space ?? t.tok).length; + if (t.tok !== undefined && !ranges.some((r) => at < r.end && at + len > r.start)) cut.add(t.i); + at += len; + } + return cut; +} + +/** Every reason `entry.excerpt` cannot be read (empty: it can). */ +export function excerptErrors(entry, where = `timeline ${entry?.id ?? "?"}.excerpt`) { + const x = entry?.excerpt; + if (x === undefined) return []; + if (!Array.isArray(x) || !x.length) return [`${where} must be a list of the post's own words to read (one or more spans)`]; + if (x.length > POST_EXCERPT_MAX) return [`${where}: at most ${POST_EXCERPT_MAX} spans`]; + const errors = []; + x.forEach((sp, i) => { if (typeof sp !== "string" || !sp.trim()) errors.push(`${where}[${i}] must be words of the post`); }); + if (errors.length) return errors; + const text = cardText(entry); + let from = 0; + x.forEach((sp, i) => { + const at = str(text).indexOf(sp, from); + if (at < 0) { + errors.push(str(text).includes(sp) + ? `${where}[${i}] "${sp.slice(0, 40)}" is in the post, but before the span ahead of it (the spans go in the post's order)` + : `${where}[${i}] "${sp.slice(0, 40)}" is not in the post's words (an excerpt is verbatim)`); + } else from = at + sp.length; + }); + return errors; +} + +/** Seconds to read the post itself (the rule above, its first line): its excerpt when it has one. */ export function readSeconds(entry) { - return clamp(POST_READ.lead + wordCount(cardText(entry)) / POST_READ.wps, POST_READ.min, POST_READ.max); + return clamp(POST_READ.lead + wordCount(postReadText(entry)) / POST_READ.wps, POST_READ.min, POST_READ.max); } /** Whether a context post (a parent, the quoted post) is drawn as the operator's paraphrase. */ @@ -573,6 +651,7 @@ export function validatePostItem(e) { if (!POST_ITEM_PLATFORMS.includes(e.platform)) errors.push(`${w}.platform must be one of ${POST_ITEM_PLATFORMS.join(", ")}`); if (typeof e.text !== "string") errors.push(`${w}.text must be the post's words (a string; "" for none)`); else if (e.text.length > TEXT_MAX) errors.push(`${w}.text is longer than ${TEXT_MAX} characters`); + if (typeof e.text === "string") errors.push(...excerptErrors(e, `${w}.excerpt`)); if (e.author !== undefined && typeof e.author !== "string") errors.push(`${w}.author must be a string`); if (e.handle !== undefined && (typeof e.handle !== "string" || !HANDLE_RE.test(e.handle))) errors.push(`${w}.handle must be a handle`); if (typeof e.date !== "string" || Number.isNaN(Date.parse(e.date))) errors.push(`${w}.date must be the post's date (ISO)`); @@ -997,7 +1076,7 @@ export const hueOf = (s) => { * and Play zooms toward it; `hl` (`{ from, to }`) marks those words' * spans `data-w-hl` (the zoom's highlight is drawn under them). */ -export function wordsHtml(text, blurred, scope = null, hl = null, blocks = null) { +export function wordsHtml(text, blurred, scope = null, hl = null, blocks = null, cut = null) { const set = new Set(blurred.map((h) => h.replace(/^@/, "").toLowerCase())); const word = (t) => esc(t) @@ -1016,7 +1095,8 @@ export function wordsHtml(text, blurred, scope = null, hl = null, blocks = null) if (t.space !== undefined) return t.space.replace(/[^\n]+/g, " ").replace(/\n/g, "<br>"); const lit = hl && t.i >= hl.from && t.i <= hl.to; const open = opens.has(t.i) ? `<span class="fblock" data-post-block="${opens.get(t.i)}">` : ""; - return `${open}<span data-w="${esc(scope)}:${t.i}"${lit ? " data-w-hl=\"\"" : ""}>${word(t.tok)}</span>${closes.has(t.i) ? "</span>" : ""}`; + // `cut` (excerptCutWords): a word the excerpt does not read, drawn dimmed. + return `${open}<span data-w="${esc(scope)}:${t.i}"${lit ? " data-w-hl=\"\"" : ""}${cut?.has(t.i) ? ' class="xcut" data-post-cut=""' : ""}>${word(t.tok)}</span>${closes.has(t.i) ? "</span>" : ""}`; }) .join(""); } @@ -1202,7 +1282,9 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p : ""; const head = `<div class="head"${ownRed ? ' data-redacted=""' : ""}>${avatarHtml(own, { redact: ownRed, size: Math.round(64 * k), accent: ownRed ? undefined : pal.accent, img: pic(own) })}<div class="hwho">${nameHtml(own, { redact: ownRed, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="mark">${esc(PLATFORM_NAME[entry.platform] ?? "")}</div></div>`; // A card alone (text, or a stack's reading) is as tall as its words, centred in its box; beside the attachments, the box's height. - const card = (box) => `<div class="card" data-post-card="${esc(entry.id)}" style="left:${box.x}px;${L.mode === "side" ? `top:${box.y}px;height:${box.height}px` : `top:${box.y + box.height / 2}px;transform:translateY(-50%);max-height:${box.height}px`};width:${box.width}px">${repost}${ctx.length ? `<div class="context">${ctx.join("")}</div>` : ""}${head}<div class="words${picOwn ? " pmen" : ""}" data-post-words="" style="font-size:${picOwn ? menSize : size}px">${follow ? `<div class="wflow" data-post-flow="">${wordsHtml(cardText(entry), blurred, "post", hlOf("post"), blk("post"))}</div><div class="wfade" data-post-fade="top"></div><div class="wfade" data-post-fade="bottom"></div>` : wordsHtml(cardText(entry), blurred, "post", hlOf("post"))}</div>${picOwn ? picIn("post", entry, L.card.width - 2 * L.pad, ownPicMax) : ""}${quoted}${counts ? `<div class="counts" data-post-counts="">${counts}</div>` : ""}</div>`; + // The excerpt (excerptCutWords): the whole post drawn, the words it does not read dimmed. + const excerptCut = excerptCutWords(entry); + const card = (box) => `<div class="card" data-post-card="${esc(entry.id)}" style="left:${box.x}px;${L.mode === "side" ? `top:${box.y}px;height:${box.height}px` : `top:${box.y + box.height / 2}px;transform:translateY(-50%);max-height:${box.height}px`};width:${box.width}px">${repost}${ctx.length ? `<div class="context">${ctx.join("")}</div>` : ""}${head}<div class="words${picOwn ? " pmen" : ""}" data-post-words="" style="font-size:${picOwn ? menSize : size}px">${follow ? `<div class="wflow" data-post-flow="">${wordsHtml(cardText(entry), blurred, "post", hlOf("post"), blk("post"), excerptCut)}</div><div class="wfade" data-post-fade="top"></div><div class="wfade" data-post-fade="bottom"></div>` : wordsHtml(cardText(entry), blurred, "post", hlOf("post"), null, excerptCut)}</div>${picOwn ? picIn("post", entry, L.card.width - 2 * L.pad, ownPicMax) : ""}${quoted}${counts ? `<div class="counts" data-post-counts="">${counts}</div>` : ""}</div>`; const stripHtml = L.strip ? `<div class="strip" data-post-strip="" style="left:${L.strip.x}px;top:${L.strip.y}px;width:${L.strip.width}px;height:${L.strip.height}px">${avatarHtml(own, { redact: ownRed, size: Math.round(56 * k), accent: ownRed ? undefined : pal.accent, img: pic(own) })}<div class="hwho">${nameHtml(own, { redact: ownRed, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="sline">${wordsHtml(cardText(entry).split("\n")[0].slice(0, 140) + (cardText(entry).length > 140 ? "…" : ""), blurred)}</div></div>` : ""; @@ -1355,6 +1437,7 @@ b, .name, .mark { font-family: 'PostSansBold', sans-serif; font-weight: 400; } .words { line-height: ${LINE}; overflow-wrap: anywhere; flex: 0 1 auto; min-height: 0; overflow: hidden; } .sline { margin-left: ${Math.round(12 * k)}px; color: ${pal.fg}; font-size: ${Math.round(24 * k)}px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 1; } .mention, .link { color: ${pal.accent}; } +.xcut { opacity: 0.38; } .context { display: flex; flex-direction: column; gap: ${Math.round(10 * k)}px; } .parent { display: flex; gap: ${Math.round(14 * k)}px; position: relative; padding-bottom: ${Math.round(6 * k)}px; } .parent::after { content: ""; position: absolute; left: ${Math.round(21 * k)}px; top: ${Math.round(50 * k)}px; bottom: -${Math.round(6 * k)}px; width: 2px; background: ${line}; } diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -7,7 +7,7 @@ // // entry.narration = { // script: "what is read (Orpheus tags <sigh> <laugh> … allowed)", -// excerpt?: true, // drafted as an excerpt of a longer post +// excerpt?: true, // drafted from the item's `excerpt` (post-item.mjs: verbatim spans, " … "-joined) // engine?, voice?, speed?, // the next take's (default: render.postNarration's) // takes: [{ file: "narration/posts/<postId>/take-<n>.<engine>-<voice>.wav", // engine, voice, seconds, script, at, note?, speed?, lufs?, jobId?, @@ -157,7 +157,7 @@ export const POST_NARRATION_LIMITS = Object.freeze({ rate: [0.8, 1.5], /** A part's own tempo (a `tempo` step: the part time-stretched in the take's file, its pitch kept). */ tempo: [1, 1.6], - /** A script is the whole post read aloud (operator, 2 Nov: never excerpted); the editor's tts op takes 20,000. */ + /** A script is the whole post read aloud (operator, 2 Nov) -- or its `excerpt`'s spans (post-item.mjs, 6 Nov), the card showing the whole post; the editor's tts op takes 20,000. */ scriptChars: 20000, takes: 50, }); @@ -536,8 +536,9 @@ export function speakableText(text) { } /** - * A DRAFT SCRIPT from the post's words: the whole post (speakableText), never - * an excerpt. Emotion is the operator's to add (Orpheus's tags, <sigh> …). + * A DRAFT SCRIPT from the words it is given: the whole post (speakableText) -- + * or, from the CLI, its `excerpt`'s spans (post-item.mjs postReadText). Emotion + * is the operator's to add (Orpheus's tags, <sigh> …). * * @returns {{ script: string, words: number }} */ diff --git a/umtool/report-to-video/sources.mjs b/umtool/report-to-video/sources.mjs @@ -60,6 +60,7 @@ // root arrives as an argument (see umtool/lib/paths.mjs on why that matters to // the Next build). import path from "node:path"; +import { stat } from "node:fs/promises"; import { AUDIO_ONLY_PLATFORMS, CORPUS_TIERS, @@ -182,6 +183,15 @@ export const TIERS = [{ kind: "raw-cache", windows: rawCacheWindows }, ...CORPUS * windowStart: number, windowEnd: number, height?: number }>} */ export async function resolveLocalSource(want, config = {}) { + const hit = await resolveLocalSourceIn(want, config); + // The corpus behind the project's channels tree (channelsLayersFor): its windows when the project's has none. + if (hit || !config.fallbackChannelsDir || config.exact) return hit; + const behind = await resolveLocalSourceIn(want, { ...config, channelsDir: config.fallbackChannelsDir, kinds: (config.kinds ?? CORPUS_TIERS.map((t) => t.kind)).filter((k) => k !== "raw-cache") }); + if (behind) noteChannelsFallback("windows", `windows: ${want.slug ?? "?"}/${want.video} ${want.from}-${want.to} is not in ${config.channelsDir} -- read from ${config.fallbackChannelsDir} (the corpus behind the project's channels tree)`, config.log); + return behind; +} + +async function resolveLocalSourceIn(want, config = {}) { const { video, slug = null, from, to } = want; const { rawDir = null, channelsDir = null, exact = false, probe, kinds = null, audio = false } = config; if (!video || !Number.isFinite(from) || !Number.isFinite(to)) return null; @@ -216,7 +226,13 @@ export async function resolveLocalSource(want, config = {}) { * Not the audio tier: many transcribed videos keep their sound, and a * bench that called each of those "fetched" would never offer a fetch. */ -export async function corpusWindowsOf({ video, slug, channelsDir, probe = ffprobeSource }) { +export async function corpusWindowsOf({ video, slug, channelsDir, probe = ffprobeSource, fallbackChannelsDir = null }) { + const own = await corpusWindowsIn({ video, slug, channelsDir, probe }); + if (own.length || !fallbackChannelsDir) return own; + return corpusWindowsIn({ video, slug, channelsDir: fallbackChannelsDir, probe }); +} + +async function corpusWindowsIn({ video, slug, channelsDir, probe }) { const ctx = { video, slug, channelsDir, probe }; const out = []; for (const tier of CORPUS_TIERS) { @@ -245,3 +261,65 @@ export function channelsDirFor(dir, manifest, { shadowExists = false, fallback = if (shadowExists) return path.join(/* turbopackIgnore: true */ dir, SHADOW_CHANNELS); return fallback; } + +// ---- the shadow first, the corpus after ---------------------------------------- +// +// A project's own channels tree (`provenance.channelsDir`, a `.shadow-channels/`) +// is read FIRST; the real corpus (`fallback`, transcripts/channels) is read for +// anything the shadow lacks -- a channel added to the corpus after the shadow +// was made, a post, a cue file, a cached window (rev 9, 6 Nov: the cut lane had +// to copy three channels' posts, three cue files and the editor's windows into +// the shadow, and render with CHANNELS_DIR=<shadow>). Each kind that falls back +// says so once per run. Off: `provenance.channelsFallback: false`, or +// CHANNELS_FALLBACK=0 -- the shadow alone, as before. + +/** The environment switch that turns the corpus fallback off ("0"). */ +export const CHANNELS_FALLBACK_ENV = "CHANNELS_FALLBACK"; + +/** Is the corpus fallback on for this manifest (default yes)? */ +export function channelsFallbackOn(manifest, env = process.env) { + if (String(env?.[CHANNELS_FALLBACK_ENV] ?? "") === "0") return false; + return manifest?.provenance?.channelsFallback !== false; +} + +/** + * The channels trees a project reads, in order: its own (channelsDirFor) and, + * when that is not the corpus and the fallback is on, the corpus after it. + * + * @returns {string[]} + */ +export function channelsLayersFor(dir, manifest, { shadowExists = false, fallback = null, env = process.env } = {}) { + const first = channelsDirFor(dir, manifest, { shadowExists, fallback }); + if (!first) return fallback ? [fallback] : []; + const out = [first]; + if (fallback && path.resolve(fallback) !== path.resolve(first) && channelsFallbackOn(manifest, env)) out.push(fallback); + return out; +} + +const fallbackNoted = new Set(); + +/** Say ONCE per run per kind that a kind was read from the corpus behind the shadow. */ +export function noteChannelsFallback(kind, line, log = (m) => process.stderr.write(`${m}\n`)) { + if (fallbackNoted.has(kind)) return false; + fallbackNoted.add(kind); + log(line); + return true; +} + +/** (Tests: forget what was said.) */ +export const resetChannelsFallbackNotes = () => fallbackNoted.clear(); + +/** + * The first of `layers` that holds `<layer>/<...rel>` -- or the first layer + * when none does (its own "not there" is the error a caller reports). A layer + * after the first noted once for `kind`. + */ +export async function firstLayerWith(layers, rel, { kind = "files", log } = {}) { + for (let i = 0; i < layers.length; i += 1) { + if (await stat(path.join(/* turbopackIgnore: true */ layers[i], ...rel)).then(() => true, () => false)) { + if (i > 0) noteChannelsFallback(kind, `${kind}: ${rel.join("/")} is not in ${layers[0]} -- read from ${layers[i]} (the corpus behind the project's channels tree; provenance.channelsFallback: false or ${CHANNELS_FALLBACK_ENV}=0 turns this off)`, log); + return layers[i]; + } + } + return layers[0] ?? null; +}