Archilyzer · Source

archilyzer

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

commit 5fbeec9acffbeb66be3d1032bbe2bd83c9338530
parent fcaf0358fc7f4ba900e4541231589049b680ff74
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 12 Nov 2026 08:49:25 -0500

umtool: cast assign -- every post item's author gets a character BY RULE (no model), an author with none a PROPOSED character of this video: an id from the handle, their name, a stock Kokoro voice the next in one fixed rotation (male and female in turn) the project does not use yet, a gender hint only from the profile's own stated pronouns; proposals kept apart under `proposed` in narration/characters.json through its one writer (undo), applied to nothing until accepted -- --accept <id>|--accept-all makes the character and names it on that author's items that name none (never a picked read), --change <id> its voice (stock only), speed, name, anonymity, --reject <id>|--reject-all drops it, --dry-run writes nothing; a proposal's voice is one of STOCK_VOICES (held equal to the editor's list by a test) and its preset synthetic (a direction at most); cast project lists them; cli.md, knobs.md, CHANGELOG

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Meditor/CHANGELOG.md | 1+
Mumtool/docs/cli.md | 2++
Mumtool/docs/knobs.md | 35+++++++++++++++++++++++++++++++++++
Mumtool/lib/cli/groups.mjs | 4++++
Mumtool/lib/cli/verbs.mjs | 9+++++++++
Aumtool/lib/report/castAssign.test.mjs | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/castCli.mjs | 178+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/lib/report/castProject.mjs | 9++++++++-
Mumtool/lib/report/castStore.mjs | 17+++++++++++------
Aumtool/report-to-video/cast-assign.mjs | 226+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/cast-assign.test.mjs | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/cast.mjs | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 1+
13 files changed, 780 insertions(+), 14 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **umtool: every post author gets a character by rule, as a proposal you accept.** Giving each author of a video a voice meant one `cast project … keep` or Voices-page click per author. `umtool cast assign <p>` now goes through every post item's author: one the item, this video, its voice map or the cast already answers for is left as it is; one with none gets a PROPOSED character of this video -- an id from the handle, their name and a stock Kokoro voice, the next in one fixed rotation (a male and a female voice in turn) that the project does not use yet. A gender hint comes only from pronouns the profile itself states; today's captures carry none, so the rotation is neutral. Proposals are kept apart in `narration/characters.json` (the same writer and undo) and change nothing until a person acts: `--accept <id>` / `--accept-all` makes the character and names it on that author's items that name none, without touching any take; `--change <id>` sets its voice (a stock one only), speed, name or anonymity; `--reject <id>` drops it. `--dry-run` writes nothing. - **umtool: a Model log shows what the model was asked, what it answered, and what the code did with it.** Until now a prompt was shown nowhere, and a local model's calls were in no ledger. Every model call of a run is now recorded, on every route (a local model, the Claude API, this session), and listed in a **Model log** panel on the run page (`/research/runs/<article>/<n>`), the article's Iterations tab and each media draft. Calls are grouped by phase (terms, reading, meaning check, grouping). A row has the first lines of what was asked, what came back, the seconds, and whether its answer was kept, dropped or rewritten, with the reason and each item's fate. A row opens to the whole prompt and answer (40,000 characters of each are kept). A log holds 20,000 calls or 32 MB; past that the panel says the log is full, and later calls are not recorded. The header counts the calls, the seconds and the models; a filter narrows to kept, dropped or rewritten; the list follows a run while it runs. `umtool model-log <article> <n>` (or `--job <jobId>`) prints the same, with `--phase`, `--outcome`, `--task`, `--run`, `--call <run.call>` for one call's whole text, and `--json`; a control sequence in a recorded text is printed as its escape (`\x1b`), never sent to the terminal. `/settings/generation` shows, per task, the route and the model it will run on, "no API key configured" when there is none, and the model of its last run. - **The job page has the Model log too, and a local model's calls are in the usage ledger.** A job that calls a model (a report draft, a refresh, triage, verdicts, a frame scan, clip suggestions, video assist) shows its calls on `/jobs/<id>`, as umtool does. Calls to a local model are appended to `.generation/usage.jsonl` with route `local` and cost 0, so `pnpm ops get generation-usage` lists every model a run called, and a run that was local only lists no other. `pnpm ops get iterations` gains each iteration's call count and seconds. The record keeps the text sent to the model and nothing else: no header and no model host; the editor's `WORKER_TOKEN`, an API key, every environment variable named like a credential, and host paths are taken out before a line is written, anything shaped like a credential (a URL's user and password, a token in a query string however its `&` and `=` are written — `\u0026`, `&amp;`, `%26`, `%3D` — an `Authorization` value of any scheme, a `Bearer` value, a cookie line, a key that says what it is) loses its value whoever's it is, while a date or a time after `secret:` or `token:` is left as it is, and a failed call's message has its URLs and addresses removed. Links are kept. - **Cancelling a job whose program never started no longer stops the editor.** A download cancelled after its channel directory was gone sent SIGTERM to the editor's whole process group: Node's `kill()` on a child that failed to spawn has no pid and signals the caller's own group. A kill on such a child is now a no-op in the editor, and umtool and the standalone scripts (the queue lock, `render-mode on -- <cmd>`, loudness, voice, TTS, diarization, `pnpm e2e:all`) check the child's pid before every kill; a sweep test holds them to it. diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -25,6 +25,7 @@ Inbox cannot disagree about what is wrong with one. | `cast [ls] \| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--speed s] [--convert-engine e] [--convert-voice v] [--convert-pitch target\|source\|contour] [--convert-semitones n] [--enhance on\|off] [--trim on\|off] [--trim-pad ms] [--direction "…"] [--narrator] \| set <id> … \| rm <id> \| undo [--json]` | **THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects, one writer, an undo point a write. **A character is a PRESET**, two of them ([knobs.md](knobs.md#a-character-is-a-preset)): `synthetic` -- the STOCK voice it reads in (`--voice`) and its speed (`--speed` 0.5–2; Orpheus has none) -- and `recorded` -- what a recording of them is made into: the stock voice (`--convert-voice`; a file or a recording is refused), the engine, the **pitch** the converted read lands on (`--convert-pitch`: `target` the stock voice's own, `source` the pitch it was read at, `contour` the read's rises and falls at the stock voice's register; `--convert-semitones` -12…12 moves a followed one), whether it is cleaned first (`--enhance`), its edges trimmed to speech (`--trim`, `--trim-pad` the ms kept either side) and a `--direction` (one line for the person reading, never sent to a model). `set` lays the flags given over the presets; `default` for one takes that key off; `--no-convert`, `--no-speed`. A version 1 file (`voice`, `convert` at a character's top) reads as these presets and the first write makes it version 2 (`undo` puts the old file back). A followed pitch on an engine that has none, semitones with nothing followed, a speed or a pad out of range: **exit 1** | | `cast project <project> [--json]` · `cast use <project> <character\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]` | a project's characters: each one's voice now (and speed) and **where it comes from** -- the chain one read asks, first hit wins: the command's flags, the item's own character (`posts character`), this video's character for the author (then its voice map), the cast's, the narrator's, the default -- what a recording of them is made into, its stale reads; this video's own characters; the items that name their own. `use`: the voice for this project (its own character's when it has one for them, else the voice map) or everywhere, and the re-reads that asks for | | `cast project <project> add <id> [--name "…"] [--voice <engine:voice>] [--handles a,b] [--anonymous [--shown "…"]] [the preset flags]` · `set <id> … [--no-voice] [--no-anonymous]` · `rm <id>` · `undo` · `pool <id>` · `keep <character\|@handle> [--anonymous]` `[--json]` | **THIS VIDEO's OWN CHARACTERS** (`<project>/narration/characters.json`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the cast's shape and the cast's writer (a token, an undo point a write, atomic, a broken file never overwritten), for people who must not enter the pool. `--anonymous`: it goes by a **shown name** (`--shown`; default the next of `Anon 1`, `Anon 2` …) on the Voices page, in `cast project` and in a recording's note, and never enters the pool; **the on-screen card is not anonymised yet** (it still shows the post's author). `--voice` is optional here: a character with none leaves the voice to the layers under it. `narration/voices.json` keeps working under it (a handle in it reads as a character with only a synthetic voice) and is never rewritten by these. `pool <id>` (**Add to the pool**) moves one into the cast -- an anonymous one, or an id the cast has, is refused; `keep` (**Keep in this video only**) copies a cast character here (its presets changed for this video alone), or gives an author with no character one, in the voice they read in now. A refusal: **exit 1**, nothing written | +| `cast assign <project> [--model] [--dry-run] [--json]` · `--accept <id>` · `--accept-all` · `--reject <id>` · `--reject-all` · `--change <id> [--voice <engine:voice>] [--speed s] [--name "…"] [--direction "…"] [--anonymous [--shown "…"] \| --no-anonymous]` | **AUTO-ASSIGNMENT BY RULE** ([knobs.md](knobs.md#proposed-characters-cast-assign)): every post item's author gets a character -- the item's own, this video's, its voice map's or the cast's; an author with none a **PROPOSED** character of this video: an id from the handle, their name, a STOCK Kokoro voice -- the next, in one fixed rotation (a male and a female voice in turn), that this project does not use yet; a gender hint only from the profile's own stated pronouns when the capture carries them. Proposals are kept apart in `<project>/narration/characters.json` (`proposed`; the same writer, an undo point: `cast project <p> undo`) and are **applied to nothing** -- no item, no picked read -- until a person accepts. `--accept <id>` / `--accept-all`: this video's character, named (`narration.character`) on that author's items that name none -- no take made or changed (a picked read in another voice shows as drift); `--change <id>`: its voice (a stock one only), speed, name, direction or anonymity; `--reject <id>` / `--reject-all`: dropped. A proposal whose author has a character now is dropped by the next run. `--dry-run` writes nothing. **`--model`** (on request only): the generation task `cast-assign`, routed by `settings.generation` like the other tasks, is asked per author (display name, bio, post text -- untrusted) for `{character, voice, speed, direction}`; each field is checked (a stock voice, a speed 0.5–2, one plain line, control characters stripped) and laid over the rule's row, which stays when the answer fails. Refused: **exit 1**, nothing written | | `cast audition <character\|@handle> --voices a,b,… [--project <p>] [--text "…" \| --item <id> \| --line <n> \| --stock] [--no-score \| --score-only] [--json] [--progress ndjson]` | **AN AUDITION**: one line read by 2-6 stock voices through the editor's tts op, levelled to -20 LUFS in `<p>/narration/auditions/` (cached), scored for closeness to the character's real voice (`speakers.json`; TitaNet, local) | | `speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]` · `--set 'Name=<clip>,<channel>/<id>,channel:<slug>'` · `--remove <name>` · `--list` | which of the project's **named voices** (`speakers.json`) each clip is: TitaNet-small, local, against each voice's robust centroid → `<project>/speaker-check.json` (merged); the walk's **Speaker:** badge and **Check speaker** ([report-video.md](report-video.md#the-speaker-check-on-the-walk-which-of-several-voices)) | | `quote-check <project> [--clips a,b] [--pad S] [--json]` · `quote-check <project> --status` | **is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; the editor's work files go to `<project>/.quote-check/`, never under `out/` (a link onto a media drive the editor will not write in); `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays)) | @@ -187,6 +188,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `cast audition <character> --voices VOICES [--project PROJECT] [--text TEXT] [--item ITEM] [--line N] [--stock] [--no-score] [--score-only]` | one line read by 2-6 candidate voices, scored against the real voice | form · queued · *project* | | `cast use <project> <character> <voice> [--everywhere]` | the voice a character reads in, here or everywhere | form · *draft* | | `cast reread <project> <character> [--dry-run]` | the items that say a character in another voice, read again | form · queued · *project* | +| `cast assign <project> [--model] [--dry-run] [--accept ACCEPT] [--accept-all] [--reject REJECT] [--reject-all] [--change CHANGE] [--voice VOICE] [--speed N] [--name NAME] [--direction DIRECTION] [--anonymous] [--shown SHOWN] [--no-anonymous]` | a proposed character for each author with none (by rule; --model on request); accept, change, reject | form · *project* | | `speaker-check <project> [--clip CLIP…] [--list] [--set SET] [--remove REMOVE]` | which named voice each clip is (speaker-check.json) | form · queued · *project* | | `quote-check <project> [--clips CLIPS] [--pad N] [--status]` | is each clip's quote in the seconds it plays | form · queued · *project* | | `check-joins <project> --take TAKE [--all] [--limit N]` | do a rendered take's post joins carry on | form · queued · *project* | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -1514,6 +1514,41 @@ handle does -- a reply read as "Anon 2" while the same handle elsewhere reads as by the command; one that stops existing later (the character removed) reads as its author does, and `umtool cast project <p>` says so. +### Proposed characters (cast assign) + +Every post item's author gets a character **by rule**, no model (`umtool cast assign <p>`; the Voices page's +**Propose characters**): the item's own, this video's, its voice map's or the cast's -- and an author with none a +**PROPOSED** character of this video (`cast-assign.mjs` `assignPlan`): an id from the handle, the author's name, a +STOCK Kokoro voice (Kokoro first: Orpheus is heavy) -- the next voice this project does not use yet, in one fixed +rotation (`ASSIGN_ROTATION`: American then British, a male and a female voice in turn), past every voice its authors, +characters, voice map and narrator use. A gender hint comes **only from the profile's own stated pronouns** when the +capture carries them (`pronouns`, or "she/her" … in a `bio`; today's captures carry neither, so the rotation is +neutral) -- never a guess from a name. + +Proposals live apart, under `proposed` in `<project>/narration/characters.json` (the same writer, an undo point a +write: `umtool cast project <p> undo`), and are **applied to nothing** -- no item, no picked read -- until a person +acts on one: + +| knob | UI | CLI | +|---|---|---| +| propose | Voices › proposed · **Propose characters** | `umtool cast assign <p> [--dry-run] [--json]` | +| accept | **Accept** (or **Accept all**): this video's character, named (`narration.character`) on that author's items that name none -- no take made or changed; a picked read in another voice is listed as drift | `umtool cast assign <p> --accept <id>` · `--accept-all` | +| change | **Change**: the voice (a stock one only), the name, anonymous and its shown name | `umtool cast assign <p> --change <id> [--voice <engine:voice>] [--speed s] [--name "…"] [--direction "…"] [--anonymous [--shown "…"] \| --no-anonymous]` | +| reject | **Reject**: dropped | `umtool cast assign <p> --reject <id>` · `--reject-all` | +| ask the model too | **Ask the model too** (optional; the page works without it) | `umtool cast assign <p> --model [--dry-run]` | + +A proposal is refused unless its voice is one of the stock voices (`cast.mjs` `STOCK_VOICES`, held equal to the +editor's list by a test) and its preset synthetic -- a direction line at most; a convert target is set by a person, +after accepting. A held proposal whose author has a character now is dropped by the next run. + +**The model, on request only** (`--model`, the page's **Ask the model too**): the generation task **`cast-assign`**, +routed by `settings.generation` like the other tasks (`local` by default; the code route is answered in a session), is +asked per author for `{character, voice, speed, direction}` from the author's display name, bio and post text -- +untrusted text, so its answer is held to a schema and checked field by field: the voice one of the stock voices, the +speed 0.5–2, the name and the direction one plain line (control characters stripped). What passes is laid over the +rule's row (`by: "model"`, the model named); the rule's row stays as it was when nothing passes. It is never asked +without the flag or the button. + ### The pitch a converted read lands on A converter given no pitch speaks every read at the STOCK voice's own: measured 11 Nov, reads with a median pitch of diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -72,6 +72,8 @@ export const GROUPS = [ " [--everywhere] | reread <p> <character> the CAST: characters across projects (cast.json), each a", " PRESET -- synthetic (voice, speed) and recorded (convert, clean, trim, a direction) -- a project's", " characters, its OWN (characters.json: anonymous ones), their drift, an audition of candidate voices", + " | assign <p> [--model] [--dry-run] | assign <p> --accept <id>|--accept-all|--reject <id>|--change <id> …", + " PROPOSED characters for authors with none, by rule; nothing applied until a person accepts", ], docs: [ ["`cast [ls] \\| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--speed s] [--convert-engine e] [--convert-voice v] [--convert-pitch target\\|source\\|contour] [--convert-semitones n] [--enhance on\\|off] [--trim on\\|off] [--trim-pad ms] [--direction \"…\"] [--narrator] \\| set <id> … \\| rm <id> \\| undo [--json]`", @@ -80,6 +82,8 @@ export const GROUPS = [ "a project's characters: each one's voice now (and speed) and **where it comes from** -- the chain one read asks, first hit wins: the command's flags, the item's own character (`posts character`), this video's character for the author (then its voice map), the cast's, the narrator's, the default -- what a recording of them is made into, its stale reads; this video's own characters; the items that name their own. `use`: the voice for this project (its own character's when it has one for them, else the voice map) or everywhere, and the re-reads that asks for"], ["`cast project <project> add <id> [--name \"…\"] [--voice <engine:voice>] [--handles a,b] [--anonymous [--shown \"…\"]] [the preset flags]` · `set <id> … [--no-voice] [--no-anonymous]` · `rm <id>` · `undo` · `pool <id>` · `keep <character\\|@handle> [--anonymous]` `[--json]`", "**THIS VIDEO's OWN CHARACTERS** (`<project>/narration/characters.json`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the cast's shape and the cast's writer (a token, an undo point a write, atomic, a broken file never overwritten), for people who must not enter the pool. `--anonymous`: it goes by a **shown name** (`--shown`; default the next of `Anon 1`, `Anon 2` …) on the Voices page, in `cast project` and in a recording's note, and never enters the pool; **the on-screen card is not anonymised yet** (it still shows the post's author). `--voice` is optional here: a character with none leaves the voice to the layers under it. `narration/voices.json` keeps working under it (a handle in it reads as a character with only a synthetic voice) and is never rewritten by these. `pool <id>` (**Add to the pool**) moves one into the cast -- an anonymous one, or an id the cast has, is refused; `keep` (**Keep in this video only**) copies a cast character here (its presets changed for this video alone), or gives an author with no character one, in the voice they read in now. A refusal: **exit 1**, nothing written"], + ["`cast assign <project> [--model] [--dry-run] [--json]` · `--accept <id>` · `--accept-all` · `--reject <id>` · `--reject-all` · `--change <id> [--voice <engine:voice>] [--speed s] [--name \"…\"] [--direction \"…\"] [--anonymous [--shown \"…\"] \\| --no-anonymous]`", + "**AUTO-ASSIGNMENT BY RULE** ([knobs.md](knobs.md#proposed-characters-cast-assign)): every post item's author gets a character -- the item's own, this video's, its voice map's or the cast's; an author with none a **PROPOSED** character of this video: an id from the handle, their name, a STOCK Kokoro voice -- the next, in one fixed rotation (a male and a female voice in turn), that this project does not use yet; a gender hint only from the profile's own stated pronouns when the capture carries them. Proposals are kept apart in `<project>/narration/characters.json` (`proposed`; the same writer, an undo point: `cast project <p> undo`) and are **applied to nothing** -- no item, no picked read -- until a person accepts. `--accept <id>` / `--accept-all`: this video's character, named (`narration.character`) on that author's items that name none -- no take made or changed (a picked read in another voice shows as drift); `--change <id>`: its voice (a stock one only), speed, name, direction or anonymity; `--reject <id>` / `--reject-all`: dropped. A proposal whose author has a character now is dropped by the next run. `--dry-run` writes nothing. **`--model`** (on request only): the generation task `cast-assign`, routed by `settings.generation` like the other tasks, is asked per author (display name, bio, post text -- untrusted) for `{character, voice, speed, direction}`; each field is checked (a stock voice, a speed 0.5–2, one plain line, control characters stripped) and laid over the rule's row, which stays when the answer fails. Refused: **exit 1**, nothing written"], ["`cast audition <character\\|@handle> --voices a,b,… [--project <p>] [--text \"…\" \\| --item <id> \\| --line <n> \\| --stock] [--no-score \\| --score-only] [--json] [--progress ndjson]`", "**AN AUDITION**: one line read by 2-6 stock voices through the editor's tts op, levelled to -20 LUFS in `<p>/narration/auditions/` (cached), scored for closeness to the character's real voice (`speakers.json`; TitaNet, local)"], ], diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -168,6 +168,15 @@ export const VERBS = Object.freeze([ ], Q), form("cast use", "draft", "the voice a character reads in, here or everywhere", [project(), arg("character", { allowAt: true }), arg("voice", { help: "engine:voice" }), bool("--everywhere", "the cast's voice, not this project's")], { shape: "cast use <project> <character> <voice>" }), form("cast reread", "project", "the items that say a character in another voice, read again", [project(), arg("character", { allowAt: true }), dry()], Q), + // C3: PROPOSED characters by rule (a model only on request), kept apart until a person accepts one (castCli.mjs assignCommand). + form("cast assign", "project", "a proposed character for each author with none (by rule; --model on request); accept, change, reject", [ + project(), bool("--model", "the cast-assign generation task's proposals laid over the rule's (optional)"), dry(), + opt("--accept", { type: "name", help: "a proposal's id: this video's character, named on that author's items" }), bool("--accept-all"), + opt("--reject", { type: "name", help: "a proposal's id: dropped (an undo point)" }), bool("--reject-all"), + opt("--change", { type: "name", help: "a proposal's id: its voice, speed, name, direction or anonymity" }), + opt("--voice", { help: "with --change: a STOCK voice, engine:voice" }), num("--speed", { help: "with --change: 0.5–2" }), opt("--name"), opt("--direction"), + bool("--anonymous"), opt("--shown"), bool("--no-anonymous"), + ], { shape: "cast assign <project>" }), form("speaker-check", "project", "which named voice each clip is (speaker-check.json)", [ project(), many("--clip", { repeat: true, help: "clip ids, one per line (none: every clip)" }), bool("--list", "list the named voices"), diff --git a/umtool/lib/report/castAssign.test.mjs b/umtool/lib/report/castAssign.test.mjs @@ -0,0 +1,100 @@ +// `umtool cast assign` on disk (castCli.mjs assignCommand; cast-assign.mjs): the rule's proposals kept apart in the +// project's characters file (one writer, an undo point), applied to nothing; --dry-run writes nothing; accept makes the +// character and names it on that author's items (never a picked read); change and reject; a convert target refused. +// Every project is a temp dir; no editor. +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 { castCommand } from "./castCli.mjs"; +import { projectCharactersFile, readProjectCharacters } from "./castStore.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-cast-assign-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const cast = async (args, extra = {}) => { + const lines = []; + const code = await castCommand(args, { reportsRoot: ROOT, log: (s) => lines.push(s), err: (s) => lines.push(s), ...extra }); + return { code, text: lines.join("\n"), json: () => JSON.parse(lines.join("\n")) }; +}; + +const DIR = path.join(ROOT, "assign"); +const take = { file: "narration/posts/x-1/take-1.kokoro.wav", engine: "kokoro", voice: "af_heart", seconds: 2, script: "Mine." }; +{ + const post = (id, handle, author, o = {}) => ({ type: "post", id: `p-${id}`, post: `chan/${id}`, platform: "x", author, handle, date: `2026-10-30T1${id}:00:00.000Z`, text: `words of ${id}.`, ...o }); + await mkdir(DIR, { recursive: true }); + await writeFile(path.join(DIR, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: "assign", title: "Assign", provenance: { channelsDir: "../channels", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, postNarration: { engine: "kokoro", voice: "af_heart" } }, + timeline: [ + post("1", "hostman", "Host Man"), + post("2", "newbie", "New Person", { narration: { takes: [take], pick: 0 } }), + post("3", "newbie", "New Person", { narration: { character: "hostman" } }), + post("4", "other", "Someone Else"), + ], + }, null, 2)); + await mkdir(path.join(ROOT, ".umtool"), { recursive: true }); + await writeFile(path.join(ROOT, ".umtool", "cast.json"), JSON.stringify({ format: "umtool-cast", version: 2, characters: [{ id: "hostman", name: "Host Man", handles: ["hostman"], synthetic: { voice: "kokoro:am_adam" } }] })); +} +const manifest = async () => JSON.parse(await readFile(path.join(DIR, "video.manifest.json"), "utf8")); + +test("assign --dry-run: the plan, nothing written", async () => { + const r = await cast(["assign", "assign", "--dry-run", "--json"]); + assert.equal(r.code, 0, r.text); + const j = r.json(); + assert.equal(j.dryRun, true); + assert.deepEqual(j.authors.map((a) => [a.handle, a.state, a.character]), [["hostman", "cast", "hostman"], ["newbie", "propose", "newbie"], ["other", "propose", "other"]]); + assert.deepEqual(j.proposed.map((x) => x.synthetic.voice), ["kokoro:af_alloy", "kokoro:am_echo"], "past the cast's am_adam (and the narrator's af_heart)"); + assert.equal((await readProjectCharacters(DIR)).exists, false, "no file made"); +}); + +test("assign: proposals kept apart, applied to nothing; again: nothing new; accept names the items; change; reject; undo", async () => { + const before = JSON.stringify(await manifest()); + const r = await cast(["assign", "assign"]); + assert.equal(r.code, 0, r.text); + assert.match(r.text, /2 proposed now/); + assert.match(r.text, /applied to nothing until accepted/); + const doc = JSON.parse(await readFile(projectCharactersFile(DIR), "utf8")); + assert.deepEqual(doc.characters, [], "no character made"); + assert.deepEqual(doc.proposed.map((x) => [x.id, x.by]), [["newbie", "rule"], ["other", "rule"]]); + assert.equal(JSON.stringify(await manifest()), before, "no item touched"); + // The project view lists them (the Voices page reads it), and a second run proposes nothing new. + const view = (await cast(["project", "assign", "--json"])).json(); + assert.deepEqual(view.proposed.map((x) => [x.id, x.items]), [["newbie", ["p-2"]], ["other", ["p-4"]]], "p-3 names its own character"); + const again = (await cast(["assign", "assign", "--json"])).json(); + assert.deepEqual(again.proposed, []); + assert.deepEqual(again.held.map((x) => x.id), ["newbie", "other"]); + // Change: a voice that is not a stock one is refused; a stock one, a name, anonymity are taken. + assert.equal((await cast(["assign", "assign", "--change", "newbie", "--voice", "kokoro:nobody"])).code, 1); + const refused = await cast(["assign", "assign", "--change", "newbie", "--convert-voice", "kokoro:am_echo"]); + assert.equal(refused.code, 1); + assert.match(refused.text, /accept it first/); + const ch = await cast(["assign", "assign", "--change", "newbie", "--voice", "kokoro:bm_george", "--speed", "1.1", "--anonymous", "--json"]); + assert.equal(ch.code, 0, ch.text); + assert.deepEqual(ch.json().proposal.synthetic, { voice: "kokoro:bm_george", speed: 1.1 }); + assert.equal(ch.json().proposal.shown, "Anon 1"); + assert.equal(ch.json().proposal.by, "rule"); + // Accept: this video's character; that author's items that name none name it -- the picked take untouched. + const ac = await cast(["assign", "assign", "--accept", "newbie", "--json"]); + assert.equal(ac.code, 0, ac.text); + assert.deepEqual(ac.json().items, [{ id: "p-2", character: "newbie" }]); + const m = await manifest(); + assert.equal(m.timeline[1].narration.character, "newbie"); + assert.deepEqual(m.timeline[1].narration.takes, [take], "the picked read is never touched"); + assert.equal(m.timeline[1].narration.pick, 0); + assert.equal(m.timeline[2].narration.character, "hostman", "a person's choice stays"); + const after1 = (await readProjectCharacters(DIR)).doc; + assert.deepEqual(after1.characters.map((c) => [c.id, c.anonymous ?? false, c.shown ?? null, c.synthetic]), [["newbie", true, "Anon 1", { voice: "kokoro:bm_george", speed: 1.1 }]]); + assert.deepEqual(after1.proposed.map((x) => x.id), ["other"]); + // Reject: dropped; undo puts it back. + assert.equal((await cast(["assign", "assign", "--reject", "nobody"])).code, 1); + assert.equal((await cast(["assign", "assign", "--reject", "other"])).code, 0); + assert.equal((await readProjectCharacters(DIR)).doc.proposed, undefined, "none left: the key is gone"); + assert.equal((await cast(["project", "assign", "undo"])).code, 0); + assert.deepEqual((await readProjectCharacters(DIR)).doc.proposed.map((x) => x.id), ["other"]); + // One ask at a time. + assert.equal((await cast(["assign", "assign", "--accept", "other", "--reject", "other"])).code, 1); + assert.equal((await cast(["assign", "assign", "--accept-all"])).code, 0); + assert.deepEqual((await readProjectCharacters(DIR)).doc.characters.map((c) => c.id), ["newbie", "other"]); + assert.equal((await manifest()).timeline[3].narration.character, "other"); +}); diff --git a/umtool/lib/report/castCli.mjs b/umtool/lib/report/castCli.mjs @@ -16,12 +16,15 @@ // [--no-score | --score-only] [--no-hold] [--json] [--progress ndjson] // umtool cast use <p> <character|@handle> <voice> [--everywhere] [--json] // umtool cast reread <p> <character|@handle> [--dry-run] [--json] +// umtool cast assign <p> [--model] [--dry-run] [--json] PROPOSED characters for the authors with none +// umtool cast assign <p> --accept <id> | --accept-all | --reject <id> | --reject-all +// umtool cast assign <p> --change <id> [--voice <engine:voice>] [--speed s] [--name "…"] [--anonymous [--shown "…"] | --no-anonymous] // // Plain ESM: the CLI runs under bare node. import path from "node:path"; import { ANON_NAME_PATTERN, CAST_CONVERT_ENGINES, CAST_CONVERT_PITCH, CAST_SEMITONES_MAX, CAST_SPEED, DIRECTION_MAX, TRIM_PAD_MAX_MS, characterOf, characterView, convertPitchErrors, convertPitchLabel, - charactersOf, findCharacter, isQualifiedVoice, nextAnonName, projectCharactersOf, shownNameOf, upgradeCharacter, + charactersOf, findCharacter, idOfHandle, isQualifiedVoice, isStockVoice, nextAnonName, projectCharactersOf, proposalCharacter, shownNameOf, upgradeCharacter, } from "umtool-report-to-video/cast"; import { handleKey, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; @@ -46,6 +49,9 @@ export const CAST_USAGE = [ " [--text \"…\" | --item <id> | --line <n> | --stock] [--no-score | --score-only] [--no-hold] [--json] [--progress ndjson]", " umtool cast use <project> <character|@handle> <engine:voice> [--everywhere] [--json]", " umtool cast reread <project> <character|@handle> [--dry-run] [--json]", + " umtool cast assign <project> [--model] [--dry-run] [--json]", + " umtool cast assign <project> --accept <id> | --accept-all | --reject <id> | --reject-all [--json]", + " umtool cast assign <project> --change <id> [--voice <engine:voice>] [--speed <s>] [--name \"…\"] [--anonymous [--shown \"…\"] | --no-anonymous] [--json]", "", " THE CAST (<reports>/.umtool/cast.json, one writer, an undo point per write): the characters that recur across", " projects -- an id, a name, their handles (X handles / channel slugs) and TWO PRESETS, picked by how a read is made:", @@ -83,10 +89,22 @@ export const CAST_USAGE = [ " use: the voice for this project (its own character's when it has one for them, else its voice map) or", " --everywhere (the cast; the project's own override of it is removed); then the items whose picked reads say the", " character in another voice -- reread makes them (a new take each, picked, awaiting approval).", + " assign: every post item's author gets a character BY RULE (no model): the item's own, this video's, its voice map's", + " or the cast's; an author with none, a PROPOSED character of this video -- an id from the handle, their name, a", + " STOCK Kokoro voice, the next in one fixed rotation that this project does not use yet (a gender hint only from", + " the profile's own stated pronouns, when the capture has them). Proposals are kept apart in", + " <p>/narration/characters.json (one writer, an undo point: cast project <p> undo) and applied to NOTHING until a", + " person accepts: --accept <id> / --accept-all makes it this video's character and names it on that author's items", + " (those that name none; a picked read is never touched -- one in another voice is drift: cast reread);", + " --reject <id> / --reject-all drops it; --change <id> sets its voice (a stock one), speed, name or anonymity first.", + " --dry-run writes nothing. --model (optional, on request only): the generation task cast-assign (routed by", + " settings.generation) is asked per author -- name, bio, post text -- for {character, voice, speed, direction}, each", + " field checked (a stock voice, a speed 0.5-2, one plain line) and laid over the rule's row; the rule's row stays", + " when the answer fails.", " Exit 0 done · 1 refused or failed · 2 usage.", ].join("\n"); -const VALUED = new Set(["--name", "--voice", "--handles", "--speakers", "--convert-engine", "--convert-voice", "--convert-pitch", "--convert-semitones", "--avatar", "--note", "--add-handle", "--remove-handle", "--voices", "--project", "--text", "--item", "--line", "--progress", "--speed", "--enhance", "--trim", "--trim-pad", "--direction", "--shown"]); +const VALUED = new Set(["--name", "--voice", "--handles", "--speakers", "--convert-engine", "--convert-voice", "--convert-pitch", "--convert-semitones", "--avatar", "--note", "--add-handle", "--remove-handle", "--voices", "--project", "--text", "--item", "--line", "--progress", "--speed", "--enhance", "--trim", "--trim-pad", "--direction", "--shown", "--accept", "--reject", "--change"]); const splitList = (v) => String(v ?? "").split(",").map((x) => x.trim()).filter(Boolean); function parse(args) { @@ -276,8 +294,6 @@ const line = (c0) => { return `${c.id.padEnd(16)} ${voice.padEnd(20)} ${c.anonymous ? `${shownNameOf(c)} (anonymous; ${c.name})` : c.name}${c.handles?.length ? ` ${c.handles.map((h) => `@${h}`).join(" ")}` : ""}${recordedWords(c) ? ` ${recordedWords(c)}` : ""}${c.speakers?.length ? ` real voice: ${c.speakers.join(", ")}` : ""}${c.narrator ? " (the narrator)" : ""}${c.note ? ` -- ${c.note}` : ""}`; }; -/** An id for a handle's new character ("kirsche.verstahl" -> "kirsche-verstahl"). */ -const idOfHandle = (h) => h.replace(/[^a-z0-9_-]/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 48) || "character"; async function projectOf(ref, reportsRoot) { const r = await resolveProject(ref, reportsRoot); @@ -420,9 +436,10 @@ async function projectCharactersCommand(project, op, rest, p, { reportsRoot, out /** * `umtool cast …` * @param {string[]} args - * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, ask?: any, lanes?: any }} [o] + * `model` (the tests' to stub): `cast assign --model`'s ask -- `(project, authors) => { answers, model }` (castAssignModel.mjs). + * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, ask?: any, lanes?: any, model?: any }} [o] */ -export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, ask = undefined, lanes = undefined } = {}) { +export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, ask = undefined, lanes = undefined, model = undefined } = {}) { let p; try { p = parse(args); @@ -516,6 +533,10 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons log(` this video's own characters (${ownRead.file}):`); for (const c of view.own) log(` ${line(c)}`); } + if (view.proposed?.length) { + log(` PROPOSED, applied to nothing until accepted (umtool cast assign ${project.id} --accept <id> | --change <id> … | --reject <id>):`); + for (const x of view.proposed) log(` ${proposalLine(x)}`); + } for (const it of view.itemCharacters) log(` item ${it.id} is read as ${it.character}${it.found ? ` (${it.layer === "project" ? "this video's" : "the cast's"}): ${it.voice.spec}${speedWords(it.voice)} (${fromWords(it.voice)})` : ` -- NO SUCH CHARACTER: it reads as its author does, ${it.voice.spec} (${fromWords(it.voice)}); umtool posts character ${project.id} ${it.id} --clear`}`); return 0; } @@ -618,7 +639,8 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons return failed ? 1 : 0; } if (sub === "audition") return await auditionCommand(rest, p, { reportsRoot, log, err, ask, lanes }); - throw new CastError(`cast: ls, add, set, rm, undo, project, audition, use or reread (not ${sub})`); + if (sub === "assign") return await assignCommand(rest, p, { reportsRoot, out, json, model }); + throw new CastError(`cast: ls, add, set, rm, undo, project, audition, use, reread or assign (not ${sub})`); } catch (e) { if (e instanceof CastError || e?.name === "AuditionError" || e?.name === "SayError") { if (json) log(JSON.stringify({ ok: false, error: e.message }, null, 2)); @@ -683,3 +705,145 @@ async function auditionCommand(rest, p, { reportsRoot, log, err, ask, lanes }) { if (score?.reference) log(` the real voice (a reference, never a target): ${score.reference}`); return 0; } + +/** A proposal as a line: its id, voice, name, handles, who proposed it and why. */ +const proposalLine = (x) => `${x.id.padEnd(16)} ${`${x.synthetic?.voice ?? "?"}${typeof x.synthetic?.speed === "number" ? ` ×${x.synthetic.speed}` : ""}`.padEnd(20)} ${x.anonymous ? `${shownNameOf(x)} (anonymous; ${x.name})` : x.name} ${(x.handles ?? []).map((h) => `@${h}`).join(" ")} [${x.by}${x.model ? `: ${x.model}` : ""}]${x.recorded?.direction ? ` direction: "${x.recorded.direction}"` : ""}${x.why ? ` -- ${x.why}` : ""}`; + +const ASSIGN_STATE = { item: "every item names its own character", project: "this video's character", map: "this video's voice map", cast: "the cast's character", proposed: "PROPOSED already", propose: "PROPOSED now" }; + +/** + * `umtool cast assign <p> …` (umtool-report-to-video/cast-assign.mjs): the rule's plan and its PROPOSED characters + * (kept in the project's characters file, applied to nothing), and the three a person does with one -- accept, + * change, reject. + */ +async function assignCommand(rest, p, { reportsRoot, out, json, model = undefined }) { + const [ref] = rest; + if (!ref) throw new CastError("cast assign takes the project"); + const project = await projectOf(ref, reportsRoot); + const asks = [["--accept", p.str("--accept")], ["--accept-all", p.has("--accept-all")], ["--reject", p.str("--reject")], ["--reject-all", p.has("--reject-all")], ["--change", p.str("--change")]].filter(([, v]) => v !== null && v !== false); + if (asks.length > 1) throw new CastError(`cast assign: one of ${asks.map(([k]) => k).join(", ")} at a time`); + const what = (w) => `assign: ${w} (${project.id})`; + const [ask] = asks[0] ?? []; + if (ask && p.has("--model")) throw new CastError(`cast assign: --model makes proposals; ${ask} acts on one`); + if (ask === "--accept" || ask === "--accept-all") { + const id = p.str("--accept"); + const r = await projectCharactersWrite(project.dir, (chars, extra) => { + const pick = ask === "--accept-all" ? [...extra.proposed] : extra.proposed.filter((x) => x.id === id); + if (!pick.length) throw new CastError(ask === "--accept-all" ? `nothing is proposed in ${project.id} (umtool cast assign ${project.id})` : `no proposal ${id} in ${project.id} (umtool cast assign ${project.id} --dry-run lists them)`); + const made = []; + for (const x of pick) { + if (chars.some((c) => c.id === x.id)) throw new CastError(`${x.id} is one of ${project.id}'s characters already: --reject ${x.id}, or --change it first`); + for (const h of x.handles ?? []) { + const o = chars.find((c) => (c.handles ?? []).includes(h)); + if (o) throw new CastError(`@${h} is ${o.id}'s already (this video's): --reject ${x.id}`); + } + const c = proposalCharacter(x); + chars.push(c); + made.push(c); + } + extra.proposed = extra.proposed.filter((x) => !pick.includes(x)); + return { accepted: made }; + }, { what: what(ask === "--accept-all" ? "accept all" : `accept ${id}`) }); + // That author's items name it -- those that name none (a person's choice stays); no take is made or changed. + const manifest = await readManifest(project.dir); + const patches = []; + for (const c of r.accepted) { + for (const e of manifest?.timeline ?? []) { + if (e?.type === "post" && (c.handles ?? []).includes(handleKey(e.handle)) && !String(e.narration?.character ?? "").trim()) patches.push({ id: e.id, patch: { character: c.id } }); + } + } + let items = []; + let itemsError = null; + if (patches.length) { + const { withEditNotes } = await import("./edit-guard.mjs"); + const { manifestToken, updatePostNarrations } = await import("./manifest.mjs"); + try { + await withEditNotes(project, async () => updatePostNarrations(project.dir, patches, { token: await manifestToken(project.dir), op: "post-character" })); + items = patches.map((x) => ({ id: x.id, character: x.patch.character })); + } catch (e) { + itemsError = `the character${r.accepted.length === 1 ? " is" : "s are"} made, but the items were not named: ${e instanceof Error ? e.message : e} (umtool posts character ${project.id} <item> <id>)`; + } + } + out( + { ok: !itemsError, scope: "project", accepted: r.accepted.map(characterView), items, ...(itemsError ? { error: itemsError } : {}), token: r.token }, + [ + ...r.accepted.map((c) => `accepted in ${project.id}: ${line(c)}`), + items.length ? ` ${items.length} item(s) name it now: ${items.map((x) => x.id).join(", ")} (no take made or changed; a picked read in another voice is drift -- umtool cast project ${project.id})` : " no item to name (each names its own already)", + ...(itemsError ? [` ${itemsError}`] : []), + ].join("\n"), + ); + return itemsError ? 1 : 0; + } + if (ask === "--reject" || ask === "--reject-all") { + const id = p.str("--reject"); + const r = await projectCharactersWrite(project.dir, (_chars, extra) => { + const gone = ask === "--reject-all" ? [...extra.proposed] : extra.proposed.filter((x) => x.id === id); + if (!gone.length) throw new CastError(ask === "--reject-all" ? `nothing is proposed in ${project.id}` : `no proposal ${id} in ${project.id}`); + extra.proposed = extra.proposed.filter((x) => !gone.includes(x)); + return { rejected: gone }; + }, { what: what(ask === "--reject-all" ? "reject all" : `reject ${id}`) }); + out({ ok: true, scope: "project", rejected: r.rejected.map((x) => x.id), token: r.token }, `rejected in ${project.id}: ${r.rejected.map((x) => x.id).join(", ")} (umtool cast project ${project.id} undo puts ${r.rejected.length === 1 ? "it" : "them"} back)`); + return 0; + } + if (ask === "--change") { + const id = p.str("--change"); + const f = fieldsOf(p); + const extraFlags = ["--convert-engine", "--convert-voice", "--convert-pitch", "--convert-semitones", "--enhance", "--trim", "--trim-pad", "--handles", "--speakers", "--avatar", "--note"].filter((k) => p.has(k)); + if (extraFlags.length) throw new CastError(`cast assign --change sets a proposal's voice, speed, name, direction or anonymity (${extraFlags.join(", ")}: accept it first, then umtool cast project ${project.id} set ${id} …)`); + if (f.voice !== undefined && !isStockVoice(f.voice)) throw new CastError(`--voice: a proposal's voice is one of the stock voices (kokoro:am_michael, orpheus:zac), not ${f.voice}`); + const r = await projectCharactersWrite(project.dir, (_chars, extra) => { + const at = extra.proposed.findIndex((x) => x.id === id); + if (at < 0) throw new CastError(`no proposal ${id} in ${project.id}`); + const { by, why, model: m, ...base } = extra.proposed[at]; + const c = characterFrom(base, id, f, p, { layer: "project", anon: () => nextAnonName([..._chars, ...extra.proposed.filter((_, i) => i !== at)]) }); + if (c.recorded && Object.keys(c.recorded).some((k) => k !== "direction")) throw new CastError("a proposal carries a direction line at most"); + const next = { ...c, by, ...(why ? { why } : {}), ...(m ? { model: m } : {}) }; + extra.proposed[at] = next; + return { proposal: next }; + }, { what: what(`change ${id}`) }); + out({ ok: true, scope: "project", proposal: r.proposal, token: r.token }, `changed: ${proposalLine(r.proposal)}`); + return 0; + } + // THE PLAN (cast-assign.mjs assignPlan): the rule's answer for every author; the new proposals kept (--dry-run: not). + const { assignPlan } = await import("umtool-report-to-video/cast-assign"); + const v = await projectView(project, { reportsRoot }); + if (v.ownRead.error) throw new CastError(v.ownRead.error); + const used = [v.view.narrator?.spec, ...v.view.characters.map((c) => c.voice?.spec)].filter(Boolean); + const plan = assignPlan(v.manifest, { project: v.ownRead.doc, cast: v.castRead.cast, map: v.map, used }); + let proposals = plan.proposals; + let modelRun = null; + if (p.has("--model")) { + const { modelProposals } = await import("./castAssignModel.mjs"); + modelRun = await modelProposals(project, v.manifest, plan, { ask: model }); + proposals = modelRun.proposals; + } + const dryRun = p.has("--dry-run"); + let token = v.ownRead.token; + if (!dryRun && (proposals.length || plan.moot.length)) { + const w = await projectCharactersWrite(project.dir, (chars, extra) => { + extra.proposed = extra.proposed.filter((x) => !plan.moot.includes(x.id)); + for (const x of proposals) { + if (chars.some((c) => c.id === x.id) || extra.proposed.some((y) => y.id === x.id)) throw new CastError(`${x.id} is taken since the plan was made: run cast assign again`); + extra.proposed.push(x); + } + return {}; + }, { token: v.ownRead.token, what: what(`${proposals.length} proposed${plan.moot.length ? `, ${plan.moot.length} moot dropped` : ""}`) }); + token = w.token; + } + const authors = plan.authors.map((a) => { + const fresh = proposals.find((x) => x.id === a.character && a.state === "propose"); + return { handle: a.handle, name: a.name, items: a.items, state: a.state, ...(a.character ? { character: a.character } : {}), ...(fresh?.synthetic?.voice ?? a.voice ? { voice: fresh?.synthetic?.voice ?? a.voice } : {}), ...(fresh ? { proposal: fresh } : a.proposal ? { proposal: a.proposal } : {}) }; + }); + const held = authors.filter((a) => a.state === "proposed").map((a) => a.proposal); + out( + { ok: true, project: project.id, dryRun, authors, proposed: proposals, held, moot: plan.moot, ...(modelRun ? { model: modelRun.report } : {}), token }, + [ + `${project.id}: ${authors.length} author(s); ${proposals.length} proposed now${held.length ? `, ${held.length} proposed before` : ""}${plan.moot.length ? `; ${plan.moot.length} proposal(s) moot (${plan.moot.join(", ")})${dryRun ? "" : ", dropped"}` : ""}${dryRun ? " -- a dry run, nothing written" : " -- applied to nothing until accepted"}`, + ...authors.map((a) => ` @${a.handle.padEnd(18)} ${String(a.voice ?? "").padEnd(20)} ${ASSIGN_STATE[a.state]}${a.character ? `: ${a.character}` : ""} (${a.items.length} item(s))`), + ...(modelRun ? [` the model (${modelRun.report.route}${modelRun.report.model ? `: ${modelRun.report.model}` : ""}): ${modelRun.report.summary}`] : []), + ...[...proposals, ...held].map((x) => ` ${proposalLine(x)}`), + ...([...proposals, ...held].length ? [` umtool cast assign ${project.id} --accept <id> | --accept-all | --change <id> --voice … | --reject <id>`] : []), + ].join("\n"), + ); + return 0; +} diff --git a/umtool/lib/report/castProject.mjs b/umtool/lib/report/castProject.mjs @@ -9,7 +9,7 @@ import { postNarrationKnobs } from "umtool-report-to-video/post-narration"; import { handleKey, resolvePieceVoice, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say"; import { - castDrift, castPresetMap, characterForRead, characterOf, charactersOf, convertTargetOf, itemCharacterOf, itemPresetOf, narratorOf, projectCharactersOf, projectPresetMap, recordedPresetOf, + castDrift, castPresetMap, characterForRead, characterOf, charactersOf, convertTargetOf, itemCharacterOf, itemPresetOf, narratorOf, projectCharactersOf, projectPresetMap, proposalsOf, recordedPresetOf, shownNameOf, speakerFor, takeReads, voiceDrift, ENGINE_WEIGHT, } from "umtool-report-to-video/cast"; import { characterLines } from "./castAudition.mjs"; @@ -141,6 +141,13 @@ export function projectCharacters(manifest, { map = {}, cast = null, project = n cast: charactersOf(cast).length, own: pchars.map((c) => rowCharacter(c, "project")).map((c, i) => ({ ...c, handles: pchars[i].handles ?? [] })), itemCharacters, + // The PROPOSED characters (`umtool cast assign`): applied to nothing until a person accepts -- each with the post + // items of its author's it would be named on (those that name no character of their own). + proposed: proposalsOf(project).map((x) => ({ + ...x, + ...(x.anonymous ? { shown: shownNameOf(x) } : {}), + items: tl.filter((e) => e?.type === "post" && (x.handles ?? []).includes(handleKey(e.handle)) && !str(e.narration?.character).trim()).map((e) => e.id), + })), }; } diff --git a/umtool/lib/report/castStore.mjs b/umtool/lib/report/castStore.mjs @@ -66,9 +66,11 @@ const CAST_KIND = Object.freeze({ what: "the cast", validate: validateCast, empty: emptyCast, doc: (characters) => ({ format: CAST_FORMAT, version: CAST_VERSION, characters }), }); +// A project's file also holds its PROPOSED characters (`proposed`, cast.mjs proposalErrors: `umtool cast assign`), +// written by this writer with the characters, and left out while there are none. const PROJECT_KIND = Object.freeze({ what: "the project's characters", validate: validateProjectCharacters, empty: emptyProjectCharacters, - doc: (characters) => ({ format: PROJECT_CHARACTERS_FORMAT, version: PROJECT_CHARACTERS_VERSION, characters }), + doc: (characters, extra = {}) => ({ format: PROJECT_CHARACTERS_FORMAT, version: PROJECT_CHARACTERS_VERSION, characters, ...(Array.isArray(extra?.proposed) && extra.proposed.length ? { proposed: extra.proposed } : {}) }), }); async function readKind(kind, file) { @@ -88,7 +90,7 @@ async function readKind(kind, file) { const errors = kind.validate(doc, path.basename(file)); if (errors.length) return { cast: kind.empty(), token: sha(text), file, exists: true, text, error: `${path.basename(file)} is refused: ${errors.join("; ")}` }; // As a reader is handed it: each character version 2's shape, with the `voice` / `convert` its presets answer to. - return { cast: { ...kind.doc(doc.characters.map(characterView)) }, token: sha(text), file, exists: true, text }; + return { cast: { ...kind.doc(doc.characters.map(characterView), doc) }, token: sha(text), file, exists: true, text }; } /** @@ -155,8 +157,10 @@ function writeKind(kind, file, mutate, { token = null, what = "an edit" } = {}) // itself (cast.mjs foldWritten, against the character as it was handed). const chars = JSON.parse(JSON.stringify((read.cast.characters ?? []).map(upgradeCharacter))); const was = new Map(chars.map((c) => [c?.id, JSON.parse(JSON.stringify(c))])); - const result = mutate(chars) ?? {}; - const doc = kind.doc(chars.map((c) => foldWritten(c, was.get(c?.id) ?? null))); + // The rest of the document a mutation may change (a project's `proposed`), a copy. + const extra = { proposed: JSON.parse(JSON.stringify(Array.isArray(read.cast.proposed) ? read.cast.proposed : [])) }; + const result = mutate(chars, extra) ?? {}; + const doc = kind.doc(chars.map((c) => foldWritten(c, was.get(c?.id) ?? null)), extra); const errors = kind.validate(doc, path.basename(file)); if (errors.length) throw new CastError(`refused: ${errors.join("; ")}`); const points = [...(await readCastUndo(file)), { at: new Date().toISOString(), what, text: read.exists ? read.text : null }].slice(-CAST_UNDO_KEEP); @@ -198,9 +202,10 @@ export const undoCast = (file, o) => undoKind(CAST_KIND, file, o); /** * ONE WRITE of a project's own characters (`<dir>/narration/characters.json`): castWrite's rules -- a token, an undo - * point, atomic, refused whole (cast.mjs validateProjectCharacters). Returns `{ ...result, doc, token, undo }`. + * point, atomic, refused whole (cast.mjs validateProjectCharacters). `mutate(characters, { proposed })` may change + * the PROPOSED characters too (the list in place). Returns `{ ...result, doc, token, undo }`. * @param {string} dir the project's folder - * @param {(chars: any[]) => any} mutate + * @param {(chars: any[], extra: { proposed: any[] }) => any} mutate * @param {{ token?: string | null, what?: string }} [o] */ export async function projectCharactersWrite(dir, mutate, o) { diff --git a/umtool/report-to-video/cast-assign.mjs b/umtool/report-to-video/cast-assign.mjs @@ -0,0 +1,226 @@ +// AUTO-ASSIGNMENT BY RULE (characters C3; `umtool cast assign`, the Voices page's Propose): every post item's author +// gets a character -- the one the layers already give them (the item's own, this video's, its voice map's, the +// cast's) or, for an author with none, a PROPOSED character of this video (cast.mjs proposalErrors): an id from the +// handle, the author's name, and a STOCK synthetic voice chosen by rotation through the voices this project does not +// use yet, in one fixed order. A gender hint comes only from the profile's OWN stated pronouns, when the capture +// carries them (`pronouns`, or "she/her" … in `bio`); otherwise the rotation is neutral. No model: a model's +// proposals (`--model`) are laid over these rows by mergeModelProposal, never instead of them. +// +// PURE and dependency-free beyond cast.mjs / post-say.mjs (the CLI and the tests read it). +import { CAST_SPEED, CHARACTER_ID_RE, DIRECTION_MAX, STOCK_VOICES, characterOf, charactersOf, idOfHandle, isStockVoice, projectCharactersOf, proposalErrors, proposalsOf } from "./cast.mjs"; +import { handleKey, voiceRefOf, voiceSpecOf } from "./post-say.mjs"; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const str = (v) => (typeof v === "string" ? v : ""); + +/** The engine a rule's proposal reads in (Kokoro: fast, on the CPU -- the operator's rule, Orpheus heavy). */ +export const ASSIGN_ENGINE = "kokoro"; + +/** A Kokoro voice's gender by its name (`?f_` / `?m_`), or null. */ +export const voiceGender = (voice) => (/^[ab]f_/.test(str(voice)) ? "f" : /^[ab]m_/.test(str(voice)) ? "m" : null); + +/** + * THE ROTATION, in one fixed order: Kokoro's American voices, a male and a female in turn, then its British ones the + * same way -- so a neutral rotation alternates. Every stock Kokoro voice is in it once. + */ +export const ASSIGN_ROTATION = Object.freeze((() => { + const all = STOCK_VOICES.kokoro; + const turn = (a, b) => Array.from({ length: Math.max(a.length, b.length) }, (_, i) => [a[i], b[i]]).flat().filter(Boolean); + const of = (re) => all.filter((v) => re.test(v)); + return [...turn(of(/^am_/), of(/^af_/)), ...turn(of(/^bm_/), of(/^bf_/))].map((v) => `${ASSIGN_ENGINE}:${v}`); +})()); + +/** + * The pronouns an author's profile STATES, read from the capture's own words only: `pronouns` ("she/her"), else a + * "she/her" / "he/him" / "they/them" in `bio` -- `"she" | "he" | "they"`, or null (nothing stated: no hint). + */ +export function statedPronounsOf(who) { + const said = [str(who?.pronouns), str(who?.bio)].join(" ").toLowerCase(); + const m = /\b(she|he|they)\s*\/\s*(her|hers|him|his|them|theirs|she|he|they)\b/.exec(said); + if (!m) return null; + return m[1]; +} + +/** The gender a voice is chosen by for stated pronouns: "f", "m", or null (they: the neutral rotation). */ +const hintOf = (pronouns) => (pronouns === "she" ? "f" : pronouns === "he" ? "m" : null); + +/** + * The next voice of the rotation: the first not in `used` (specs, compared whole) whose gender is the hint's (none: + * any); when every one is used, the one used least among `taken` (this run's proposals) in the rotation's order. + */ +export function rotationVoice(used, { hint = null, taken = [] } = {}) { + const fits = ASSIGN_ROTATION.filter((s) => !hint || voiceGender(voiceRefOf(s)?.voice) === hint); + const pool = fits.length ? fits : ASSIGN_ROTATION; + const free = pool.find((s) => !used.has(s)); + if (free) return free; + const count = (s) => taken.filter((t) => t === s).length; + return [...pool].sort((a, b) => count(a) - count(b) || pool.indexOf(a) - pool.indexOf(b))[0]; +} + +/** The post items' authors in the order they come on: `[{ handle, name, items: id[], named: id[], post: e }]` (`named`: items that name their own character). */ +export function itemAuthorsOf(manifest) { + const out = new Map(); + for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { + if (e?.type !== "post") continue; + const h = handleKey(e.handle); + if (!h || h === "*") continue; + const a = out.get(h) ?? { handle: h, name: "", items: [], named: [], post: e }; + if (!a.name && str(e.author).trim()) a.name = str(e.author).trim(); + a.items.push(e.id); + if (str(e.narration?.character).trim()) a.named.push(e.id); + out.set(h, a); + } + return [...out.values()]; +} + +/** A free id for a handle's proposal: idOfHandle, then `-2`, `-3` … past every id in `taken`. */ +export function freeIdOf(h, taken) { + const base = idOfHandle(h); + if (!taken.has(base)) return base; + for (let n = 2; ; n += 1) { + const id = `${base.slice(0, 48 - String(n).length - 1)}-${n}`; + if (!taken.has(id)) return id; + } +} + +/** + * THE PLAN, pure: for every post item's author, what gives them a character now and, for one with none, the proposal + * -- `{ authors: [{ handle, name, items, state, character?, voice?, proposal? }], proposals: [new], moot: [ids] }`. + * state "item" every item of theirs names its own character (a person chose: left alone) + * "project" this video's character holds the handle "map" its voice map names them (voices.json) + * "cast" the cast's character holds it "proposed" a proposal for them is held already + * "propose" none: `proposal` is the new one + * `moot`: held proposals whose author has a character now (a write drops them). `used` are the voice specs the + * project reads in now (the Voices view's: every author's, the narrator's), laid over the layers' own. + * + * @param {Record<string, any>} manifest + * @param {{ project?: any, cast?: any, map?: Record<string, any>, used?: string[] }} [o] + */ +export function assignPlan(manifest, { project = null, cast = null, map = {}, used = [] } = {}) { + const own = projectCharactersOf(project); + const held = proposalsOf(project); + const castChars = charactersOf(cast); + const usedSet = new Set(used.filter(Boolean)); + for (const c of own) if (c.voice) usedSet.add(c.voice); + for (const c of castChars) if (c.voice) usedSet.add(c.voice); + for (const v of Object.values(isObj(map) ? map : {})) { + const spec = typeof v === "string" ? v : str(v?.voice); + const r = voiceRefOf(spec, ASSIGN_ENGINE); + if (r) usedSet.add(voiceSpecOf(r)); + } + for (const p of held) if (p.synthetic?.voice) usedSet.add(p.synthetic.voice); + const ids = new Set([...own.map((c) => c.id), ...castChars.map((c) => c.id), ...held.map((p) => p.id)]); + const authors = []; + const proposals = []; + const taken = []; + const answered = new Set(); + for (const a of itemAuthorsOf(manifest)) { + const row = { handle: a.handle, name: a.name || a.handle, items: a.items }; + const p = own.find((c) => (c.handles ?? []).includes(a.handle)); + const c = characterOf(cast, a.handle); + const inMap = isObj(map) && Object.prototype.hasOwnProperty.call(map, a.handle); + const prop = held.find((x) => (x.handles ?? []).includes(a.handle)); + if (a.named.length === a.items.length) authors.push({ ...row, state: "item" }); + else if (p) authors.push({ ...row, state: "project", character: p.id, ...(p.voice ? { voice: p.voice } : {}) }); + else if (inMap) authors.push({ ...row, state: "map", voice: typeof map[a.handle] === "string" ? map[a.handle] : str(map[a.handle]?.voice) }); + else if (c) authors.push({ ...row, state: "cast", character: c.id, voice: c.voice }); + else if (prop) authors.push({ ...row, state: "proposed", character: prop.id, voice: prop.synthetic?.voice ?? null, proposal: prop }); + else { + const pronouns = statedPronounsOf(a.post); + const hint = hintOf(pronouns); + const exhausted = ASSIGN_ROTATION.every((s) => usedSet.has(s)); + const voice = rotationVoice(usedSet, { hint, taken }); + usedSet.add(voice); + taken.push(voice); + const id = freeIdOf(a.handle, ids); + ids.add(id); + const proposal = { + id, name: row.name.slice(0, 80), handles: [a.handle], synthetic: { voice }, by: "rule", + why: `no character: ${exhausted ? "every stock voice is in use here; the one this run used least" : "the next stock voice this project does not use"}${pronouns ? ` (their profile states ${pronouns}/…)` : ""}`.slice(0, 300), + }; + proposals.push(proposal); + authors.push({ ...row, state: "propose", character: id, voice, proposal }); + } + if (authors.at(-1).state !== "proposed" && authors.at(-1).state !== "propose") answered.add(a.handle); + } + // A held proposal whose author has a character now (or is no longer in the cut) is moot. + const inCut = new Set(authors.map((a) => a.handle)); + const moot = held.filter((p) => (p.handles ?? []).every((h) => answered.has(h) || !inCut.has(h))).map((p) => p.id); + return { authors, proposals, moot }; +} + +// --------------------------------------------------------------------------- +// The MODEL's answer, merged into the rule's rows (C3, `--model`): untrusted text, schema-checked field by field. +// --------------------------------------------------------------------------- + +/** What a model is asked for, per author: its JSON schema (the local route's `format`, the API's tool input). */ +export const CAST_ASSIGN_SCHEMA = Object.freeze({ + type: "object", + properties: { + authors: { + type: "array", + items: { + type: "object", + properties: { + handle: { type: "string" }, + character: { type: "string" }, + voice: { type: "string", enum: Object.entries(STOCK_VOICES).flatMap(([e, vs]) => vs.map((v) => `${e}:${v}`)) }, + speed: { type: "number", minimum: CAST_SPEED[0], maximum: CAST_SPEED[1] }, + direction: { type: "string" }, + }, + required: ["handle", "character", "voice"], + }, + }, + }, + required: ["authors"], +}); + +/** A short plain line from a model: control characters stripped, white space folded, at most `max`. */ +export const plainLine = (v, max) => str(v).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max); + +/** + * ONE AUTHOR's answer from the model checked, field by field (pure): `{ name?, voice?, speed?, direction? }` with each + * field it got right, and `refused: [why]` for each it did not -- the voice one of STOCK_VOICES, the speed within + * CAST_SPEED, the direction one plain short line, the character name a plain short line. + */ +export function checkModelAnswer(a) { + const out = { refused: [] }; + if (!isObj(a)) return { refused: ["not an object"] }; + const name = plainLine(a.character, 80); + if (name) out.name = name; + else if (a.character !== undefined) out.refused.push("character: not a name"); + const voice = str(a.voice).trim(); + if (isStockVoice(voice)) out.voice = voice; + else if (a.voice !== undefined) out.refused.push(`voice ${JSON.stringify(a.voice).slice(0, 40)}: not a stock voice`); + if (a.speed !== undefined && a.speed !== null) { + const s = Number(a.speed); + if (typeof a.speed === "number" && Number.isFinite(s) && s >= CAST_SPEED[0] && s <= CAST_SPEED[1]) out.speed = Math.round(s * 100) / 100; + else out.refused.push(`speed ${JSON.stringify(a.speed).slice(0, 20)}: not ${CAST_SPEED[0]}-${CAST_SPEED[1]}`); + } + const direction = plainLine(a.direction, DIRECTION_MAX); + if (direction) out.direction = direction; + return out; +} + +/** + * A rule's proposal with the model's checked answer laid over it (pure): its voice, speed, name and direction where + * the model gave a valid one -- and the rule's row as it was when nothing valid came back. `by` is "model" when + * anything of the model's was kept. The result is held to proposalErrors; a result it refuses is the rule's row. + */ +export function mergeModelProposal(rule, answer, { model = null } = {}) { + const ok = checkModelAnswer(answer); + const kept = ["name", "voice", "speed", "direction"].filter((k) => ok[k] !== undefined); + if (!kept.length) return { proposal: rule, kept, refused: ok.refused }; + const p = JSON.parse(JSON.stringify(rule)); + if (ok.name) p.name = ok.name; + p.synthetic = { ...(p.synthetic ?? {}), ...(ok.voice ? { voice: ok.voice } : {}), ...(ok.speed !== undefined && ok.speed !== 1 ? { speed: ok.speed } : {}) }; + if (ok.direction) p.recorded = { direction: ok.direction }; + p.by = "model"; + if (model) p.model = plainLine(model, 80); + p.why = plainLine(`the model's proposal (${kept.join(", ")})${ok.refused.length ? `; refused: ${ok.refused.join("; ")}` : ""}`, 300); + if (proposalErrors(p, "proposal").length) return { proposal: rule, kept: [], refused: [...ok.refused, ...proposalErrors(p, "proposal")] }; + return { proposal: p, kept, refused: ok.refused }; +} + +/** Is `id` a proposal id the store would take? */ +export const isProposalId = (id) => CHARACTER_ID_RE.test(str(id)); diff --git a/umtool/report-to-video/cast-assign.test.mjs b/umtool/report-to-video/cast-assign.test.mjs @@ -0,0 +1,132 @@ +// Auto-assignment by rule (cast-assign.mjs), pure: the rotation, the stated pronouns, the plan for each author, the +// proposals' validation, and a model's answer checked field by field and merged into the rule's row. +// +// Run: node --test umtool/report-to-video/cast-assign.test.mjs +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; +import { ASSIGN_ROTATION, assignPlan, checkModelAnswer, freeIdOf, mergeModelProposal, plainLine, rotationVoice, statedPronounsOf, voiceGender } from "./cast-assign.mjs"; +import { STOCK_VOICES, isStockVoice, proposalCharacter, proposalErrors, validateProjectCharacters } from "./cast.mjs"; + +test("the stock voices are the editor's (common/lib/ttsApps.ts KOKORO_VOICES, ORPHEUS_VOICES)", () => { + const ts = readFileSync(new URL("../../common/lib/ttsApps.ts", import.meta.url), "utf8"); + const list = (name) => [...new RegExp(`export const ${name} = \\[([^\\]]*)\\]`).exec(ts)[1].matchAll(/"([^"]+)"/g)].map((m) => m[1]); + assert.deepEqual([...STOCK_VOICES.kokoro], list("KOKORO_VOICES")); + assert.deepEqual([...STOCK_VOICES.orpheus], list("ORPHEUS_VOICES")); + assert.ok(isStockVoice("kokoro:am_michael") && isStockVoice("orpheus:zac")); + for (const bad of ["am_michael", "kokoro:nobody", "orpheus:am_michael", "kokoro:../x.wav", "", null]) assert.equal(isStockVoice(bad), false, String(bad)); +}); + +test("the rotation: every Kokoro voice once, a male and a female in turn; the next unused, the hint's gender only", () => { + assert.equal(ASSIGN_ROTATION.length, STOCK_VOICES.kokoro.length); + assert.equal(new Set(ASSIGN_ROTATION).size, ASSIGN_ROTATION.length); + assert.deepEqual(ASSIGN_ROTATION.slice(0, 4), ["kokoro:am_adam", "kokoro:af_alloy", "kokoro:am_echo", "kokoro:af_aoede"]); + assert.equal(rotationVoice(new Set()), "kokoro:am_adam"); + assert.equal(rotationVoice(new Set(["kokoro:am_adam"])), "kokoro:af_alloy"); + assert.equal(rotationVoice(new Set(["kokoro:am_adam"]), { hint: "m" }), "kokoro:am_echo"); + assert.equal(rotationVoice(new Set(), { hint: "f" }), "kokoro:af_alloy"); + assert.equal(voiceGender("bf_emma"), "f"); + // All used: the one this run used least, in the rotation's order. + const all = new Set(ASSIGN_ROTATION); + assert.equal(rotationVoice(all, { taken: ["kokoro:am_adam"] }), "kokoro:af_alloy"); +}); + +test("stated pronouns only: the capture's own words, never a guess from a name", () => { + assert.equal(statedPronounsOf({ pronouns: "she/her" }), "she"); + assert.equal(statedPronounsOf({ bio: "Writer. he/him. Opinions mine." }), "he"); + assert.equal(statedPronounsOf({ bio: "they / them" }), "they"); + assert.equal(statedPronounsOf({ author: "Mary Smith", bio: "mother of two" }), null); + assert.equal(statedPronounsOf({}), null); +}); + +const post = (id, handle, author, o = {}) => ({ type: "post", id, handle, author, text: "words", ...o }); + +test("the plan: each author's character from the layers; one with none a PROPOSAL -- rotation past the voices in use, the id from the handle", () => { + const manifest = { + render: {}, + timeline: [ + post("p1", "Host", "Host Man"), + post("p2", "guest", "The Guest"), + post("p3", "stranger", "A Stranger", { pronouns: "she/her" }), + post("p4", "mapped", "In The Map"), + post("p5", "chosen", "Chose", { narration: { character: "host" } }), + post("p6", "kirsche.v", "Kirsche"), + { type: "clip", id: "c1" }, + post("p7", "host", "Host Man"), + ], + }; + const cast = { format: "umtool-cast", version: 2, characters: [{ id: "host", name: "Host Man", handles: ["host"], synthetic: { voice: "kokoro:am_adam" } }] }; + const project = { format: "umtool-project-characters", version: 1, characters: [{ id: "guest", name: "The Guest", handles: ["guest"] }] }; + const plan = assignPlan(manifest, { project, cast, map: { mapped: "kokoro:af_alloy" }, used: ["kokoro:af_heart"] }); + const by = Object.fromEntries(plan.authors.map((a) => [a.handle, a])); + assert.deepEqual(plan.authors.map((a) => a.handle), ["host", "guest", "stranger", "mapped", "chosen", "kirsche.v"], "in the order they come on, once each"); + assert.equal(by.host.state, "cast"); + assert.deepEqual(by.host.items, ["p1", "p7"]); + assert.equal(by.guest.state, "project"); + assert.equal(by.mapped.state, "map"); + assert.equal(by.chosen.state, "item", "every item of theirs names its own character: left alone"); + assert.equal(by.stranger.state, "propose"); + // She/her: the first female voice not used (af_alloy is the map's, af_heart the narrator's). + assert.equal(by.stranger.voice, "kokoro:af_aoede"); + assert.match(by.stranger.proposal.why, /states she/); + // Neutral: the first unused in the rotation (am_adam is the cast's). + assert.equal(by["kirsche.v"].voice, "kokoro:am_echo"); + assert.equal(by["kirsche.v"].proposal.id, "kirsche-v"); + assert.deepEqual(plan.proposals.map((x) => [x.id, x.name, x.handles, x.synthetic, x.by]), [ + ["stranger", "A Stranger", ["stranger"], { voice: "kokoro:af_aoede" }, "rule"], + ["kirsche-v", "Kirsche", ["kirsche.v"], { voice: "kokoro:am_echo" }, "rule"], + ]); + for (const x of plan.proposals) assert.deepEqual(proposalErrors(x, "p"), []); + // Deterministic: the same plan again. + assert.deepEqual(assignPlan(manifest, { project, cast, map: { mapped: "kokoro:af_alloy" }, used: ["kokoro:af_heart"] }), plan); + // Held already: kept as it is, not proposed again; a held one whose author has a character now is moot. + const held = { ...project, proposed: [plan.proposals[0], { id: "gone", name: "Gone", handles: ["guest"], synthetic: { voice: "kokoro:bm_fable" }, by: "rule" }] }; + const again = assignPlan(manifest, { project: held, cast, map: { mapped: "kokoro:af_alloy" } }); + assert.equal(again.authors.find((a) => a.handle === "stranger").state, "proposed"); + assert.deepEqual(again.proposals.map((x) => x.id), ["kirsche-v"]); + assert.notEqual(again.proposals[0].synthetic.voice, "kokoro:af_aoede", "a held proposal's voice is in use"); + assert.deepEqual(again.moot, ["gone"]); +}); + +test("an id is free of every character and proposal", () => { + assert.equal(freeIdOf("Guest", new Set()), "guest"); + assert.equal(freeIdOf("guest", new Set(["guest", "guest-2"])), "guest-3"); + assert.equal(freeIdOf("___", new Set()), "character"); +}); + +test("a proposal is refused unless its voice is a STOCK one, its preset synthetic (a direction at most), its author named", () => { + const ok = { id: "anon", name: "Anon", handles: ["anon"], synthetic: { voice: "kokoro:am_echo" }, by: "rule", why: "no character" }; + assert.deepEqual(proposalErrors(ok, "p"), []); + assert.deepEqual(proposalCharacter(ok), { id: "anon", name: "Anon", handles: ["anon"], synthetic: { voice: "kokoro:am_echo" } }); + assert.match(proposalErrors({ ...ok, synthetic: { voice: "kokoro:nobody" } }, "p").join(), /one of the stock voices/); + assert.match(proposalErrors({ ...ok, synthetic: { voice: "voices/me.wav" } }, "p").join(), /stock/); + assert.match(proposalErrors({ ...ok, recorded: { convert: { voice: "kokoro:am_echo" } } }, "p").join(), /direction line at most/); + assert.match(proposalErrors({ ...ok, handles: [] }, "p").join(), /one handle at least/); + assert.match(proposalErrors({ ...ok, by: "magic" }, "p").join(), /by must be/); + assert.match(proposalErrors({ ...ok, why: "two\nlines" }, "p").join(), /one line/); + const doc = { format: "umtool-project-characters", version: 1, characters: [{ id: "anon", name: "A", handles: [] }], proposed: [ok, ok] }; + const errs = validateProjectCharacters(doc).join("; "); + assert.match(errs, /is a character already/); + assert.match(errs, /two proposals are "anon"/); +}); + +test("the model's answer: untrusted -- a stock voice, a speed in bounds, one plain line; the rule's row stays when nothing is valid", () => { + assert.deepEqual(checkModelAnswer({ character: "The Skeptic", voice: "kokoro:bm_george", speed: 1.15, direction: "dry,\u0007 wry\nand slow" }), { refused: [], name: "The Skeptic", voice: "kokoro:bm_george", speed: 1.15, direction: "dry, wry and slow" }); + const bad = checkModelAnswer({ character: "\u0000", voice: "/etc/passwd", speed: 9, direction: "" }); + assert.equal(bad.voice, undefined); + assert.equal(bad.speed, undefined); + assert.equal(bad.refused.length, 3); + assert.equal(checkModelAnswer({ voice: "kokoro:am_echo", speed: "1.2" }).speed, undefined, "a speed is a number, not words"); + assert.equal(plainLine("a
b\tc", 10), "a b c"); + const rule = { id: "stranger", name: "A Stranger", handles: ["stranger"], synthetic: { voice: "kokoro:af_aoede" }, by: "rule", why: "no character" }; + const m = mergeModelProposal(rule, { character: "The Stranger", voice: "orpheus:tara", speed: 0.9, direction: "warm" }, { model: "qwen3:8b" }); + assert.deepEqual(m.proposal, { id: "stranger", name: "The Stranger", handles: ["stranger"], synthetic: { voice: "orpheus:tara", speed: 0.9 }, by: "model", why: "the model's proposal (name, voice, speed, direction)", recorded: { direction: "warm" }, model: "qwen3:8b" }); + assert.deepEqual(proposalErrors(m.proposal, "p"), []); + assert.equal(mergeModelProposal(rule, { voice: "nope", speed: 7 }).proposal, rule, "nothing valid: the rule's row"); + assert.equal(mergeModelProposal(rule, "not even an object").proposal, rule); + // Part right: the right part kept, the rest said. + const part = mergeModelProposal(rule, { voice: "kokoro:bm_lewis", speed: 5 }); + assert.equal(part.proposal.synthetic.voice, "kokoro:bm_lewis"); + assert.equal(part.proposal.synthetic.speed, undefined); + assert.match(part.proposal.why, /refused: speed 5/); +}); diff --git a/umtool/report-to-video/cast.mjs b/umtool/report-to-video/cast.mjs @@ -279,9 +279,89 @@ export function validateProjectCharacters(doc, where = "characters.json") { if (!Array.isArray(list)) return [...errors, `${where}.characters must be a list`]; if (list.length > CAST_MAX) errors.push(`${where}: at most ${CAST_MAX} characters`); errors.push(...listErrors(list, where, "project")); + if (doc.proposed !== undefined) { + if (!Array.isArray(doc.proposed)) errors.push(`${where}.proposed must be a list`); + else { + if (doc.proposed.length > CAST_MAX) errors.push(`${where}: at most ${CAST_MAX} proposed characters`); + const taken = new Set(list.filter(isObj).map((c) => c.id)); + const seen = new Set(); + doc.proposed.forEach((p, i) => { + const w = `${where}.proposed[${i}]`; + errors.push(...proposalErrors(p, w)); + if (!isObj(p)) return; + if (taken.has(p.id)) errors.push(`${w}: "${p.id}" is a character already (accept makes it one)`); + if (seen.has(p.id)) errors.push(`${w}: two proposals are "${p.id}"`); + seen.add(p.id); + }); + } + } return errors; } +// --------------------------------------------------------------------------- +// PROPOSED characters (C3, `umtool cast assign`): a project character a RULE (or, on request, a model) proposes for +// an author with none -- held apart in the project's characters file (`proposed`, the same writer and undo), applied +// to nothing until a person accepts it. +// --------------------------------------------------------------------------- + +/** + * THE STOCK VOICES a proposal may name, by engine -- common/lib/ttsApps.ts KOKORO_VOICES and ORPHEUS_VOICES (a test + * holds them equal; this file stays dependency-free). Kokoro's are `a*` American, `b*` British, `?f_` female, `?m_` male. + */ +export const STOCK_VOICES = Object.freeze({ + kokoro: Object.freeze([ + "af_alloy", "af_aoede", "af_bella", "af_heart", "af_jessica", "af_kore", "af_nicole", "af_nova", "af_river", "af_sarah", "af_sky", + "am_adam", "am_echo", "am_eric", "am_fenrir", "am_liam", "am_michael", "am_onyx", "am_puck", "am_santa", + "bf_alice", "bf_emma", "bf_isabella", "bf_lily", "bm_daniel", "bm_fable", "bm_george", "bm_lewis", + ]), + orpheus: Object.freeze(["tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe"]), +}); +/** Is `spec` one of the STOCK voices with its engine named ("kokoro:am_michael")? */ +export const isStockVoice = (spec) => { + const r = voiceRefOf(spec); + return !!r?.engine && (STOCK_VOICES[r.engine] ?? []).includes(r.voice); +}; + +/** A proposal's keys: a project character's, and who proposed it (`by`), why, and the model that did. */ +export const PROPOSAL_KEYS = Object.freeze([...PROJECT_CHARACTER_KEYS, "by", "why", "model"]); +export const PROPOSAL_BY = Object.freeze(["rule", "model"]); +export const PROPOSAL_WHY_MAX = 300; + +/** The character a proposal becomes when it is accepted (its own keys dropped), version 2's shape. */ +export function proposalCharacter(p) { + if (!isObj(p)) return p; + const { by: _b, why: _w, model: _m, ...c } = p; + return upgradeCharacter(c); +} + +/** + * What is wrong with ONE proposed character, as sentences that start at `w`: a project character's rules, and more -- + * one handle at least, a SYNTHETIC preset whose voice is one of STOCK_VOICES (never a file, never a convert target: + * a proposal's recorded preset is a direction line at most), who proposed it, a one-line why. + */ +export function proposalErrors(p, w) { + if (!isObj(p)) return [`${w} must be {id, name, handles, synthetic, by, …}`]; + const errors = []; + for (const k of Object.keys(p)) if (!PROPOSAL_KEYS.includes(k)) errors.push(`${w}.${k} is not a proposal's key (${PROPOSAL_KEYS.join(", ")})`); + const c = proposalCharacter(Object.fromEntries(Object.entries(p).filter(([k]) => PROPOSAL_KEYS.includes(k)))); + errors.push(...characterErrors(c, w, { layer: "project" })); + if (!Array.isArray(c.handles) || !c.handles.length) errors.push(`${w}.handles: a proposal is for an author (one handle at least)`); + if (!isObj(c.synthetic) || !isStockVoice(c.synthetic.voice)) errors.push(`${w}.synthetic.voice must be one of the stock voices (${Object.keys(STOCK_VOICES).map((e) => `${e}:…`).join(", ")}), got ${JSON.stringify(c.synthetic?.voice)}`); + if (c.recorded !== undefined && (!isObj(c.recorded) || Object.keys(c.recorded).some((k) => k !== "direction"))) errors.push(`${w}.recorded: a proposal carries a direction line at most (a convert target is set by a person)`); + if (!PROPOSAL_BY.includes(p.by)) errors.push(`${w}.by must be ${PROPOSAL_BY.join(" or ")}`); + if (p.why !== undefined && (typeof p.why !== "string" || p.why.length > PROPOSAL_WHY_MAX || /[\r\n]/.test(p.why))) errors.push(`${w}.why must be one line (at most ${PROPOSAL_WHY_MAX} characters)`); + if (p.model !== undefined && (typeof p.model !== "string" || !p.model.trim() || p.model.length > 80)) errors.push(`${w}.model must be the model's name (at most 80 characters)`); + return errors; +} + +/** A project's PROPOSED characters (the valid-looking ones: an id and a handle), as they are held. */ +export function proposalsOf(doc) { + return (Array.isArray(doc?.proposed) ? doc.proposed : []).filter((p) => isObj(p) && CHARACTER_ID_RE.test(str(p.id)) && Array.isArray(p.handles) && p.handles.length); +} + +/** An id for a handle's new character ("kirsche.verstahl" -> "kirsche-verstahl"). */ +export const idOfHandle = (h) => str(h).toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 48) || "character"; + /** The cast's characters, as views (characterView) -- the invalid ones dropped, never fatal for a reader. */ export function charactersOf(cast) { return (Array.isArray(cast?.characters) ? cast.characters : []).filter((c) => isObj(c) && CHARACTER_ID_RE.test(str(c.id)) && isQualifiedVoice(characterVoice(c))).map(characterView); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -87,6 +87,7 @@ "./post-redact": "./post-redact.mjs", "./post-say": "./post-say.mjs", "./cast": "./cast.mjs", + "./cast-assign": "./cast-assign.mjs", "./post-redact-files": "./post-redact-files.mjs", "./post-slurs": "./post-slurs.mjs", "./post-thread": "./post-thread.mjs",