The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Edit speech: the words you change become small windows AuK re-speaks in the same voice, crossfaded back without clicks
Claudec6fe598e9bdd
diff --git a/src/app/api/audio-tools/route.ts b/src/app/api/audio-tools/route.tsindex d20426a0..47cd2480 100644--- a/src/app/api/audio-tools/route.ts+++ b/src/app/api/audio-tools/route.ts@@ -15,7 +15,7 @@ const MESSAGES: Record<string, string> = {/*** Audio → Loop / extend, Join, Split soundtrack (and its Clean up dialogue) and Clean up voice (and a split's mix put back on its video), and Video- * tools → Remove dialogue: start a run; `?preview=1` only plans and prices it.+ * tools → Remove dialogue, and Audio → Edit speech: start a run; `?preview=1` only plans and prices it.*/async function post(request: Request) {const raw: unknown = await request.json().catch(() => null);@@ -31,7 +31,13 @@ async function post(request: Request) {? "Add the video to take the dialogue out of": (tool === "clean" || tool === "clean-dialogue") && path === "media"? "Add the audio or video to clean"- : (MESSAGES[path] ?? "Check the settings");+ : tool === "speech-edit"+ ? path === "media"+ ? "Add the recording to edit"+ : path.startsWith("cues") || path.startsWith("edited")+ ? "Transcribe the recording first, then edit its lines"+ : "Pick one of the offered settings for the effect"+ : (MESSAGES[path] ?? "Check the settings");return Response.json({ error: msg }, { status: 400 });}const preview = new URL(request.url).searchParams.get("preview") === "1";diff --git a/src/lib/av/speech-edit-graph.ts b/src/lib/av/speech-edit-graph.tsnew file mode 100644index 00000000..20312825--- /dev/null+++ b/src/lib/av/speech-edit-graph.ts@@ -0,0 +1,181 @@+import type { ComfyNode, ComfyWorkflow } from "@/lib/comfy";+import { AUK_SETTINGS, SPEECH_CROSSFADE, stitchPlan, type AukQuality, type SpeechWindow } from "@/lib/speech-edit";++/**+ * Edit speech's graph (speech-edit-auk, nm10-speech-edit) for any number of windows, in one prompt: the hand-built+ * template binds the recording, the fade-in curve (written by the provider: a linear ramp, then a flat tail that+ * AudioMerge trims off), AuK's loader and one window. This rebuilds the windows and the stitch from+ * src/lib/speech-edit.ts's stitchPlan: each window is cut from the original, edited by AuK (one AuKGenerateEdit each, one+ * shared engine), and crossfaded back over the original's first and last SPEECH_CROSSFADE seconds of the window. Only+ * core audio nodes besides AuK's (TrimAudioDuration, AudioMerge, AudioConcat, SplitAudioChannels, EmptyAudio).+ *+ * Clicks: AudioMerge resamples the lower-rate side of a merge, and a resampled piece tapers at its edges. So the+ * recording and each edit are brought to one rate first (each merged with silence at the other's rate: AuK speaks at+ * 24 kHz), and a seam is a + (b − a) × fade-in, which uses only the curve that starts at 0 and whose end is cut away.+ */++const ids = (wf: ComfyWorkflow, type: string) => Object.keys(wf).filter((id) => wf[id].class_type === type);+const linkFrom = (v: unknown): string | undefined => (Array.isArray(v) && typeof v[0] === "string" ? v[0] : undefined);+const r3 = (n: number) => Math.round(n * 1000) / 1000;++/** Plenty: TrimAudioDuration stops at the end of the audio. */+const REST = 100000;+/** AuK's output rate (its VAE's target_sample_rate in config.yaml at the pinned revisions). */+export const AUK_RATE = 24000;+/** The flat tail after the ramp: longer than the resampler's reach, trimmed off by AudioMerge. */+export const FADE_TAIL = 0.05;++/**+ * The fade-in curve as a 16-bit stereo PCM WAV at 8 kHz: a linear ramp from 0 to 1 over `seconds`, then FADE_TAIL+ * seconds at 1 (both channels the same; the graph reads the left one).+ */+export function speechFadeWav(seconds: number, rate = 8000): Uint8Array {+ if (!(seconds > 0)) throw new Error("A crossfade needs a length above 0 s");+ const ramp = Math.max(2, Math.round(seconds * rate));+ const n = ramp + Math.round(FADE_TAIL * rate);+ const bytes = new Uint8Array(44 + n * 4);+ const v = new DataView(bytes.buffer);+ const text = (o: number, str: string) => [...str].forEach((c, i) => v.setUint8(o + i, c.charCodeAt(0)));+ text(0, "RIFF");+ v.setUint32(4, 36 + n * 4, true);+ text(8, "WAVE");+ text(12, "fmt ");+ v.setUint32(16, 16, true);+ v.setUint16(20, 1, true);+ v.setUint16(22, 2, true);+ v.setUint32(24, rate, true);+ v.setUint32(28, rate * 4, true);+ v.setUint16(32, 4, true);+ v.setUint16(34, 16, true);+ text(36, "data");+ v.setUint32(40, n * 4, true);+ for (let i = 0; i < n; i++) {+ const g = Math.round(Math.min(1, i / (ramp - 1)) * 32767);+ v.setInt16(44 + i * 4, g, true);+ v.setInt16(46 + i * 4, g, true);+ }+ return bytes;+}++export interface SpeechGraphOptions {+ /** Seconds the recording runs. */+ duration: number;+ quality?: AukQuality;+ seed?: number;+ crossfade?: number;+}++export function expandSpeechEditWorkflow(wf: ComfyWorkflow, windows: SpeechWindow[], o: SpeechGraphOptions): ComfyWorkflow {+ if (!windows.length) throw new Error("Nothing to change: edit the words, or pick a range and an effect");+ const [split] = ids(wf, "SplitAudioChannels");+ const curve = split ? linkFrom(wf[split].inputs.audio) : undefined;+ const [source] = ids(wf, "LoadAudio").filter((id) => id !== curve);+ const [loader] = ids(wf, "AuKModelLoader");+ const [gen] = ids(wf, "AuKGenerateEdit");+ const [trim] = ids(wf, "TrimAudioDuration");+ const [merge] = ids(wf, "AudioMerge");+ const [concat] = ids(wf, "AudioConcat");+ const [empty] = ids(wf, "EmptyAudio");+ const [save] = Object.keys(wf).filter((id) => /^SaveAudio/.test(wf[id].class_type));+ if (!split || !curve || !source || !loader || !gen || !trim || !merge || !concat || !empty || !save) {+ throw new Error("Not an Edit speech workflow (needs the recording, the fade curve, AuK's loader and edit node, silence, trims, merges, concats and a save)");+ }+ const x = o.crossfade ?? SPEECH_CROSSFADE;+ const settings = AUK_SETTINGS[o.quality ?? "fast"];+ const out: ComfyWorkflow = {};+ for (const id of [source, curve, split, loader, empty, save]) out[id] = structuredClone(wf[id]);+ out[loader].inputs.checkpoint_path = settings.checkpoint;+ Object.assign(out[empty].inputs, { duration: 0.05, sample_rate: AUK_RATE, channels: 1 });+ const fadeIn = [split, 0];+ const add = (id: string, node: ComfyNode) => ((out[id] = node), id);+ const cut = (id: string, from: string, start: number, duration: number) =>+ add(id, { class_type: wf[trim].class_type, inputs: { ...wf[trim].inputs, audio: [from, 0], start_index: r3(start), duration: r3(duration) } });+ const mix = (id: string, a: string, b: unknown, method: string) => add(id, { class_type: wf[merge].class_type, inputs: { ...wf[merge].inputs, audio1: [a, 0], audio2: b, merge_method: method } });+ const join = (id: string, a: string, b: string) => add(id, { class_type: wf[concat].class_type, inputs: { ...wf[concat].inputs, audio1: [a, 0], audio2: [b, 0], direction: "after" } });++ // The recording at max(its rate, AuK's): silence at 24 kHz added.+ const src = mix("src", source, [empty, 0], "add");+ const edits = windows.map((w, k) => {+ const n = k + 1;+ const input = cut(`w${n}_cut`, src, w.start, w.end - w.start);+ const auk = add(`w${n}_auk`, {+ class_type: wf[gen].class_type,+ inputs: {+ ...wf[gen].inputs,+ engine: [loader, 0],+ instruction: w.instruction,+ generation_seconds: w.seconds,+ use_prompt_enhancer: false,+ seed: (o.seed ?? Number(wf[gen].inputs.seed ?? 42)) + k,+ nfe_steps: settings.steps,+ cfg_strength: settings.cfg,+ sway_sampling_coef: -1,+ input_audio: [input, 0],+ },+ _meta: { title: w.label.slice(0, 80) },+ });+ // The edit at the recording's rate: silence cut from the window (window − window) added.+ return mix(`w${n}_edit`, auk, [mix(`w${n}_zero`, input, [input, 0], "subtract"), 0], "add");+ });++ let acc: string | undefined;+ const append = (id: string) => (acc = acc ? join(`j${Object.keys(out).length}`, acc, id) : id);+ stitchPlan(windows, o.duration, x).forEach((p, i) => {+ const tag = `p${i + 1}`;+ if (p.kind === "source") append(cut(`${tag}_orig`, src, p.from, Math.abs(p.to - o.duration) < 1e-6 ? REST : p.to - p.from));+ else if (p.kind === "edit") append(cut(`${tag}_edit`, edits[p.window], p.from, p.to - p.from));+ else {+ // A seam from a (leaving) to b (coming): a + (b − a) × fade-in.+ const w = windows[p.window];+ const orig = cut(`${tag}_o`, src, p.at, p.length);+ const edit = cut(`${tag}_e`, edits[p.window], p.kind === "seam-in" ? 0 : w.seconds - p.length, p.length);+ const [a, b] = p.kind === "seam-in" ? [orig, edit] : [edit, orig];+ append(mix(`${tag}_seam`, a, [mix(`${tag}_ramp`, mix(`${tag}_diff`, b, [a, 0], "subtract"), fadeIn, "multiply"), 0], "add"));+ }+ });+ out[save].inputs.audio = [acc!, 0];+ return out;+}++/** AuK's loader device and dtype for the server's torch device: an NVIDIA GPU in bf16, a CPU in fp32 (its node's rule). */+export function aukDevice(device: string | undefined): { device: string; dtype: string } {+ if (device === "cpu") return { device: "cpu", dtype: "fp32" };+ if (device === "mps") throw new Error("AuK runs on an NVIDIA GPU (or, slowly, a CPU): its nodes don't support Apple's GPU");+ return { device: "cuda:0", dtype: "bf16" };+}++/** Sets AuK's loader(s) for the device. */+export function setAukDevice(wf: ComfyWorkflow, device: string | undefined): ComfyWorkflow {+ const d = aukDevice(device);+ for (const id of ids(wf, "AuKModelLoader")) Object.assign(wf[id].inputs, d);+ return wf;+}++/** The edit windows a request carries (params.extra.speechWindows), checked; null when absent or malformed. */+export function readSpeechWindows(v: unknown): SpeechWindow[] | null {+ if (!Array.isArray(v) || !v.length) return null;+ const out: SpeechWindow[] = [];+ for (const w of v) {+ const x = w as Partial<SpeechWindow>;+ const ok = typeof x?.start === "number" && typeof x.end === "number" && typeof x.seconds === "number" && typeof x.instruction === "string" && x.instruction.trim() && x.end > x.start && x.start >= 0 && x.seconds > 0;+ if (!ok) return null;+ out.push({ start: x.start!, end: x.end!, seconds: x.seconds!, instruction: x.instruction!.slice(0, 1000), label: typeof x.label === "string" ? x.label.slice(0, 200) : "Edit" });+ }+ return out.sort((a, b) => a.start - b.start);+}++/**+ * AuK's text to speech (speech-tts-auk): the generation's length on the edit node, and without a voice sample the loader+ * taken out (instruct TTS from the description alone).+ */+export function aukTtsWorkflow(wf: ComfyWorkflow, o: { seconds: number; hasVoice: boolean }): ComfyWorkflow {+ const [gen] = ids(wf, "AuKGenerateEdit");+ if (!gen) throw new Error("Not an AuK workflow");+ wf[gen].inputs.generation_seconds = o.seconds;+ if (!o.hasVoice) {+ const src = linkFrom(wf[gen].inputs.input_audio);+ delete wf[gen].inputs.input_audio;+ if (src && wf[src]?.class_type === "LoadAudio") delete wf[src];+ }+ return wf;+}diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.tsindex ff775c4f..1d967400 100644--- a/src/lib/catalog/models.ts+++ b/src/lib/catalog/models.ts@@ -1285,6 +1285,19 @@ const open: ModelDef[] = [routes: [comfy("voice-design", "tts-voxcpm2"), comfy("tts", "tts-voxcpm2-clone")],options: { voiceClone: true, seed: true },}),+ // Edit speech (nm10-speech-edit): Tencent AuK (MIT) changes words, pitch, pace, emotion and noise in a recording, and+ // speaks a line in a voice. Hosted on neither fal nor Replicate, so it runs on your GPU only (src/lib/speech-edit.ts).+ o({+ id: "oss-auk",+ name: "AuK",+ vendor: "Tencent",+ family: "auk",+ kind: "audio",+ tagline: "Change what was said in a recording, or how it was said: words, pitch, pace, emotion, noise",+ badges: ["new"],+ routes: [comfy("speech-edit", "speech-edit-auk", "every edit window in one job"), comfy("tts", "speech-tts-auk")],+ options: { voiceClone: true, seed: true },+ }),o({id: "oss-chatterbox-dialogue",name: "Chatterbox Dialogue",diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.tsindex a59510fd..17f650f9 100644--- a/src/lib/catalog/plan.ts+++ b/src/lib/catalog/plan.ts@@ -235,7 +235,7 @@ const PROMPTLESS = new Set<Operation>(["concat", "frame", "color-match", "finalize", "reframe", "dialogue", "voice-change", "dub", "bg-remove-video", "depth-video", "upscale-image", "upscale-video", "bg-remove","interpolate", "v2a", "face-swap", "motion-transfer", "lipsync", "avatar",// round 3: tools that work from their inputs (open caption burn-in takes timed lines as its prompt and says so when they're missing)- "trim", "transcribe", "mux", "separate-audio", "enhance-voice", "layers", "image-to-3d", "captions", "text-layers", "vectorize", "level",+ "trim", "transcribe", "mux", "separate-audio", "enhance-voice", "speech-edit", "layers", "image-to-3d", "captions", "text-layers", "vectorize", "level",// av-tools: the dub voice track (clips placed on the video's timeline)"timeline",// round 4: tools that work from their inputs (removing an object needs a prompt only on models that read one)@@ -497,6 +497,7 @@ export function planGeneration(if (op === "dialogue" && !params.dialogue?.some((l) => l.text.trim())) throw new Error("Write at least one line");if (op === "dub" && !params.targetLanguage) throw new Error("Pick a language to translate into");if (op === "voice-design" && !params.voiceDescription?.trim()) throw new Error("Describe the voice you want");+ if (op === "speech-edit" && !(Array.isArray(params.extra?.speechWindows) && params.extra.speechWindows.length)) throw new Error("Edit the words, or pick a range and an effect");if (model.options.motionPaths && !(params.extra?.motionPaths as { paths?: unknown[] } | undefined)?.paths?.length) {throw new Error(`Draw on the start frame — ${model.name} moves things along the paths you draw`);}@@ -780,6 +781,7 @@ const NEEDS: Partial<transcribe: { oneOf: ["audio", "video"], msg: "Add the audio or video to transcribe" },"separate-audio": { oneOf: ["audio", "video"], msg: "Add the audio or video to split" },"enhance-voice": { oneOf: ["audio", "video"], msg: "Add the audio or video to clean" },+ "speech-edit": { oneOf: ["audio", "video"], msg: "Add the recording to edit" },level: { audio: true, msg: "Add the audio to level" },// round 4"remove-object": { video: true, msg: "Add the video to remove something from" },diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex 06f1d0f4..43f8d994 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -93,7 +93,9 @@ export type Operation =| "insert-moment" // video + params.startTime / params.endTime (+ prompt, reference images and clips, params.duration: the new scene's length) → the clip with a new scene between them| "retexture-3d" // 3D model (inputs.model3d) + prompt or a style image → the same model with new textures// nm10-voice-design- | "voice-design"; // params.voiceDescription (who is speaking) + prompt (the line) → the line in a new voice made from the words+ | "voice-design" // params.voiceDescription (who is speaking) + prompt (the line) → the line in a new voice made from the words+ // nm10-speech-edit+ | "speech-edit"; // audio or video (its soundtrack) + params.extra.speechWindows (src/lib/speech-edit.ts) → the recording with those parts changed (AuK)export const OPERATION_LABELS: Record<Operation, string> = {t2i: "Text to image",@@ -124,6 +126,7 @@ export const OPERATION_LABELS: Record<Operation, string> = {dialogue: "Dialogue","voice-change": "Voice change","voice-design": "Design a voice",+ "speech-edit": "Edit speech",dub: "Translate & dub","bg-remove-video": "Video background removal","depth-video": "Video depth map",@@ -199,6 +202,7 @@ export const OPERATION_OUTPUT: Record<Operation, MediaKind> = {dialogue: "audio","voice-change": "audio","voice-design": "audio",+ "speech-edit": "audio",dub: "video","bg-remove-video": "video","depth-video": "video",diff --git a/src/lib/comfy.ts b/src/lib/comfy.tsindex fcd74300..e1b57352 100644--- a/src/lib/comfy.ts+++ b/src/lib/comfy.ts@@ -114,9 +114,10 @@ export interface ManifestWorkflow {/*** The provider rewrites the graph before submitting ("captions": one segment per caption cue;* "timeline": one loader per audio clip, each placed at its start time; "videos" / "audios": one loader- * per clip of a join, src/lib/av/joins.ts).+ * per clip of a join, src/lib/av/joins.ts; "speech": every Edit speech window of params.extra.speechWindows,+ * src/lib/av/speech-edit-graph.ts).*/- expand?: "captions" | "timeline" | "videos" | "audios";+ expand?: "captions" | "timeline" | "videos" | "audios" | "speech";validated: boolean;/** What ComfyUI answered when it last refused this graph. */validationError?: string;diff --git a/src/lib/speech-edit.ts b/src/lib/speech-edit.tsnew file mode 100644index 00000000..c12e885e--- /dev/null+++ b/src/lib/speech-edit.ts@@ -0,0 +1,669 @@+/**+ * Audio → Edit speech (nm10-speech-edit): change what was said in a recording, or how it was said, with Tencent's AuK+ * (MIT, open engine only: AuK is hosted on neither fal nor Replicate). Pure data and logic shared by the page, the server+ * (src/server/audio-tools.ts, tool "speech-edit"), the provider (src/server/providers/comfyui.ts) and Assist's+ * edit_speech tool.+ *+ * The flow: a transcript with times (Transcribe's lines; their words are timed by length inside each line) → the person+ * edits the text → the edit is diffed to the smallest changed span of words → a window around it, cut at silences, with at+ * least CONTEXT_MIN seconds of untouched speech on each side (AuK needs the voice around the change to match it) → AuK's+ * content-edit instruction ("Replace 'X' with 'Y'.") on that window → the edited window crossfaded back into the original+ * (the speech-edit-auk graph does it with core audio nodes, one prompt for every window). Several edits run as several+ * windows in that one prompt; windows that would touch are merged into one edit first.+ *+ * Pitch, pace, volume, emotion, whisper, Clean up (noise and room echo) and Keep only this speaker run on a picked range+ * the same way, the range split at silences into windows AuK can take.+ *+ * AuK's limit (its ComfyUI node, docs/COMFYUI.md at the pinned commit): the source audio plus the audio it makes must fit+ * in 30 seconds per call, and the node doesn't split. So a window plus its new length stays under AUK_SEQUENCE_MAX minus a+ * margin for the model's frame rounding: a same-length effect takes at most ~14.7 s of speech per window.+ */+import type { Cue } from "./cues";+import type { Engine, GenerationRequest } from "./catalog/types";+import type { ToolPlan, ToolStep } from "./av/audio-tools";++export const SPEECH_EDIT_FEATURE = "speech-edit";+export const SPEECH_EDIT_MODEL = "oss-auk";+/** The stream-copy mux that puts the edited sound back on a video (video-mux-audio-replace). */+export const SPEECH_EDIT_MUX_MODEL = "oss-mux";++/** Source + generated seconds per AuK call (its node refuses more). */+export const AUK_SEQUENCE_MAX = 30;+/** Kept free for AuK's resampling and model-frame rounding. */+export const SEQUENCE_MARGIN = 0.5;+/** Untouched speech kept on each side of a change inside its window. */+export const CONTEXT_MIN = 1;+/** The seam between the original and an edited window (linear: the two sides are the same voice, nearly the same sound). */+export const SPEECH_CROSSFADE = 0.12;+/** A pause at least this long between two words is a silence a window may be cut at. */+export const MIN_SILENCE = 0.12;+/** Speaking rate when the transcript can't tell (seconds per character, spaces included). */+export const DEFAULT_SECONDS_PER_CHAR = 0.065;+/** The longest recording the tool takes (the whole file goes through the graph once). */+export const SPEECH_EDIT_MAX_SECONDS = 20 * 60;+/** Edits per run (each is a window and an AuK call in the one prompt). */+export const MAX_WINDOWS = 24;++const round3 = (n: number) => Math.round(n * 1000) / 1000;++// ---------------------------------------------------------------------------+// Words++export interface Word {+ text: string;+ /** Seconds from the start of the recording. */+ start: number;+ end: number;+}++/** A word as compared: lower case, without the punctuation around it ("Hello," = "hello"). */+export const normalizeWord = (w: string): string =>+ w+ .toLowerCase()+ .normalize("NFKC")+ .replace(/[’‘]/g, "'")+ .replace(/^[^\p{L}\p{N}']+|[^\p{L}\p{N}']+$/gu, "");++export const splitWords = (text: string): string[] => text.split(/\s+/).filter(Boolean);++/**+ * Words with times from transcript lines: each line's words share its time by their length (characters plus one for the+ * space), so a line's first word starts with it and its last ends with it. The pauses between lines are the silences a+ * window is cut at; a transcript with a line per word (a word-timed one) gives exact times.+ */+export function wordsFromCues(cues: Cue[]): Word[] {+ const out: Word[] = [];+ for (const c of [...cues].sort((a, b) => a.start - b.start)) {+ const words = splitWords(c.text);+ if (!words.length || !(c.end > c.start)) continue;+ const weights = words.map((w) => w.length + 1);+ const total = weights.reduce((a, b) => a + b, 0);+ let t = c.start;+ words.forEach((w, i) => {+ const end = i === words.length - 1 ? c.end : t + ((c.end - c.start) * weights[i]) / total;+ out.push({ text: w, start: round3(t), end: round3(end) });+ t = end;+ });+ }+ return out;+}++/** Seconds per character of this speaker (spaces counted), from the transcript; the default when it's too short to say. */+export function speakingRate(words: Word[]): number {+ const chars = words.reduce((a, w) => a + w.text.length + 1, 0);+ const seconds = words.reduce((a, w) => a + Math.max(0, w.end - w.start), 0);+ if (chars < 20 || seconds <= 0) return DEFAULT_SECONDS_PER_CHAR;+ return Math.min(0.2, Math.max(0.03, seconds / chars));+}++/** About how long these words take to say at this rate. */+export const sayLength = (text: string, rate: number): number => (text.trim() ? round3((text.trim().length + 1) * rate) : 0);++// ---------------------------------------------------------------------------+// The diff++/** A changed span: old words [from, to) become `words` (from = to: an insertion before word `from`). */+export interface TextChange {+ from: number;+ to: number;+ words: string[];+}++/**+ * The smallest changed spans between the old words and the new text, compared word by word (case and the punctuation+ * around a word don't count as a change). Common words at both ends are taken off first, then the middle is matched by+ * the longest common subsequence, so two edits far apart stay two changes.+ */+export function diffWords(old: string[], next: string[]): TextChange[] {+ const a = old.map(normalizeWord);+ const b = next.map(normalizeWord);+ let head = 0;+ while (head < a.length && head < b.length && a[head] === b[head]) head++;+ let tail = 0;+ while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail++;+ const A = a.slice(head, a.length - tail);+ const B = b.slice(head, b.length - tail);+ if (!A.length && !B.length) return [];+ // LCS table over the middle (n × m; a transcript edit's middle is short once the ends are off).+ const n = A.length;+ const m = B.length;+ const dp: Uint32Array[] = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));+ for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) dp[i][j] = A[i] === B[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);+ const changes: TextChange[] = [];+ let i = 0;+ let j = 0;+ let open: TextChange | null = null;+ const close = () => {+ if (open) changes.push(open);+ open = null;+ };+ while (i < n || j < m) {+ if (i < n && j < m && A[i] === B[j]) {+ close();+ i++;+ j++;+ } else if (j < m && (i >= n || dp[i][j + 1] >= dp[i + 1][j])) {+ open ??= { from: head + i, to: head + i, words: [] };+ open.words.push(next[head + j]);+ j++;+ } else {+ open ??= { from: head + i, to: head + i, words: [] };+ open.to = head + i + 1;+ i++;+ }+ }+ close();+ return changes;+}++/** Changes from edited transcript lines: the old lines' words against the new lines' words, as one text. */+export function diffLines(cues: Cue[], edited: string[]): TextChange[] {+ const old = [...cues].sort((a, b) => a.start - b.start).flatMap((c) => splitWords(c.text));+ const next = edited.flatMap(splitWords);+ return diffWords(old, next);+}++// ---------------------------------------------------------------------------+// Instructions++/** AuK's text in quotes: single quotes (its Cookbook's), straight apostrophes kept inside words. */+const q = (s: string) => `'${s.replace(/\s+/g, " ").trim()}'`;++/** How many times a run of words occurs among these words (compared as words). */+function occurrences(words: string[], phrase: string[]): number {+ const p = phrase.map(normalizeWord);+ if (!p.length) return 0;+ const w = words.map(normalizeWord);+ let n = 0;+ for (let i = 0; i + p.length <= w.length; i++) if (p.every((x, k) => w[i + k] === x)) n++;+ return n;+}++/**+ * The content-edit instruction for one change (AuK's Cookbook templates, docs/COOKBOOK.md §2.1): Replace 'X' with 'Y'.,+ * Add 'Y' after 'A'. (or before 'B' at the start), Remove 'X'. A phrase that occurs more than once in the window is+ * widened by its neighbouring words on both sides until it occurs once, so AuK edits the right one.+ */+export function editInstruction(words: string[], change: TextChange, windowFrom = 0, windowTo = words.length): string {+ const scope = words.slice(windowFrom, windowTo);+ let { from, to } = change;+ let added = [...change.words];+ if (from === to) {+ // An insertion: anchored on the word before it (or after it, at the start), the anchor widened until it's unique.+ if (from > windowFrom) {+ let a = from - 1;+ while (a > windowFrom && occurrences(scope, words.slice(a, from)) > 1) a--;+ return `Add ${q(added.join(" "))} after ${q(words.slice(a, from).join(" "))}.`;+ }+ let b = from + 1;+ while (b < windowTo && occurrences(scope, words.slice(from, b)) > 1) b++;+ return `Add ${q(added.join(" "))} before ${q(words.slice(from, Math.min(b, windowTo)).join(" "))}.`;+ }+ while (occurrences(scope, words.slice(from, to)) > 1 && (from > windowFrom || to < windowTo)) {+ if (from > windowFrom) {+ from--;+ added = [words[from], ...added];+ }+ if (to < windowTo && occurrences(scope, words.slice(from, to)) > 1) {+ added = [...added, words[to]];+ to++;+ }+ }+ const before = words.slice(from, to).join(" ");+ return added.length ? `Replace ${q(before)} with ${q(added.join(" "))}.` : `Remove ${q(before)}.`;+}++export type EmotionId = "happy" | "angry" | "sad" | "fearful" | "surprised" | "disgusted" | "calm" | "excited";+export const EMOTIONS: EmotionId[] = ["happy", "calm", "excited", "sad", "angry", "surprised", "fearful", "disgusted"];+/** AuK's speed edits (its Cookbook offers these factors). */+export const PACES = [0.5, 0.75, 1.25, 1.5, 2] as const;+export const PITCH_STEPS = [-3, -2, -1, 1, 2, 3] as const;+export const VOLUME_STEPS = [-15, -10, -5, 5, 10, 15] as const;++/** What a picked range can have done to it. */+export type SpeechEffect =+ | { kind: "pitch"; semitones: (typeof PITCH_STEPS)[number] }+ | { kind: "pace"; speed: (typeof PACES)[number] }+ | { kind: "volume"; db: (typeof VOLUME_STEPS)[number] }+ | { kind: "emotion"; emotion: EmotionId }+ | { kind: "whisper" }+ | { kind: "unwhisper" }+ | { kind: "clean" }+ | { kind: "isolate" };++export type EffectKind = SpeechEffect["kind"];++export const EFFECT_LABELS: Record<EffectKind, string> = {+ pitch: "Pitch",+ pace: "Pace",+ volume: "Volume",+ emotion: "Emotion",+ whisper: "Whisper",+ unwhisper: "Normal voice",+ clean: "Clean up",+ isolate: "Keep only this speaker",+};++/** AuK's instruction for an effect on a window (Cookbook §3–§5); `said` is what the window's speaker says (Keep only this speaker). */+export function effectInstruction(e: SpeechEffect, said = ""): string {+ switch (e.kind) {+ case "pitch":+ return `${e.semitones > 0 ? "Raise" : "Lower"} the pitch by ${Math.abs(e.semitones)} semitone${Math.abs(e.semitones) === 1 ? "" : "s"}.`;+ case "pace":+ return `Adjust the speech speed to ${e.speed}x.`;+ case "volume":+ return `${e.db > 0 ? "Increase" : "Decrease"} the volume by ${Math.abs(e.db)} dB.`;+ case "emotion":+ return `Change the emotion to ${e.emotion}.`;+ case "whisper":+ return "Convert this speech into a soft whisper while preserving the speaker and content.";+ case "unwhisper":+ return "Convert this whispered speech into a normal speaking voice while preserving the speaker and content.";+ case "clean":+ return "Preserve all speakers, remove noise and reverberation, and output clean speech of the same length.";+ case "isolate":+ return said.trim() ? `Keep only the speaker who says "${said.replace(/\s+/g, " ").trim()}" and remove all other speakers.` : "Keep only the first speaker to start talking and remove all other speakers.";+ }+}++/** The length an effect makes from `seconds` of speech (only pace changes it). */+export const effectLength = (e: SpeechEffect, seconds: number): number => round3(e.kind === "pace" ? seconds / e.speed : seconds);++export function effectSummary(e: SpeechEffect): string {+ switch (e.kind) {+ case "pitch":+ return `Pitch ${e.semitones > 0 ? "+" : ""}${e.semitones} semitone${Math.abs(e.semitones) === 1 ? "" : "s"}`;+ case "pace":+ return `Pace ${e.speed}×`;+ case "volume":+ return `Volume ${e.db > 0 ? "+" : ""}${e.db} dB`;+ case "emotion":+ return `Sounds ${e.emotion}`;+ default:+ return EFFECT_LABELS[e.kind];+ }+}++// ---------------------------------------------------------------------------+// Windows++/** One AuK call: [start, end] of the original, the instruction, and how long its new audio runs. */+export interface SpeechWindow {+ start: number;+ end: number;+ instruction: string;+ /** Seconds the edited window runs (AuK's generation_seconds). */+ seconds: number;+ /** What changes, in words the page shows. */+ label: string;+}++/** Places a window may start or end, best first: a silence's middle, then any word boundary. */+interface Cuts {+ silences: number[];+ boundaries: number[];+}++function cutsOf(words: Word[], duration: number): Cuts {+ const silences = [0, duration];+ const boundaries = [0, duration];+ for (let i = 1; i < words.length; i++) {+ const gap = words[i].start - words[i - 1].end;+ const mid = round3((words[i - 1].end + words[i].start) / 2);+ boundaries.push(mid);+ if (gap >= MIN_SILENCE) silences.push(mid);+ }+ if (words.length) {+ // The silence before the first word and after the last.+ if (words[0].start >= MIN_SILENCE) silences.push(round3(words[0].start / 2));+ if (duration - words[words.length - 1].end >= MIN_SILENCE) silences.push(round3((words[words.length - 1].end + duration) / 2));+ }+ const tidy = (l: number[]) => [...new Set(l.filter((t) => t >= 0 && t <= duration))].sort((a, b) => a - b);+ return { silences: tidy(silences), boundaries: tidy(boundaries) };+}++/** The latest cut at or before t (0 when there's none). */+const cutBefore = (cuts: number[], t: number) => cuts.filter((c) => c <= t + 1e-6).pop() ?? 0;+/** The earliest cut at or after t (the end when there's none). */+const cutAfter = (cuts: number[], t: number, duration: number) => cuts.find((c) => c >= t - 1e-6) ?? duration;++/** The most seconds of source a window may hold when its new audio runs `ratio` × as long (plus `extra` seconds). */+export const windowBudget = (ratio = 1, extra = 0): number => round3((AUK_SEQUENCE_MAX - SEQUENCE_MARGIN - extra) / (1 + ratio));++export class SpeechEditError extends Error {}++export interface PlanInput {+ /** The words with their times. */+ words: Word[];+ /** Seconds the recording runs. */+ duration: number;+}++/**+ * The window around [s, e] (times of the changed words, or the insertion point twice): at least CONTEXT_MIN seconds of+ * untouched speech on each side (less only where the recording starts or ends), cut at the nearest silence beyond that,+ * else a word boundary, else the exact time; then held to `budget` seconds of source.+ */+function windowAround(s: number, e: number, cuts: Cuts, duration: number, budget: number): { start: number; end: number } | null {+ const wantStart = Math.max(0, s - CONTEXT_MIN);+ const wantEnd = Math.min(duration, e + CONTEXT_MIN);+ const tries: [number, number][] = [+ [cutBefore(cuts.silences, wantStart), cutAfter(cuts.silences, wantEnd, duration)],+ [cutBefore(cuts.silences, wantStart), cutAfter(cuts.boundaries, wantEnd, duration)],+ [cutBefore(cuts.boundaries, wantStart), cutAfter(cuts.silences, wantEnd, duration)],+ [cutBefore(cuts.boundaries, wantStart), cutAfter(cuts.boundaries, wantEnd, duration)],+ [wantStart, wantEnd],+ ];+ for (const [a, b] of tries) if (b - a <= budget + 1e-6) return { start: round3(a), end: round3(b) };+ return null;+}++/** A change's old words' time span (an insertion: the pause it goes into, as one point). */+function spanOf(words: Word[], c: TextChange, duration: number): [number, number] {+ if (c.from < c.to) return [words[c.from].start, words[c.to - 1].end];+ const before = c.from > 0 ? words[c.from - 1].end : 0;+ const after = c.from < words.length ? words[c.from].start : duration;+ const at = round3(c.from === 0 ? Math.min(after, before) : c.from >= words.length ? before : (before + after) / 2);+ return [at, at];+}++/** Merge two changes into one that spans both (the words between them unchanged on both sides). */+function mergeChanges(words: Word[], a: TextChange, b: TextChange): TextChange {+ const [x, y] = a.from <= b.from ? [a, b] : [b, a];+ const between = words.slice(x.to, y.from).map((w) => w.text);+ return { from: x.from, to: Math.max(x.to, y.to), words: [...x.words, ...between, ...y.words] };+}++/**+ * Text edits → AuK windows, one per change (changes whose windows would overlap or nearly touch become one), in time+ * order. Each window's new length is its old length plus the change in the words' time: the difference in characters at the+ * speaker's rate for a replacement, the new words' time for an insertion, the old words' time for a removal. Throws (in words the page shows) when a change is too long for one AuK call or there are too many.+ */+export function planTextWindows(input: PlanInput, changes: TextChange[]): SpeechWindow[] {+ const { words, duration } = input;+ if (!changes.length) return [];+ const rate = speakingRate(words);+ const cuts = cutsOf(words, duration);+ const texts = words.map((w) => w.text);+ const build = (c: TextChange) => {+ const [s, e] = spanOf(words, c, duration);+ // A replacement keeps the old words' real length and adds or takes the difference in characters at the speaker's+ // rate; an insertion adds the new words' time, a removal takes the old words' time away.+ const oldText = texts.slice(c.from, c.to).join(" ");+ const delta = c.from === c.to ? sayLength(c.words.join(" "), rate) : c.words.length ? round3((c.words.join(" ").length - oldText.length) * rate) : -(e - s);+ // The window's old length L and new length L + delta must fit together: 2L + delta ≤ max.+ const budget = windowBudget(1, Math.max(0, delta));+ const w = windowAround(s, e, cuts, duration, budget);+ return { c, s, e, w, delta };+ };+ let list = [...changes].sort((a, b) => a.from - b.from || a.to - b.to).map(build);+ // Merge neighbours whose windows overlap or leave no room for two seams between them.+ for (let k = 0; k < list.length - 1; ) {+ const [p, n] = [list[k], list[k + 1]];+ if (p.w && n.w && n.w.start - p.w.end < 2 * SPEECH_CROSSFADE) {+ list.splice(k, 2, build(mergeChanges(words, p.c, n.c)));+ if (k > 0) k--;+ } else k++;+ }+ const out: SpeechWindow[] = [];+ for (const { c, w, delta } of list) {+ const old = texts.slice(c.from, c.to).join(" ");+ const label = c.from === c.to ? `Add “${c.words.join(" ")}”` : c.words.length ? `“${old}” → “${c.words.join(" ")}”` : `Remove “${old}”`;+ if (!w) throw new SpeechEditError(`${label} is too long for one pass (AuK takes ${AUK_SEQUENCE_MAX} s per call, before and after together): split it into shorter edits`);+ const inWindow = words.map((x, i) => [x, i] as const).filter(([x]) => x.start >= w.start - 1e-6 && x.end <= w.end + 1e-6);+ const from = inWindow.length ? inWindow[0][1] : c.from;+ const to = inWindow.length ? inWindow[inWindow.length - 1][1] + 1 : c.to;+ const seconds = round3(Math.max(2 * SPEECH_CROSSFADE + 0.1, w.end - w.start + delta));+ out.push({ start: w.start, end: w.end, seconds, instruction: editInstruction(texts, c, Math.min(from, c.from), Math.max(to, c.to)), label });+ }+ if (out.length > MAX_WINDOWS) throw new SpeechEditError(`That's ${out.length} edits: up to ${MAX_WINDOWS} run at once. Run some, then the rest on the new version`);+ return out;+}++/**+ * An effect on [start, end] → AuK windows: the range widened to the nearest silence (within half a second, else a word+ * boundary), then split at silences into pieces short enough for one call each (same-length effects up to about 14.7 s,+ * a faster pace a little more). Keep only this speaker names what the speaker says in each piece.+ */+export function planEffectWindows(input: PlanInput, range: { start: number; end: number }, effect: SpeechEffect): SpeechWindow[] {+ const { words, duration } = input;+ const s0 = Math.max(0, Math.min(range.start, range.end));+ const e0 = Math.min(duration, Math.max(range.start, range.end));+ if (!(e0 - s0 >= 0.3)) throw new SpeechEditError("Pick at least a third of a second to change");+ const cuts = cutsOf(words, duration);+ const near = (list: number[], t: number, dir: -1 | 1) => {+ const c = dir < 0 ? cutBefore(list, t) : cutAfter(list, t, duration);+ return Math.abs(c - t) <= 0.5 ? c : null;+ };+ const start = near(cuts.silences, s0, -1) ?? near(cuts.boundaries, s0, -1) ?? s0;+ const end = near(cuts.silences, e0, 1) ?? near(cuts.boundaries, e0, 1) ?? e0;+ const ratio = effect.kind === "pace" ? 1 / effect.speed : 1;+ const budget = windowBudget(ratio);+ const out: SpeechWindow[] = [];+ let a = round3(start);+ while (end - a > 1e-6) {+ let b: number;+ if (end - a <= budget) b = end;+ else {+ // The latest silence inside the budget, else the latest word boundary, else a hard cut at the budget.+ const limit = a + budget;+ const inside = (l: number[]) => l.filter((c) => c > a + 1 && c <= limit).pop();+ b = inside(cuts.silences) ?? inside(cuts.boundaries) ?? limit;+ }+ b = round3(b);+ const said = words.filter((w) => w.start >= a - 1e-6 && w.end <= b + 1e-6).map((w) => w.text).join(" ");+ out.push({ start: a, end: b, seconds: effectLength(effect, b - a), instruction: effectInstruction(effect, said.split(" ").slice(0, 12).join(" ")), label: effectSummary(effect) });+ a = b;+ }+ if (out.length > MAX_WINDOWS) throw new SpeechEditError(`That range needs ${out.length} passes: pick up to ${Math.floor(MAX_WINDOWS * budget)} s at a time`);+ return out;+}++// ---------------------------------------------------------------------------+// Stitching (what the graph does, as times)++/** A piece of the result: the original between `from` and `to`, an edited window's middle, or a seam of the two. */+export type StitchPiece =+ | { kind: "source"; from: number; to: number }+ | { kind: "edit"; window: number; from: number; to: number }+ | { kind: "seam-in"; window: number; at: number; length: number }+ | { kind: "seam-out"; window: number; at: number; length: number };++/**+ * The result as pieces in order, for windows sorted by time and not overlapping: the original up to each window, a seam+ * where the original's first `x` seconds of the window fade out as the edit's fade in, the edit's middle, a seam back, and+ * the original after it. No seam where a window starts the recording or ends it. The result runs the original's length+ * minus each window's old length plus its new one.+ */+export function stitchPlan(windows: SpeechWindow[], duration: number, x = SPEECH_CROSSFADE): StitchPiece[] {+ const pieces: StitchPiece[] = [];+ let at = 0;+ windows.forEach((w, k) => {+ if (w.start < at - 1e-6) throw new SpeechEditError("Edit windows overlap");+ if (w.seconds <= 2 * x) throw new SpeechEditError("An edited window is too short to crossfade");+ const head = w.start > 1e-6;+ const tail = w.end < duration - 1e-6;+ if (w.start - at > 1e-6) pieces.push({ kind: "source", from: round3(at), to: w.start });+ if (head) pieces.push({ kind: "seam-in", window: k, at: w.start, length: x });+ pieces.push({ kind: "edit", window: k, from: head ? x : 0, to: round3(w.seconds - (tail ? x : 0)) });+ if (tail) pieces.push({ kind: "seam-out", window: k, at: round3(w.end - x), length: x });+ at = w.end;+ });+ if (duration - at > 1e-6) pieces.push({ kind: "source", from: round3(at), to: round3(duration) });+ return pieces;+}++export const pieceLength = (p: StitchPiece): number => round3(p.kind === "source" || p.kind === "edit" ? p.to - p.from : p.length);++/** Seconds the edited recording runs. */+export const editedLength = (windows: SpeechWindow[], duration: number): number => round3(windows.reduce((t, w) => t + w.seconds - (w.end - w.start), duration));++/** Where an original time lands in the edited recording (times inside a window scale with it). */+export function mapTime(windows: SpeechWindow[], t: number): number {+ let shift = 0;+ for (const w of windows) {+ if (t <= w.start) break;+ if (t < w.end) return round3(w.start + shift + ((t - w.start) * w.seconds) / (w.end - w.start));+ shift += w.seconds - (w.end - w.start);+ }+ return round3(t + shift);+}++// ---------------------------------------------------------------------------+// Engines, words for the page++/** AuK checkpoints: Flash (distilled, 4 steps, no guidance) by default, the base model for the best take. */+export type AukQuality = "fast" | "best";+export const AUK_SETTINGS: Record<AukQuality, { checkpoint: string; steps: number; cfg: number; label: string }> = {+ fast: { checkpoint: "ckpts/AuK-Flash/auk_flash.safetensors", steps: 4, cfg: 0, label: "Fast (AuK-Flash)" },+ best: { checkpoint: "ckpts/AuK/auk_base.safetensors", steps: 32, cfg: 2, label: "Best (AuK)" },+};++/** Why the cloud engine has no Edit speech (and what Engine mode "Paid APIs only" says). */+export const CLOUD_SPEECH_EDIT_PROBLEM =+ "Edit speech runs on your GPU (open source): AuK isn't hosted on fal or Replicate, so the cloud engine can't change what was said. Switch to the open engine.";+export const CLOUD_ONLY_SPEECH_EDIT_PROBLEM = "Edit speech runs on your GPU (open source), but this install is set to paid cloud APIs only (Settings → Engine mode)";++/** What the page says about AuK's optional prompt helper. */+export const PROMPT_HELPER_NOTE =+ "Fuobe writes AuK's instruction itself and sets the new length from your words, so AuK's optional Prompt Enhancer (a separate language model) stays off and nothing you type leaves your GPU.";++/** AuK's languages, from its technical report (arXiv 2609.08936: a bilingual Chinese and English corpus). */+export const AUK_LANGUAGES = ["English", "Chinese"];++export const engineProblem = (engine: Engine): string | null => (engine === "cloud" ? CLOUD_SPEECH_EDIT_PROBLEM : null);++/** A changed word shown on camera: the result can say so and offer Lipsync, with the times it should cover. */+export function onCameraWarning(kind: "audio" | "video", windows: SpeechWindow[]): string | null {+ if (kind !== "video" || !windows.some((w) => !/^(Pitch|Volume|Clean up|Keep only|Whisper|Normal voice)/.test(w.label))) return null;+ return "If the speaker is on camera when the words change, their lips won't match the new words. Lipsync the changed part to fix it.";+}++// ---------------------------------------------------------------------------+// AuK speech (op tts on oss-auk)++/** The longest line AuK says in one call: its 30 s holds a voice sample and the line together. */+export const AUK_TTS_MAX_SECONDS = 30;++/**+ * AuK's text-to-speech instruction (Cookbook §1): with a voice sample, "Say the following with the same voice"; without+ * one, a voice from its description (a neutral narrator when none is given).+ */+export function ttsInstruction(text: string, o: { hasVoice: boolean; voiceDescription?: string }): string {+ const line = text.replace(/\s+/g, " ").trim().replace(/"/g, "'");+ if (o.hasVoice) return `Say the following with the same voice: "${line}"`;+ const who = (o.voiceDescription?.trim() || "A clear, natural narrator at a moderate pace").replace(/"/g, "'");+ return `Generate speech based on the following description: "${who}". The content to speak is: "${line}".`;+}++/** How long AuK should make a line, and the room its 30 s leaves (a voice sample of `sample` seconds takes the rest). */+export function ttsLength(text: string, sample = 0): number {+ const want = Math.max(1, sayLength(text, DEFAULT_SECONDS_PER_CHAR) + 0.4);+ const room = AUK_SEQUENCE_MAX - SEQUENCE_MARGIN - sample;+ if (room < 1) throw new SpeechEditError("That voice sample is too long for AuK: use one under 20 seconds");+ if (want > room) throw new SpeechEditError(`AuK says up to about ${Math.floor(room)} s per line${sample ? " with this voice sample" : ""}: split the line`);+ return round3(want);+}++// ---------------------------------------------------------------------------+// A run (src/server/audio-tools.ts, tool "speech-edit")++export interface SpeechEditInput {+ engine: Engine;+ /** The recording (/api/files/…): audio, or a video whose soundtrack is edited. */+ media: string;+ kind: "audio" | "video";+ name?: string;+ /** The transcript the edits were made on (Transcribe's lines). */+ cues: Cue[];+ /** Word edits: every line's new text, in the cues' order (unchanged lines as they were). */+ edited?: string[];+ /** Or an effect on a range of the recording. */+ range?: { start: number; end: number };+ effect?: SpeechEffect;+ quality?: AukQuality;+ /** Seconds the recording runs (its header, else the browser's). */+ seconds?: number;+ /** False when the header says the file has no sound. */+ hasAudio?: boolean;+}++export interface SpeechEditPlan extends ToolPlan {+ windows: SpeechWindow[];+ /** Words to show on a video's result: the changed words may be on camera (Lipsync fixes it). */+ warning: string | null;+}++/** The windows a request makes (word edits, else an effect on a range); throws what's in the way, in words the page shows. */+export function speechWindowsFor(i: Pick<SpeechEditInput, "cues" | "edited" | "range" | "effect" | "seconds">): SpeechWindow[] {+ const duration = i.seconds ?? Math.max(0, ...i.cues.map((c) => c.end));+ if (!(duration > 0)) throw new SpeechEditError("Couldn't tell how long the recording runs: add it again");+ const words = wordsFromCues(i.cues);+ if (i.effect) {+ if (!i.range) throw new SpeechEditError("Pick the part to change");+ return planEffectWindows({ words, duration }, i.range, i.effect);+ }+ if (!i.edited) throw new SpeechEditError("Edit the words, or pick a range and an effect");+ const changes = diffLines(i.cues, i.edited);+ if (!changes.length) throw new SpeechEditError("Nothing changed yet: edit a line's words first");+ return planTextWindows({ words, duration }, changes);+}++/** One AuK job for every window (and, on a video, the stream-copy mux that puts the new sound on the picture). */+export function planSpeechEdit(i: SpeechEditInput): SpeechEditPlan {+ const problem = engineProblem(i.engine);+ if (problem) throw new SpeechEditError(problem);+ if (i.hasAudio === false) throw new SpeechEditError("This file has no sound to edit");+ if (i.seconds && i.seconds > SPEECH_EDIT_MAX_SECONDS) throw new SpeechEditError(`Recordings run up to ${SPEECH_EDIT_MAX_SECONDS / 60} minutes here: trim it first`);+ const windows = speechWindowsFor(i);+ const duration = i.seconds ?? Math.max(0, ...i.cues.map((c) => c.end));+ const name = i.name?.trim() || (i.kind === "video" ? "video" : "recording");+ const what = i.effect ? effectSummary(i.effect) : windows.length === 1 ? windows[0].label : `${windows.length} edits`;+ const title = `${what} · ${name}`.slice(0, 200);+ const video = i.kind === "video";+ const base = { feature: SPEECH_EDIT_FEATURE, batchTitle: title } satisfies Partial<GenerationRequest>;+ const steps: ToolStep[] = [+ {+ key: "edit",+ request: {+ ...base,+ modelId: SPEECH_EDIT_MODEL,+ engine: "open",+ op: "speech-edit",+ title: video ? `Edited sound · ${name}` : title,+ inputs: video ? { video: i.media } : { audio: i.media },+ params: { sourceDuration: round3(duration), extra: { speechWindows: windows, ...(i.quality === "best" && { quality: "best" }) } },+ step: { label: what, index: 0, of: video ? 2 : 1 },+ },+ },+ ];+ if (video) {+ steps.push({+ key: "video",+ after: ["edit"],+ chain: [{ slot: "audio" }],+ request: {+ ...base,+ modelId: SPEECH_EDIT_MUX_MODEL,+ engine: "open",+ op: "mux",+ title,+ inputs: { video: i.media },+ step: { label: "New sound on the video · picture copied", index: 1, of: 2 },+ },+ });+ }+ const warning = onCameraWarning(i.kind, windows);+ return {+ steps,+ windows,+ warning,+ length: editedLength(windows, duration),+ summary: `${windows.length === 1 ? "One part" : `${windows.length} parts`} of the ${video ? "video's sound" : "recording"} ${i.effect ? "changed" : "re-spoken"} by AuK in the same voice and crossfaded back${video ? ", then put back on the picture (copied as it is)" : ""}.`,+ notes: [+ "Each part keeps at least a second of the untouched recording around it, so the new words match the voice and the room.",+ ...(i.quality === "best" ? [] : ["Fast uses AuK-Flash (4 steps). Best uses the full AuK model: slower, a little closer to the voice."]),+ ...(warning ? [warning] : []),+ ],+ };+}diff --git a/src/server/audio-tools.ts b/src/server/audio-tools.tsindex 31a0a055..0f09fe35 100644--- a/src/server/audio-tools.ts+++ b/src/server/audio-tools.ts@@ -6,6 +6,7 @@ import { CLOUD_ONLY_REMOVE_PROBLEM, LOWER_MAX_DB, LOWER_MIN_DB, NO_SOUND_PROBLEMimport { planCleanDialogue } from "@/lib/av/clean-dialogue";import { CLOUD_ONLY_CLEAN_PROBLEM, missingReuse, NO_REUSE_PACK, planClean, planTime, tooLongProblem } from "@/lib/av/clean-voice";import type { Engine, Generation } from "@/lib/catalog/types";+import { CLOUD_ONLY_SPEECH_EDIT_PROBLEM, EMOTIONS, PACES, PITCH_STEPS, planSpeechEdit, SPEECH_EDIT_MAX_SECONDS, VOLUME_STEPS } from "@/lib/speech-edit";import { lastGpuDevice } from "./account-gpu";import { createPipeline } from "./chains";import { ConnectComfyError, previewChained } from "./generations";@@ -109,6 +110,31 @@ export const AudioToolBody = z.discriminatedUnion("tool", [channels: z.number().int().positive().max(64).optional(),sourceDuration: z.number().positive().max(36_000).optional(),}),+ z.object({+ // Edit speech (nm10-speech-edit): a recording's words changed (its transcript's lines, edited), or an effect on a range.+ tool: z.literal("speech-edit"),+ engine: Engine,+ media: FileUrl,+ kind: z.enum(["audio", "video"]),+ name: z.string().max(200).optional(),+ cues: z.array(z.object({ start: z.number().min(0).max(SPEECH_EDIT_MAX_SECONDS), end: z.number().min(0).max(SPEECH_EDIT_MAX_SECONDS), text: z.string().max(2000) })).min(1).max(2000),+ edited: z.array(z.string().max(2000)).max(2000).optional(),+ range: z.object({ start: z.number().min(0), end: z.number().min(0) }).optional(),+ effect: z+ .discriminatedUnion("kind", [+ z.object({ kind: z.literal("pitch"), semitones: z.number().refine((n) => (PITCH_STEPS as readonly number[]).includes(n)) }),+ z.object({ kind: z.literal("pace"), speed: z.number().refine((n) => (PACES as readonly number[]).includes(n)) }),+ z.object({ kind: z.literal("volume"), db: z.number().refine((n) => (VOLUME_STEPS as readonly number[]).includes(n)) }),+ z.object({ kind: z.literal("emotion"), emotion: z.enum(EMOTIONS as [string, ...string[]]) }),+ z.object({ kind: z.literal("whisper") }),+ z.object({ kind: z.literal("unwhisper") }),+ z.object({ kind: z.literal("clean") }),+ z.object({ kind: z.literal("isolate") }),+ ])+ .optional(),+ quality: z.enum(["fast", "best"]).optional(),+ sourceDuration: z.number().positive().max(36_000).optional(),+ }),z.object({tool: z.literal("remux"),engine: Engine,@@ -167,6 +193,7 @@ async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engineif (body.tool === "split" && mode === "cloud") throw new AudioToolError(CLOUD_ONLY_PROBLEM);if (body.tool === "remove-dialogue" && mode === "cloud") throw new AudioToolError(CLOUD_ONLY_REMOVE_PROBLEM);if (body.tool === "clean" && mode === "cloud") throw new AudioToolError(CLOUD_ONLY_CLEAN_PROBLEM);+ if (body.tool === "speech-edit" && mode === "cloud") throw new AudioToolError(CLOUD_ONLY_SPEECH_EDIT_PROBLEM);if (mode !== "both" && body.engine !== mode) throw new AudioToolError(mode === "open" ? "This install is set to open source only (Settings → Engine mode)" : "This install is set to paid cloud APIs only (Settings → Engine mode)");try {if (body.tool === "split") {@@ -197,6 +224,11 @@ async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engineconst channels = facts?.channels ?? body.channels;return { engine: body.engine, ...planCleanDialogue({ ...body, seconds, channels, silent: facts?.hasAudio === false }), split: { duration: seconds, channels }, headerChannels: facts?.channels };}+ if (body.tool === "speech-edit") {+ const facts = factsOf(body.media, body.kind === "video" ? "That video is gone — add it again" : "That recording is gone — add it again");+ const seconds = facts?.duration ?? body.sourceDuration;+ return { engine: body.engine, ...planSpeechEdit({ ...body, effect: body.effect as Parameters<typeof planSpeechEdit>[0]["effect"], seconds, hasAudio: facts?.hasAudio }) };+ }if (body.tool === "remux") {present(body.audio, "That mix is gone — export it again");present(body.video, "That video is gone — add it again");diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 70a0fb2c..444b60d7 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -52,6 +52,8 @@ import { crossfadeProblem, fadeCurveWav } from "@/lib/av/crossfade";import { dbsChannelsFor, dbsModelFor, dbsSurroundBed, installedDbs, surroundSource, type DbsModel } from "@/lib/av/split";import { installedReuse, NO_REUSE_PACK, rateFor, reuseFileFor, STRENGTH_DB, type ReuseModel } from "@/lib/av/clean-voice";import { expandAudioJoinWorkflow, expandVideoJoinWorkflow } from "@/lib/av/joins";+import { aukTtsWorkflow, expandSpeechEditWorkflow, readSpeechWindows, setAukDevice, speechFadeWav } from "@/lib/av/speech-edit-graph";+import { SpeechEditError, ttsInstruction, ttsLength, type SpeechWindow } from "@/lib/speech-edit";import { expandTimelineWorkflow, readTimeline } from "@/lib/av/timeline";import { exportValues, framesPerPass, hdrColorSpace, upscaleShortSide, wholeClipProblem, wholeClipTool } from "@/lib/av/video-finish";import { guessKind } from "@/lib/catalog/payload";@@ -1259,7 +1261,7 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,// A voice track on the video's timeline: the clips are the spoken lines (the template binds the first).if (ctx.op === "timeline") values.audio = input.audios?.[0] ?? input.audio;// Speech workflows read the soundtrack with LoadAudio, which also takes a video upload.- if ((ctx.op === "transcribe" || ctx.op === "separate-audio" || ctx.op === "enhance-voice" || ctx.op === "translate") && b.audio && !b.video) values.audio = input.audio ?? input.video ?? clips[0];+ if ((ctx.op === "transcribe" || ctx.op === "separate-audio" || ctx.op === "enhance-voice" || ctx.op === "translate" || ctx.op === "speech-edit") && b.audio && !b.video) values.audio = input.audio ?? input.video ?? clips[0];if (b.language && input.targetLanguage) values.language = input.targetLanguage;if (b.sourceLanguage && input.sourceLanguage) {const whisper = b.sourceLanguage.some((t) => workflow[t.node]?.class_type === "Apply Whisper");@@ -1403,6 +1405,19 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,if (maxSeconds && b.duration && Number(values.duration ?? d.duration ?? 0) > maxSeconds + 0.001) {throw new ProviderError(OVER_LIMIT[manifest.capability]?.(maxSeconds) ?? `This workflow makes up to ${maxSeconds} s per job`);}+ // Edit speech (speech-edit-auk): the edit windows the planner made, crossfaded back on a linear fade-in with a flat tail+ // (src/lib/av/speech-edit-graph.ts says why; both sides of a seam are the same voice, so equal power would bump the level).+ let speechWindows: SpeechWindow[] | null = null;+ const aukQuality = extra.quality === "best" ? "best" : "fast";+ if (manifest.expand === "speech") {+ speechWindows = readSpeechWindows(extra.speechWindows);+ if (!speechWindows) throw new ProviderError("Nothing to change: edit the words, or pick a range and an effect", 400);+ if (b.fadeCurve && extra.fadeCurve === undefined) extra.fadeCurve = await ctx.upload(Buffer.from(speechFadeWav(Math.max(0.02, Number(input.crossfade ?? d.crossfade ?? 0.12)))), "audio/wav", "speech_fade.wav");+ }+ if (Object.values(workflow).some((n) => n.class_type === "AuKModelLoader")) {+ delete extra.speechWindows;+ delete extra.quality;+ }// Loops and joins with a crossfade: core ComfyUI has no gain ramp, so the curve is a tiny WAV written here// (left = fade-in, right = fade-out, exactly the crossfade long). Clips too short for it are refused up front.if (b.fadeCurve) {@@ -1493,6 +1508,20 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,// place of SAM's, the anchor after the boundary, masked generation off. Branches it doesn't use go after binding.// Media inputs a studio job leaves out on purpose (their branches go after binding).const studioLeft: string[] = [];+ // AuK's text to speech (speech-tts-auk, nm10-speech-edit): its instruction and length, written here since AuK's Prompt+ // Enhancer is off. Without a voice sample the loader goes (a voice from its description).+ let aukTts: { seconds: number; hasVoice: boolean } | null = null;+ if (manifest.id === "speech-tts-auk") {+ const hasVoice = !!values.audio;+ if (!hasVoice) studioLeft.push("audio");+ const sample = hasVoice ? (ctx.media?.(String(values.audio))?.duration ?? 0) : 0;+ try {+ aukTts = { seconds: ttsLength(String(input.prompt ?? ""), sample), hasVoice };+ } catch (e) {+ throw new ProviderError((e as Error).message, 400);+ }+ values.prompt = ttsInstruction(String(input.prompt ?? ""), { hasVoice, voiceDescription: input.voiceDescription });+ }let studioSegment: Omit<SegmentGraphOptions, "outputs"> | null = null;if (manifest.id === STUDIO_WORKFLOWS.segment) {const history = typeof extra.historyVideo === "string" && !!extra.historyVideo;@@ -1811,6 +1840,23 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,throw new ProviderError((e as Error).message);}}+ if (speechWindows) {+ const duration = ctx.media?.(String(values.audio ?? ""))?.duration ?? input.sourceDuration;+ if (!duration) throw new ProviderError("Couldn't read how long the recording runs: add it again as WAV, MP3, M4A or MP4", 400);+ try {+ wf = expandSpeechEditWorkflow(wf, speechWindows, { duration, quality: aukQuality, seed: Number(values.seed) || 0, crossfade: Math.max(0.02, Number(input.crossfade ?? d.crossfade ?? 0.12)) });+ } catch (e) {+ throw new ProviderError((e as Error).message, e instanceof SpeechEditError ? 400 : 500);+ }+ }+ if (aukTts) wf = aukTtsWorkflow(wf, aukTts);+ if (Object.values(wf).some((n) => n.class_type === "AuKModelLoader")) {+ try {+ wf = setAukDevice(wf, typeof values.device === "string" ? values.device : undefined);+ } catch (e) {+ throw new ProviderError((e as Error).message, 400);+ }+ }// Joins of more clips than the template binds: one loader per clip, in one prompt.try {if (manifest.expand === "videos" && clips.length > 2) wf = expandVideoJoinWorkflow(wf, clips);diff --git a/tests/speech-edit-comfy.test.ts b/tests/speech-edit-comfy.test.tsnew file mode 100644index 00000000..871a0f79--- /dev/null+++ b/tests/speech-edit-comfy.test.ts@@ -0,0 +1,153 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { expandSpeechEditWorkflow, FADE_TAIL, speechFadeWav } from "@/lib/av/speech-edit-graph";+import type { ComfyWorkflow } from "@/lib/comfy";+import { editedLength, type SpeechWindow } from "@/lib/speech-edit";++/**+ * Edit speech on your GPU (nm10-speech-edit): the AuK graphs, their pack pinned for the GPU pre-flight, the node list+ * they are checked against (ComfyUI-AuK is not on the validation server), the windows' rebuild, and what the ComfyUI+ * provider binds.+ */++process.env.FUOBE_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-speech-edit-comfy-"));+process.env.COMFYUI_URL = "http://127.0.0.1:9";++const root = path.resolve(__dirname, "..");+const read = (p: string) => JSON.parse(fs.readFileSync(path.join(root, p), "utf8"));+type Entry = { id: string; capability: string; customNodes?: { name: string; repo: string }[]; validated: boolean; license?: string; expand?: string; bindings: Record<string, { node: string; input: string }[]> };+const manifest = read("workflows/comfyui/manifest.json") as { workflows: Entry[] };+const packs = read("workflows/comfyui/packs.json") as Record<string, { repo: string; commit: string; subdir: string | null }>;+const requirements = read("workflows/comfyui/requirements.json") as { workflows: Record<string, { packs: Record<string, string[]>; firstRun: string[]; vramGb: number }> };+const subset = read("workflows/comfyui/object_info.subset.json") as Record<string, { python_module: string; input: { required: Record<string, unknown>; optional?: Record<string, unknown> } } | null>;+const graph = (id: string) => read(`workflows/comfyui/${id}.json`) as ComfyWorkflow;++/** The inputs of ComfyUI-AuK's two nodes at the pinned commit (comfyui/ComfyUI-AuK/nodes.py, define_schema). */+const AUK_NODES: Record<string, string[]> = {+ AuKModelLoader: ["checkpoint_path", "config_path", "qwen_path", "device", "dtype", "cpu_offload"],+ AuKGenerateEdit: ["engine", "instruction", "generation_seconds", "use_prompt_enhancer", "seed", "input_audio", "nfe_steps", "cfg_strength", "sway_sampling_coef"],+};++describe("the AuK graphs in the library", () => {+ it.each([+ ["speech-edit-auk", "speech-edit", ["audio", "fadeCurve", "seed", "device", "filenamePrefix"]],+ ["speech-tts-auk", "tts", ["audio", "prompt", "seed", "device", "filenamePrefix"]],+ ])("%s: its pack pinned, checked against AuK's node list, MIT and its downloads stated", (id, capability, bindings) => {+ const w = manifest.workflows.find((x) => x.id === id)!;+ expect(w.capability).toBe(capability);+ expect(Object.keys(w.bindings).sort()).toEqual([...bindings].sort());+ expect(w.customNodes?.map((c) => c.name)).toEqual(["ComfyUI-AuK"]);+ expect(w.validated).toBe(false);+ expect(w.license).toMatch(/MIT/);+ expect(w.license).toMatch(/Qwen Research License/);+ expect(packs["ComfyUI-AuK"]).toMatchObject({ repo: "https://github.com/Tencent-Hunyuan/AuK", subdir: "comfyui/ComfyUI-AuK" });+ expect(packs["ComfyUI-AuK"].commit).toMatch(/^[0-9a-f]{40}$/);+ expect(requirements.workflows[id].packs["ComfyUI-AuK"]).toEqual(["AuKGenerateEdit", "AuKModelLoader"]);+ expect(requirements.workflows[id].firstRun.join(" ")).toMatch(/tencent\/AuK-Flash at 575b92f0.*Qwen\/Qwen2\.5-Omni-3B/);+ expect(requirements.workflows[id].vramGb).toBe(24);+ for (const n of Object.values(graph(id))) {+ const info = subset[n.class_type];+ expect(info, n.class_type).toBeTruthy();+ const allowed = AUK_NODES[n.class_type];+ if (!allowed) continue;+ expect(info!.python_module).toBe("custom_nodes.ComfyUI-AuK");+ for (const input of Object.keys(n.inputs)) expect(allowed, `${n.class_type}.${input}`).toContain(input);+ expect(Object.keys({ ...info!.input.required, ...info!.input.optional }).sort()).toEqual([...allowed].sort());+ }+ // Prompt Enhancer off, AuK-Flash's settings.+ const gen = Object.values(graph(id)).find((n) => n.class_type === "AuKGenerateEdit")!;+ expect(gen.inputs).toMatchObject({ use_prompt_enhancer: false, nfe_steps: 4, cfg_strength: 0, sway_sampling_coef: -1 });+ expect(w.expand).toBe(id === "speech-edit-auk" ? "speech" : undefined);+ });++ it("is pinned the same in the install script", () => {+ const sh = fs.readFileSync(path.join(root, "scripts/comfy/install-comfyui.sh"), "utf8");+ expect(sh).toContain(`AUK_REF="\${AUK_REF:-${packs["ComfyUI-AuK"].commit}}"`);+ expect(sh).toMatch(/AUK:-0/);+ });+});++describe("the windows' rebuild", () => {+ const windows: SpeechWindow[] = [+ { start: 0, end: 3, seconds: 3.4, instruction: "Replace 'a' with 'b'.", label: "a → b" },+ { start: 5, end: 9, seconds: 4, instruction: "Raise the pitch by 2 semitones.", label: "Pitch +2" },+ ];++ it("gives every window its own AuK call on one engine, and stitches the rest of the recording around them", () => {+ const wf = expandSpeechEditWorkflow(graph("speech-edit-auk"), windows, { duration: 12, seed: 7, quality: "best" });+ const auk = Object.values(wf).filter((n) => n.class_type === "AuKGenerateEdit");+ expect(auk.map((n) => [n.inputs.instruction, n.inputs.generation_seconds, n.inputs.seed])).toEqual([+ ["Replace 'a' with 'b'.", 3.4, 7],+ ["Raise the pitch by 2 semitones.", 4, 8],+ ]);+ expect(auk.every((n) => n.inputs.nfe_steps === 32 && n.inputs.cfg_strength === 2 && n.inputs.use_prompt_enhancer === false)).toBe(true);+ expect(Object.values(wf).filter((n) => n.class_type === "AuKModelLoader")).toHaveLength(1);+ expect(Object.values(wf).find((n) => n.class_type === "AuKModelLoader")!.inputs.checkpoint_path).toBe("ckpts/AuK/auk_base.safetensors");+ // Each window's cut is from the recording at one rate, at the window's times.+ const cuts = Object.entries(wf).filter(([id]) => /^w\d_cut$/.test(id)).map(([, n]) => [n.inputs.start_index, n.inputs.duration]);+ expect(cuts).toEqual([+ [0, 3],+ [5, 4],+ ]);+ // Every link points at a node that exists, and the save gets the whole chain.+ for (const n of Object.values(wf)) for (const v of Object.values(n.inputs)) if (Array.isArray(v) && typeof v[0] === "string") expect(wf[v[0]], `${v[0]}`).toBeTruthy();+ const save = Object.values(wf).find((n) => n.class_type === "SaveAudio")!;+ expect(wf[(save.inputs.audio as [string, number])[0]].class_type).toBe("AudioConcat");+ // The pieces' lengths add up to the edited recording's length: the original's untouched parts plus each new window.+ const trims = Object.entries(wf).filter(([id, n]) => n.class_type === "TrimAudioDuration" && /^p\d+_(orig|edit)$/.test(id));+ const seams = Object.keys(wf).filter((id) => /_seam$/.test(id)).length;+ const len = trims.reduce((t, [, n]) => t + Math.min(Number(n.inputs.duration), 12 - Number(n.inputs.start_index)), 0) + seams * 0.12;+ expect(len).toBeCloseTo(editedLength(windows, 12), 6);+ // The first window starts the recording: no seam before it.+ expect(seams).toBe(3);+ });++ it("writes a fade-in that ramps to 1 and stays there for the tail AudioMerge trims off", () => {+ const wav = speechFadeWav(0.12);+ const v = new DataView(wav.buffer);+ const n = (wav.length - 44) / 4;+ expect(n).toBe(Math.round(0.12 * 8000) + Math.round(FADE_TAIL * 8000));+ expect(v.getInt16(44, true)).toBe(0);+ expect(v.getInt16(44 + (Math.round(0.12 * 8000) - 1) * 4, true)).toBe(32767);+ expect(v.getInt16(44 + (n - 1) * 4, true)).toBe(32767);+ });+});++describe("what the ComfyUI provider binds", () => {+ const WAV = "data:audio/wav;base64,UklGRg==";+ const ctx = (op: "speech-edit" | "tts", device?: string, duration = 12) => ({+ generationId: "g",+ op,+ upload: async (_b: Buffer, _t: string, name: string) => name,+ device: async () => device,+ media: () => ({ duration }),+ });++ it("rebuilds the windows from params.extra, on the GPU's device, with the fade-in it writes", async () => {+ const { prepareWorkflow } = await import("@/server/providers/comfyui");+ const windows: SpeechWindow[] = [{ start: 2, end: 6, seconds: 4.3, instruction: "Replace 'Tuesday' with 'Thursday'.", label: "x" }];+ const p = await prepareWorkflow("speech-edit-auk", { audio: WAV, extra: { speechWindows: windows } }, ctx("speech-edit", "cpu"));+ const nodes = Object.values(p.workflow);+ expect(nodes.find((n) => n.class_type === "AuKModelLoader")!.inputs).toMatchObject({ device: "cpu", dtype: "fp32", checkpoint_path: "ckpts/AuK-Flash/auk_flash.safetensors" });+ expect(nodes.find((n) => n.class_type === "AuKGenerateEdit")!.inputs).toMatchObject({ instruction: "Replace 'Tuesday' with 'Thursday'.", generation_seconds: 4.3 });+ expect(nodes.filter((n) => n.class_type === "LoadAudio").map((n) => n.inputs.audio)).toContain("speech_fade.wav");+ // An NVIDIA GPU: cuda:0 in bf16. Apple's GPU isn't one AuK's nodes take.+ const gpu = await prepareWorkflow("speech-edit-auk", { audio: WAV, extra: { speechWindows: windows } }, ctx("speech-edit", "cuda"));+ expect(Object.values(gpu.workflow).find((n) => n.class_type === "AuKModelLoader")!.inputs).toMatchObject({ device: "cuda:0", dtype: "bf16" });+ await expect(prepareWorkflow("speech-edit-auk", { audio: WAV, extra: { speechWindows: windows } }, ctx("speech-edit", "mps"))).rejects.toThrow(/Apple/);+ await expect(prepareWorkflow("speech-edit-auk", { audio: WAV, extra: {} }, ctx("speech-edit"))).rejects.toThrow(/Nothing to change/);+ });++ it("speaks a line in a sample's voice, or from a description with the loader gone", async () => {+ const { prepareWorkflow } = await import("@/server/providers/comfyui");+ const clone = await prepareWorkflow("speech-tts-auk", { prompt: "Welcome back.", voiceAudio: WAV }, ctx("tts", undefined, 5));+ expect(clone.workflow["3"].inputs).toMatchObject({ instruction: 'Say the following with the same voice: "Welcome back."', input_audio: ["1", 0] });+ expect(Number(clone.workflow["3"].inputs.generation_seconds)).toBeGreaterThan(1);+ const design = await prepareWorkflow("speech-tts-auk", { prompt: "Welcome back.", voiceDescription: "A bright young host" }, ctx("tts"));+ expect(design.workflow["1"]).toBeUndefined();+ expect(design.workflow["3"].inputs.input_audio).toBeUndefined();+ expect(design.workflow["3"].inputs.instruction).toBe('Generate speech based on the following description: "A bright young host". The content to speak is: "Welcome back.".');+ });+});diff --git a/tests/speech-edit.test.ts b/tests/speech-edit.test.tsnew file mode 100644index 00000000..34c760e3--- /dev/null+++ b/tests/speech-edit.test.ts@@ -0,0 +1,256 @@+import { describe, expect, it } from "vitest";+import {+ AUK_SEQUENCE_MAX,+ CONTEXT_MIN,+ diffLines,+ diffWords,+ editedLength,+ editInstruction,+ effectInstruction,+ mapTime,+ onCameraWarning,+ pieceLength,+ planEffectWindows,+ planSpeechEdit,+ planTextWindows,+ SEQUENCE_MARGIN,+ SPEECH_CROSSFADE,+ SpeechEditError,+ splitWords,+ stitchPlan,+ ttsInstruction,+ ttsLength,+ wordsFromCues,+ type SpeechWindow,+ type Word,+} from "@/lib/speech-edit";++/** Words at 0.4 s each with a 0.05 s gap, and a 0.5 s pause after every `phrase` words. */+function timed(text: string, phrase = 6, start = 0): Word[] {+ let t = start;+ return splitWords(text).map((w, i) => {+ if (i > 0) t += i % phrase === 0 ? 0.5 : 0.05;+ const word = { text: w, start: Math.round(t * 1000) / 1000, end: Math.round((t + 0.4) * 1000) / 1000 };+ t += 0.4;+ return word;+ });+}++const TEXT =+ "We open the new studio on Tuesday morning. Everyone is welcome to come along and see the space. " ++ "There will be coffee and cake for the first fifty guests. Bring a friend if you like and say hello to the team.";++const fits = (w: SpeechWindow) => w.end - w.start + w.seconds <= AUK_SEQUENCE_MAX - SEQUENCE_MARGIN + 1e-6;++describe("Edit speech: the diff", () => {+ it("finds the smallest changed span, ignoring case and punctuation around words", () => {+ const old = splitWords("We open the new studio on Tuesday morning.");+ expect(diffWords(old, splitWords("we open the new studio, on Thursday morning"))).toEqual([{ from: 6, to: 7, words: ["Thursday"] }]);+ expect(diffWords(old, old)).toEqual([]);+ });++ it("tells insertions, removals and replacements apart, and keeps far-apart edits separate", () => {+ const old = splitWords("one two three four five six seven eight");+ expect(diffWords(old, splitWords("one two really three four five six seven eight"))).toEqual([{ from: 2, to: 2, words: ["really"] }]);+ expect(diffWords(old, splitWords("one two four five six seven eight"))).toEqual([{ from: 2, to: 3, words: [] }]);+ expect(diffWords(old, splitWords("uno two three four five six seven ocho"))).toEqual([+ { from: 0, to: 1, words: ["uno"] },+ { from: 7, to: 8, words: ["ocho"] },+ ]);+ });++ it("diffs edited transcript lines as one text", () => {+ const cues = [+ { start: 0, end: 2, text: "Hello there" },+ { start: 2.5, end: 4, text: "how are you" },+ ];+ expect(diffLines(cues, ["Hello there", "how were you"])).toEqual([{ from: 3, to: 4, words: ["were"] }]);+ });+});++describe("Edit speech: AuK's instructions", () => {+ const words = splitWords("the cat sat on the mat and the cat ran");+ it("uses the Cookbook templates", () => {+ expect(editInstruction(words, { from: 2, to: 3, words: ["stood"] })).toBe("Replace 'sat' with 'stood'.");+ expect(editInstruction(words, { from: 3, to: 3, words: ["quietly"] })).toBe("Add 'quietly' after 'sat'.");+ expect(editInstruction(words, { from: 0, to: 0, words: ["Then"] })).toBe("Add 'Then' before 'the cat sat'.");+ expect(editInstruction(words, { from: 9, to: 10, words: [] })).toBe("Remove 'ran'.");+ });++ it("widens a phrase that occurs twice until it is unique", () => {+ // "cat" occurs twice: the change is widened to "the cat sat" → "the dog sat".+ const i = editInstruction(words, { from: 1, to: 2, words: ["dog"] });+ expect(i).toBe("Replace 'the cat sat' with 'the dog sat'.");+ });++ it("writes the effects in AuK's words", () => {+ expect(effectInstruction({ kind: "pitch", semitones: 2 })).toBe("Raise the pitch by 2 semitones.");+ expect(effectInstruction({ kind: "pitch", semitones: -1 })).toBe("Lower the pitch by 1 semitone.");+ expect(effectInstruction({ kind: "pace", speed: 1.5 })).toBe("Adjust the speech speed to 1.5x.");+ expect(effectInstruction({ kind: "volume", db: -10 })).toBe("Decrease the volume by 10 dB.");+ expect(effectInstruction({ kind: "emotion", emotion: "happy" })).toBe("Change the emotion to happy.");+ expect(effectInstruction({ kind: "clean" })).toMatch(/remove noise and reverberation/);+ expect(effectInstruction({ kind: "isolate" }, "hello there")).toBe('Keep only the speaker who says "hello there" and remove all other speakers.');+ });++ it("speaks a line with or without a voice sample", () => {+ expect(ttsInstruction('Say "hi"', { hasVoice: true })).toBe("Say the following with the same voice: \"Say 'hi'\"");+ expect(ttsInstruction("Hi", { hasVoice: false, voiceDescription: "A calm voice" })).toBe('Generate speech based on the following description: "A calm voice". The content to speak is: "Hi".');+ expect(ttsLength("Hello there")).toBeGreaterThan(1);+ expect(() => ttsLength("x".repeat(600))).toThrow(SpeechEditError);+ expect(() => ttsLength("Hello", 29.5)).toThrow(/voice sample is too long/);+ });+});++describe("Edit speech: windows", () => {+ const words = timed(TEXT);+ const duration = words[words.length - 1].end + 0.6;+ const at = (w: string) => words.findIndex((x) => x.text.replace(/\W/g, "") === w);++ it("cuts a window at silences, with at least a second of untouched speech each side", () => {+ const i = at("Tuesday");+ const [w] = planTextWindows({ words, duration }, [{ from: i, to: i + 1, words: ["Thursday"] }]);+ expect(w.instruction).toBe("Replace 'Tuesday' with 'Thursday'.");+ expect(words[i].start - w.start).toBeGreaterThanOrEqual(CONTEXT_MIN);+ expect(w.end - words[i].end).toBeGreaterThanOrEqual(CONTEXT_MIN);+ // Both cuts are the middle of a pause, not inside a word.+ for (const t of [w.start, w.end]) expect(words.some((x) => t > x.start && t < x.end)).toBe(false);+ expect(fits(w)).toBe(true);+ // "Thursday" is about as long as "Tuesday": the new window runs about as long as the old one.+ expect(Math.abs(w.seconds - (w.end - w.start))).toBeLessThan(0.2);+ });++ it("starts at 0 for an edit at the very start and ends at the end for one at the end", () => {+ const first = planTextWindows({ words, duration }, [{ from: 0, to: 1, words: ["They"] }])[0];+ expect(first.start).toBe(0);+ const last = planTextWindows({ words, duration }, [{ from: words.length - 1, to: words.length, words: ["crew."] }])[0];+ expect(last.end).toBeCloseTo(duration, 6);+ });++ it("runs several far-apart edits as several windows, and merges close ones", () => {+ const far = planTextWindows({ words, duration }, [+ { from: at("Tuesday"), to: at("Tuesday") + 1, words: ["Friday"] },+ { from: at("friend"), to: at("friend") + 1, words: ["partner"] },+ ]);+ expect(far).toHaveLength(2);+ expect(far[1].start - far[0].end).toBeGreaterThanOrEqual(2 * SPEECH_CROSSFADE);+ const close = planTextWindows({ words, duration }, [+ { from: at("coffee"), to: at("coffee") + 1, words: ["tea"] },+ { from: at("cake"), to: at("cake") + 1, words: ["biscuits"] },+ ]);+ expect(close).toHaveLength(1);+ expect(close[0].instruction).toBe("Replace 'coffee and cake' with 'tea and biscuits'.");+ });++ it("lengthens or shortens the window by the new words' time", () => {+ const i = at("Tuesday");+ const [longer] = planTextWindows({ words, duration }, [{ from: i, to: i + 1, words: ["Tuesday,", "the", "fifth", "of", "November,"] }]);+ expect(longer.seconds - (longer.end - longer.start)).toBeGreaterThan(1);+ const [gone] = planTextWindows({ words, duration }, [{ from: i, to: i + 1, words: [] }]);+ expect(gone.instruction).toBe("Remove 'Tuesday'.");+ expect(gone.end - gone.start - gone.seconds).toBeCloseTo(0.4, 1);+ });++ it("holds every window to AuK's 30 s with its new audio, and refuses a change too long for one call", () => {+ const long = timed(Array.from({ length: 80 }, (_, k) => `w${k}`).join(" "), 1000);+ const end = long[long.length - 1].end;+ const [w] = planTextWindows({ words: long, duration: end }, [{ from: 30, to: 31, words: ["x"] }]);+ // No silences at all: cut at word boundaries, still in budget.+ expect(fits(w)).toBe(true);+ expect(() => planTextWindows({ words: long, duration: end }, [{ from: 5, to: 40, words: ["short"] }])).toThrow(/too long for one pass/);+ });++ it("splits an effect's range at silences into windows AuK can take", () => {+ const ws = planEffectWindows({ words, duration }, { start: 0, end: duration }, { kind: "pitch", semitones: 2 });+ expect(ws.length).toBeGreaterThan(1);+ for (const w of ws) {+ expect(fits(w)).toBe(true);+ expect(w.seconds).toBeCloseTo(w.end - w.start, 3);+ expect(w.instruction).toBe("Raise the pitch by 2 semitones.");+ }+ // Back to back, covering the whole range.+ expect(ws[0].start).toBe(0);+ expect(ws[ws.length - 1].end).toBeCloseTo(duration, 3);+ for (let k = 1; k < ws.length; k++) expect(ws[k].start).toBe(ws[k - 1].end);+ const pace = planEffectWindows({ words, duration }, { start: 2, end: 6 }, { kind: "pace", speed: 2 });+ expect(pace[0].seconds).toBeCloseTo((pace[0].end - pace[0].start) / 2, 3);+ expect(() => planEffectWindows({ words, duration }, { start: 1, end: 1.1 }, { kind: "clean" })).toThrow(SpeechEditError);+ });++ it("times words inside transcript lines by their length", () => {+ const w = wordsFromCues([{ start: 1, end: 3, text: "a bbb" }]);+ expect(w).toEqual([+ { text: "a", start: 1, end: 1.667 },+ { text: "bbb", start: 1.667, end: 3 },+ ]);+ });+});++describe("Edit speech: the crossfade stitch", () => {+ const w = (start: number, end: number, seconds: number): SpeechWindow => ({ start, end, seconds, instruction: "x", label: "x" });++ it("puts a seam at each side of a window, none at the recording's start or end", () => {+ const x = SPEECH_CROSSFADE;+ const p = stitchPlan([w(2, 6, 5)], 10, x);+ expect(p).toEqual([+ { kind: "source", from: 0, to: 2 },+ { kind: "seam-in", window: 0, at: 2, length: x },+ { kind: "edit", window: 0, from: x, to: 5 - x },+ { kind: "seam-out", window: 0, at: 6 - x, length: x },+ { kind: "source", from: 6, to: 10 },+ ]);+ const total = p.reduce((t, q) => t + pieceLength(q), 0);+ expect(total).toBeCloseTo(editedLength([w(2, 6, 5)], 10), 6);+ expect(editedLength([w(2, 6, 5)], 10)).toBe(11);+ const edge = stitchPlan([w(0, 3, 3), w(7, 10, 2)], 10, x);+ expect(edge.map((q) => q.kind)).toEqual(["edit", "seam-out", "source", "seam-in", "edit"]);+ expect(edge.reduce((t, q) => t + pieceLength(q), 0)).toBeCloseTo(9, 6);+ });++ it("joins back-to-back windows without an empty piece of the original", () => {+ const p = stitchPlan([w(1, 4, 3), w(4, 8, 4)], 10);+ expect(p.filter((q) => q.kind === "source")).toEqual([+ { kind: "source", from: 0, to: 1 },+ { kind: "source", from: 8, to: 10 },+ ]);+ expect(() => stitchPlan([w(1, 4, 3), w(3, 8, 4)], 10)).toThrow(/overlap/);+ });++ it("maps original times to the edited recording", () => {+ const ws = [w(2, 6, 5)];+ expect(mapTime(ws, 1)).toBe(1);+ expect(mapTime(ws, 4)).toBe(4.5);+ expect(mapTime(ws, 8)).toBe(9);+ });+});++describe("Edit speech: a run", () => {+ const cues = [+ { start: 0, end: 2.2, text: "We open the new studio" },+ { start: 2.8, end: 4.6, text: "on Tuesday morning." },+ { start: 5.3, end: 8, text: "Everyone is welcome to come along." },+ ];++ it("is one AuK job on audio, and AuK then the stream-copy mux on a video, with the lipsync warning", () => {+ const audio = planSpeechEdit({ engine: "open", media: "/api/files/a.wav", kind: "audio", cues, edited: [cues[0].text, "on Thursday morning.", cues[2].text], seconds: 8.5 });+ expect(audio.steps).toHaveLength(1);+ expect(audio.steps[0].request).toMatchObject({ modelId: "oss-auk", op: "speech-edit", inputs: { audio: "/api/files/a.wav" }, feature: "speech-edit" });+ expect((audio.steps[0].request.params?.extra?.speechWindows as SpeechWindow[])[0].instruction).toBe("Replace 'Tuesday' with 'Thursday'.");+ expect(audio.warning).toBeNull();+ const video = planSpeechEdit({ engine: "open", media: "/api/files/v.mp4", kind: "video", cues, edited: [cues[0].text, "on Thursday morning.", cues[2].text], seconds: 8.5 });+ expect(video.steps.map((s) => [s.request.modelId, s.request.op])).toEqual([+ ["oss-auk", "speech-edit"],+ ["oss-mux", "mux"],+ ]);+ expect(video.steps[1]).toMatchObject({ after: ["edit"], chain: [{ slot: "audio" }] });+ expect(video.warning).toMatch(/Lipsync/);+ // A pitch change keeps the lips in time: no warning.+ expect(onCameraWarning("video", planSpeechEdit({ engine: "open", media: "/api/files/v.mp4", kind: "video", cues, range: { start: 0, end: 4 }, effect: { kind: "pitch", semitones: 1 }, seconds: 8.5 }).windows)).toBeNull();+ });++ it("runs on your GPU only, and says what's missing", () => {+ expect(() => planSpeechEdit({ engine: "cloud", media: "/api/files/a.wav", kind: "audio", cues, edited: ["x"], seconds: 8 })).toThrow(/Runs on your GPU|runs on your GPU/);+ expect(() => planSpeechEdit({ engine: "open", media: "/api/files/a.wav", kind: "audio", cues, edited: cues.map((c) => c.text), seconds: 8 })).toThrow(/Nothing changed/);+ expect(() => planSpeechEdit({ engine: "open", media: "/api/files/a.wav", kind: "audio", cues, edited: ["x"], seconds: 8, hasAudio: false })).toThrow(/no sound/);+ });+});