Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 40 additions & 1 deletion docs/packages/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ npm install -g hyperframes
| Look at it, or share it | [`share`](#share), [`preview`](#preview), [`present`](#present-and-play), [`play`](#present-and-play), [`publish`](#publish), [`open`](#open-and-catch-up), [`catch-up`](#open-and-catch-up) |
| Find problems | [`lint`](#lint), [`check`](#check), [`snapshot`](#snapshot), [`keyframes`](#keyframes), [`compare`](#compare-and-grade-compare), [`grade-compare`](#compare-and-grade-compare) |
| Rebuild a video | [`reverse`](#reverse), [`measure`](#measure), [`diff`](#diff) |
| Edit from the terminal | [`timeline`](#timeline), [`history`](#history) |
| Edit from the terminal | [`timeline`](#timeline), [`history`](#history), [`narration`](#narration) |
| Make a file | [`render`](#render), [`benchmark`](#benchmark) |
| Render somewhere else | [`cloud`](#hyperframes-cloud), [`lambda`](#hyperframes-lambda), [`cloudrun`](#hyperframes-cloudrun) |
| Fix your setup | [`doctor`](#doctor), [`browser`](#browser), [`update`](#update), [`upgrade`](#upgrade), [`docs`](#docs), [`info`](#info-and-compositions), [`compositions`](#info-and-compositions), [`clean`](#clean) |
Expand Down Expand Up @@ -1993,6 +1993,45 @@ use is refused before anything is written.
A refused edit, such as a move that would overlap a neighbour, writes nothing,
exits 2 and says how to fix it.

### `narration`

Keep each voice-over line, its audio clip and its captions in step. `narration.json` at the project
root is the script: each line's text, voice and audio file, and what it was last voiced from. The
clip that plays a line carries `data-narration-line="<id>"`, and caption words can carry
`"line": "<id>"` (untagged words are matched by their clip's time window). Each line's length and
word timings are read from media-use's `audio_meta.json` by the same id. `hyperframes lint` reports
drift between them.

```bash
npx hyperframes narration init # adopt a voiced project (media-use's audio_meta.json, or tagged clips)
npx hyperframes narration list # each line and whether it is in sync
npx hyperframes narration check # exits 1 when voice, clips and captions drifted
npx hyperframes narration set l2 "Twenty renewals are due today."
npx hyperframes narration set l2 --dry-run # what would change, written nowhere
```

| Command | What it does |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `init` | Write `narration.json` from media-use's `audio_meta.json` and `audio_request.json`, or from clips already tagged with `data-narration-line`, and tag each line's clip. `--force` replaces an existing file. |
| `list` | Each line with its length and its narration findings, or "in sync". |
| `check` | The narration findings from `lint`; exits 1 when any warning remains. |
| `set <id> [text]` | Re-voice one line with Kokoro, transcribe that clip alone outside the project, then update the clip's `src` and `data-duration`, that line's caption words, `caption-overrides.json`, `narration.json` and the line's voice in `audio_meta.json` together, as one `history` entry. |

| Flag (`set`) | Description |
| ------------- | --------------------------------------------------------------------------------- |
| `--voice` | Kokoro voice for this line |
| `--speed` | Speech speed for this line (0.1 to 3) |
| `--dry-run` | Show what would change; write nothing |
| `--no-retime` | Keep a longer take that runs into the next narration clip, instead of refusing it |
| `--force` | Re-voice even when the text, voice and WAV are unchanged |

Every command also takes `--dir` and `--json`; `init` and `set` take `--who` (your agent name, for
the `history` entry). `set` re-voices with Kokoro only: a local voice gives the same audio for the
same text, so a re-voiced line still sounds like its neighbours. Lines voiced by a service whose
voices may not repeat are refused; re-voice all of them with media-use instead. The new take is
written as `assets/voice/<id>-<hash>.wav` and the old file is kept, so `history undo` always finds
the audio it points back to.

### `history`

List, undo and restore the project's recorded changes. Each change is an entry
Expand Down
40 changes: 40 additions & 0 deletions docs/reference/lint-rules.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -886,6 +886,46 @@ Source: `packages/lint/src/rules/linkedClips.ts`.

**Fix:** Give every member the same `data-start`, `data-duration`, `data-media-start` and `data-playback-rate`, or remove `data-link` from all of them to unlink.

## Narration

Source: `packages/lint/src/projectNarration.ts`. These run only when the project has a `narration.json`: the script of a narrated video, listing each voiced line's text and voice, linked to the `<audio data-narration-line="...">` clip that speaks it and to the caption words that show it. Each line's length and word timings are read from media-use's `audio_meta.json` by the same line id; without that file, the length isn't checked and a line's captions only need to fall inside its clip. They are warnings and infos, so drift never blocks a render.

### `narration_manifest_invalid`

**Warning.** `narration.json` is not valid JSON, or a field has the wrong shape (a line without a plain id, text or audio file, or a `voiced` record without its hashes).

**Fix:** Fix the listed fields, or recreate the file with `hyperframes narration init`.

### `narration_line_unlinked`

**Warning.** A line in `narration.json` has no `<audio data-narration-line>` clip on the timeline, is linked from more than one clip, or a clip names a line the manifest does not list.

**Fix:** Put `data-narration-line="<id>"` on the one `<audio>` that plays the line, or remove it from the clip.

### `narration_audio_stale`

**Warning.** A line's text, voice settings or WAV changed since it was voiced (its `voiced` record), or its audio file is missing, so the voice no longer says what the script says.

**Fix:** Run `hyperframes narration set <id>` to re-voice the line and update its captions.

### `narration_clip_timing_mismatch`

**Warning.** The line's clip plays for more than 0.05 s longer or shorter than `audio_meta.json` says its voice lasts, so the voice is cut off or followed by silence. Checked only when `audio_meta.json` describes the line's own audio file.

**Fix:** Set the clip's `data-duration` to the length `audio_meta.json` records for the line, or run `hyperframes narration set <id>`.

### `narration_captions_out_of_sync`

**Warning.** The caption words that show a line (tagged with `"line": "<id>"`, or untagged words inside its clip) differ in number from the voice's words in `audio_meta.json`, or one starts more than 0.1 s from where the voice says it. Without `audio_meta.json`: a tagged word starts outside the line's clip.

**Fix:** Run `hyperframes narration set <id>`, which re-times that line's caption words from its voice.

### `narration_transcript_mismatch`

**Info.** A line's captions are in sync with its voice but read differently from its text, often because a transcriber wrote a number as digits (47 for forty-seven).

**Fix:** Usually none. Edit the caption words if they should match the script.

## Project-level checks

Source: the project lint pass in `packages/lint/src/project.ts`, `packages/lint/src/hyperframeLinter.ts` and `packages/lint/src/hevcPreviewLint.ts`.
Expand Down
5 changes: 3 additions & 2 deletions packages/cli/src/cli.jsonFlag.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ const WITH_JSON = names(`
measure frames, measure hands, measure ink, measure look, measure probe, measure sync,
media-treatment, media-use adopt, media-use analyze, media-use avatars, media-use candidates,
media-use doctor, media-use from, media-use generate, media-use params, media-use resolve,
media-use reuse, media-use stats, media-use voices, models, normalize-audio, open, preview,
media-use reuse, media-use stats, media-use voices, models, narration check,
narration init, narration list, narration set, normalize-audio, open, preview,
remove-background, render, reverse start, share, skills check, skills update, snapshot,
telemetry, timeline apply, timeline delete, timeline duplicate, timeline ids, timeline move,
timeline set, timeline split, timeline trim, timeline undo, transcribe, tts, update, upgrade,
Expand All @@ -70,7 +71,7 @@ const WITHOUT_JSON = names(`

// Command words that take subcommands, run on their own. REFUSED answer `json_unsupported`.
const REFUSED_PARENTS = names("auth, cloud, figma, media-use, skills");
const OTHER_PARENTS = names("history, measure, reverse, timeline");
const OTHER_PARENTS = names("history, measure, narration, reverse, timeline");

interface Leaf {
path: string[];
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ const commandLoaders = {
usage: () => import("./commands/usage.js").then((m) => m.default),
models: () => import("./commands/models.js").then((m) => m.default),
tts: () => import("./commands/tts.js").then((m) => m.default),
narration: () => import("./commands/narration.js").then((m) => m.default),
docs: () => import("./commands/docs.js").then((m) => m.default),
doctor: () => import("./commands/doctor.js").then((m) => m.default),
clean: () => import("./commands/clean.js").then((m) => m.default),
Expand Down
225 changes: 225 additions & 0 deletions packages/cli/src/commands/narration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
import { terminalLines } from "@hyperframes/core";
import { type ArgsDef } from "citty";
import { defineCommand } from "../utils/defineCommand.js";
import type { Example } from "./_examples.js";
import { setCommandExitCode } from "../utils/commandResult.js";
import { jsonFailure } from "../utils/jsonError.js";
import { resolveProject } from "../utils/project.js";
import { withMeta } from "../utils/updateCheck.js";
import { NarrationRefusal } from "../narration/project.js";

export const examples: Example[] = [
["Adopt a voiced project into narration.json", "hyperframes narration init"],
["List each line and whether it is in sync", "hyperframes narration list"],
["Fail when voice, clips and captions have drifted", "hyperframes narration check"],
[
"Change one line: re-voice it and update its captions",
'hyperframes narration set l2 "Twenty renewals are due today."',
],
["See what a change would write, without writing", "hyperframes narration set l2 --dry-run"],
];

const common = {
dir: { type: "string", description: "Project directory (default: current)" },
json: { type: "boolean", description: "Output as JSON", default: false },
} as const;

function print(json: boolean, data: unknown, text: string): void {
console.log(
json ? JSON.stringify(withMeta(data as Record<string, unknown>), null, 2) : terminalLines(text),
);
}

/** A refusal is the caller's to fix: exit 2 with its message, never a stack. */
function refused(error: unknown, json: boolean | undefined): void {
if (!(error instanceof NarrationRefusal)) throw error;
setCommandExitCode(2);
if (json) print(true, jsonFailure("refused", error.message), error.message);
else console.error(terminalLines(error.message));
}

interface Narrated {
meta: { name: string; description: string };
args?: ArgsDef;
}

/** A narration subcommand: shared --dir and --json, and refusals printed instead of thrown. */
function narrated<A extends { json?: boolean }>(
{ meta, args = {} }: Narrated,
task: (args: A) => Promise<void>,
) {
return defineCommand({
meta,
args: { ...common, ...args },
async run(context) {
const parsed = context.args as unknown as A;
await task(parsed).catch((error: unknown) => refused(error, parsed.json));
},
});
}

const projectDir = (dir: string | undefined) => resolveProject(dir).dir;

const subCommands = {
list: () =>
narrated<{ dir?: string; json: boolean }>(
{
meta: { name: "list", description: "List narration lines and whether each is in sync" },
args: {},
},
async (args) => {
const { narrationStatus } = await import("../narration/status.js");
const { lines } = await narrationStatus(projectDir(args.dir));
const text = lines
.map((line) => {
const state = line.problems.length ? line.problems.join(", ") : "in sync";
const length = line.durationSeconds === null ? "?" : `${line.durationSeconds}s`;
return `${line.id.padEnd(6)} ${length.padStart(7)} ${state.padEnd(32)} ${line.text}`;
})
.join("\n");
print(args.json, { lines }, text || "narration.json has no lines.");
},
),
check: () =>
narrated<{ dir?: string; json: boolean }>(
{
meta: { name: "check", description: "Report narration drift; exits 1 when there is any" },
args: {},
},
async (args) => {
const { narrationStatus } = await import("../narration/status.js");
const { findings } = await narrationStatus(projectDir(args.dir));
const drift = findings.filter((finding) => finding.severity !== "info");
if (drift.length > 0) setCommandExitCode(1);
const text = findings.length
? findings.map((f) => `${f.severity} ${f.code}: ${f.message}`).join("\n")
: "Narration is in sync: every line's voice, clip and captions match narration.json.";
print(args.json, { ok: drift.length === 0, findings }, text);
},
),
init: () =>
narrated<{ dir?: string; json: boolean; force: boolean; who?: string }>(
{
meta: {
name: "init",
description: "Create narration.json from a voiced project and link each line's clip",
},
args: {
force: {
type: "boolean",
default: false,
description: "Replace an existing narration.json",
},
who: { type: "string", description: "Your agent name, for the history entry" },
},
},
async (args) => {
const { runNarrationInit } = await import("../narration/init.js");
const result = await runNarrationInit({
dir: projectDir(args.dir),
force: args.force,
who: args.who,
});
const unlinked = result.unlinked.length
? `\nNo clip plays: ${result.unlinked.join(", ")}; add data-narration-line to their <audio>.`
: "";
print(
args.json,
result,
`Wrote narration.json with ${result.lines.length} lines from ${result.source}; linked ${result.linked.length} clips${result.captions ? `, captions in ${result.captions}` : ""}.${unlinked}`,
);
},
),
set: () =>
narrated<{
id: string;
text?: string;
dir?: string;
json: boolean;
voice?: string;
speed?: string;
"dry-run": boolean;
retime: boolean;
force: boolean;
who?: string;
}>(
{
meta: {
name: "set",
description:
"Re-voice one line and update its clip, captions and narration.json together",
},
args: {
id: { type: "positional", required: true, description: "The line's id, such as l2" },
text: {
type: "positional",
required: false,
description: "New text (default: keep the line's text)",
},
voice: { type: "string", description: "Kokoro voice for this line" },
speed: { type: "string", description: "Speech speed for this line (0.1 to 3)" },
"dry-run": {
type: "boolean",
default: false,
description: "Show what would change; write nothing",
},
retime: {
type: "boolean",
default: true,
description:
"Refuse a longer take that runs into the next narration clip (--no-retime keeps it)",
},
force: {
type: "boolean",
default: false,
description: "Re-voice even when nothing changed",
},
who: { type: "string", description: "Your agent name, for the history entry" },
},
},
async (args) => {
const speed = args.speed === undefined ? undefined : Number(args.speed);
if (speed !== undefined && !(speed >= 0.1 && speed <= 3)) {
throw new NarrationRefusal("--speed takes a number from 0.1 to 3");
}
const { runNarrationSet } = await import("../narration/set.js");
const result = await runNarrationSet({
dir: projectDir(args.dir),
line: args.id,
text: args.text,
voice: args.voice,
speed,
dryRun: args["dry-run"],
allowOverlap: !args.retime,
force: args.force,
who: args.who,
});
print(args.json, result, describeSet(result));
},
),
};

function describeSet(
result: Awaited<ReturnType<typeof import("../narration/set.js").runNarrationSet>>,
) {
if (result.kind === "unchanged") {
return `Line ${result.line} is already voiced from its text; pass --force to re-voice it anyway.`;
}
const verb = result.kind === "planned" ? "Would write" : "Wrote";
const captions = result.captions
? ` ${result.captions.removed} caption words became ${result.captions.added} in ${result.captions.file}.`
: " No caption array was found.";
const dropped = result.overridesDropped
? ` Dropped ${result.overridesDropped} caption override(s) on words that changed.`
: "";
const warnings = result.warnings.map((warning) => `\nWarning: ${warning}`).join("");
return `${verb} line ${result.line}: ${result.durationSeconds}s, ${result.words} words, ${result.audio}.${captions}${dropped}\nFiles: ${result.files.join(", ")}${warnings}`;
}

export default defineCommand({
meta: {
name: "narration",
description: "Keep each voice-over line, its audio clip and its captions in step",
},
subCommands,
});
1 change: 1 addition & 0 deletions packages/cli/src/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ const GROUPS: Group[] = [
],
["models", "List or download on-device models (models list, models install parakeet)"],
["tts", "Generate speech audio from text using a local AI model (Kokoro-82M)"],
["narration", "Keep each voice-over line, its audio clip and its captions in step"],
["remove-background", "Remove background from a video or image to produce transparent media"],
],
},
Expand Down
Loading