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
Translate & dub: sessions, step pipelines for both engines, one-shot cloud dubs
Claude49b9c84ae408
diff --git a/scripts/gen-cloud-models.py b/scripts/gen-cloud-models.pyindex d8f81a87..623f8fa9 100644--- a/scripts/gen-cloud-models.py+++ b/scripts/gen-cloud-models.py@@ -522,6 +522,9 @@ model("whisper", "Whisper large-v3", "OpenAI", "whisper", "text", "Whisper large[("transcribe", "fal-ai/whisper")], fixed={"chunk_level": "word"})model("demucs", "Demucs stem split", "Meta", "demucs", "audio", "Split a track into vocals, drums, bass and the rest",[("separate-audio", "fal-ai/demucs")], fixed={"model": "htdemucs"})+# Translate & dub (cloud, step by step): the clean voice straight from the video, to clone in the new language.+model("elevenlabs-voice-isolation", "ElevenLabs Voice Isolation", "ElevenLabs", "elevenlabs", "audio", "Clean speech from a video or recording — music and noise removed",+ [("separate-audio", "fal-ai/elevenlabs/audio-isolation")], pricing=("minute", 0.1))# ----- Image to 3D (research part 3; product spins, 3D blocking)model("hunyuan-3d-3-1-pro", "Hunyuan3D 3.1 Pro", "Tencent Hunyuan", "hunyuan-3d", "model3d", "Textured, game-ready 3D models from a product photo",diff --git a/src/app/api/dub/[id]/route.ts b/src/app/api/dub/[id]/route.tsnew file mode 100644index 00000000..448a9df5--- /dev/null+++ b/src/app/api/dub/[id]/route.ts@@ -0,0 +1,30 @@+import { connection } from "next/server";+import { z } from "zod";+import { CueSchema, deleteDubSession, dubView, getDubSession, saveDubDraft } from "@/server/dub";++const Patch = z.object({ lang: z.string().min(2).max(12), cues: z.array(CueSchema).max(3000) });++export async function GET(_req: Request, ctx: RouteContext<"/api/dub/[id]">) {+ await connection();+ const { id } = await ctx.params;+ const s = getDubSession(id);+ return s ? Response.json(dubView(s)) : Response.json({ error: "Not found" }, { status: 404 });+}++/** Save the reviewed lines of one language. */+export async function PATCH(request: Request, ctx: RouteContext<"/api/dub/[id]">) {+ const { id } = await ctx.params;+ const parsed = Patch.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Those lines can't be saved" }, { status: 400 });+ try {+ return Response.json(saveDubDraft(id, parsed.data.lang, parsed.data.cues));+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: getDubSession(id) ? 422 : 404 });+ }+}++/** Forget the dub (its results stay in the Library). */+export async function DELETE(_req: Request, ctx: RouteContext<"/api/dub/[id]">) {+ const { id } = await ctx.params;+ return deleteDubSession(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });+}diff --git a/src/app/api/dub/[id]/voice/route.ts b/src/app/api/dub/[id]/voice/route.tsnew file mode 100644index 00000000..771da13a--- /dev/null+++ b/src/app/api/dub/[id]/voice/route.ts@@ -0,0 +1,22 @@+import { z } from "zod";+import { CueSchema, getDubSession, voiceDub } from "@/server/dub";++const Body = z.object({+ lang: z.string().min(2).max(12),+ /** The reviewed lines (saved with the run); omitted = the saved draft or the translation. */+ cues: z.array(CueSchema).max(3000).optional(),+ lipsync: z.boolean().optional(),+});++/** Speak one language's reviewed lines in the cloned voice: the voice pipeline. */+export async function POST(request: Request, ctx: RouteContext<"/api/dub/[id]/voice">) {+ const { id } = await ctx.params;+ const parsed = Body.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Pick the language to voice" }, { status: 400 });+ if (!getDubSession(id)) return Response.json({ error: "Not found" }, { status: 404 });+ try {+ return Response.json(voiceDub(id, parsed.data.lang, { cues: parsed.data.cues, lipsync: parsed.data.lipsync }), { status: 201 });+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: 422 });+ }+}diff --git a/src/app/api/dub/route.ts b/src/app/api/dub/route.tsnew file mode 100644index 00000000..74b3f554--- /dev/null+++ b/src/app/api/dub/route.ts@@ -0,0 +1,36 @@+import { connection } from "next/server";+import { z } from "zod";+import { ONE_SHOT_MODELS } from "@/lib/av/dub";+import { createDubSession, listDubSessions } from "@/server/dub";++const Body = z.object({+ engine: z.enum(["cloud", "open"]),+ mode: z.enum(["oneshot", "steps"]),+ video: z.string().startsWith("/api/files/"),+ title: z.string().max(200).optional(),+ source: z.string().max(12).optional(),+ targets: z.array(z.string().min(2).max(12)).min(1).max(8),+ model: z.enum(ONE_SHOT_MODELS).optional(),+});++/** Recent dubs with the state of every step. */+export async function GET(request: Request) {+ await connection();+ const limit = Number(new URL(request.url).searchParams.get("limit") ?? 30);+ return Response.json({ items: listDubSessions(Number.isFinite(limit) ? limit : 30) });+}++/** Start a dub: one-shot jobs (cloud) or the prepare pipeline (both engines). */+export async function POST(request: Request) {+ const parsed = Body.safeParse(await request.json().catch(() => null));+ if (!parsed.success) {+ const first = parsed.error.issues[0];+ const msg = first?.path[0] === "video" ? "Add the video to translate" : first?.path[0] === "targets" ? "Pick up to 8 languages to dub into" : "Check the dub settings";+ return Response.json({ error: msg }, { status: 400 });+ }+ try {+ return Response.json(createDubSession(parsed.data), { status: 201 });+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: 422 });+ }+}diff --git a/src/lib/av/cue-edit.ts b/src/lib/av/cue-edit.tsnew file mode 100644index 00000000..89fca3ce--- /dev/null+++ b/src/lib/av/cue-edit.ts@@ -0,0 +1,131 @@+import type { Cue } from "@/lib/cues";++/**+ * Editing a cue list (Captions studio, Translate & dub review): pure reducer, so the editor, undo and+ * the tests share one set of rules. Cues stay in time order, never overlap and last at least MIN_CUE.+ */+export const MIN_CUE = 0.2;++export type CueAction =+ | { type: "text"; index: number; text: string }+ /** New start and/or end (seconds), clamped between the neighbours. */+ | { type: "time"; index: number; start?: number; end?: number }+ /** Split at a character offset of the text (at the nearest space); time is shared by the length of each half. */+ | { type: "split"; index: number; caret?: number }+ /** Merge with the next cue. */+ | { type: "merge"; index: number }+ | { type: "remove"; index: number }+ /** A new empty cue after `index` (-1 = at the start), in the gap if there's room. */+ | { type: "insert"; index: number }+ /** Move every cue by `seconds` (an audio offset), never before 0. */+ | { type: "shift"; seconds: number }+ | { type: "reset"; cues: Cue[] };++const round = (t: number) => Math.round(t * 1000) / 1000;++/** Sorted, overlap-free copy with rounded times: what the editor starts from. */+export function normalizeCues(cues: Cue[]): Cue[] {+ const sorted = cues+ .filter((c) => Number.isFinite(c.start) && Number.isFinite(c.end))+ .map((c) => ({ start: Math.max(0, round(c.start)), end: round(c.end), text: c.text ?? "" }))+ .sort((a, b) => a.start - b.start);+ for (let i = 0; i < sorted.length; i++) {+ const c = sorted[i];+ const next = sorted[i + 1];+ if (next && c.end > next.start) c.end = next.start;+ if (c.end - c.start < MIN_CUE) c.end = round(c.start + MIN_CUE);+ if (next && next.start < c.end) next.start = c.end;+ }+ return sorted;+}++/** Where to split text near `caret`: the closest space, else the middle word boundary. */+function splitText(text: string, caret?: number): [string, string] | null {+ const t = text.trim();+ if (!t.includes(" ")) return null;+ const at = caret === undefined ? t.length / 2 : Math.max(0, Math.min(t.length, caret));+ let best = -1;+ for (let i = 0; i < t.length; i++) if (t[i] === " " && (best < 0 || Math.abs(i - at) < Math.abs(best - at))) best = i;+ const a = t.slice(0, best).trim();+ const b = t.slice(best + 1).trim();+ return a && b ? [a, b] : null;+}++export function cueReducer(cues: Cue[], a: CueAction): Cue[] {+ if (a.type === "reset") return normalizeCues(a.cues);+ if (a.type === "shift") {+ const first = cues[0]?.start ?? 0;+ const by = Math.max(-first, a.seconds);+ return cues.map((c) => ({ ...c, start: round(c.start + by), end: round(c.end + by) }));+ }+ if (a.type === "insert") {+ const prevEnd = a.index >= 0 ? (cues[a.index]?.end ?? 0) : 0;+ const nextStart = cues[a.index + 1]?.start ?? prevEnd + 2;+ if (nextStart - prevEnd < MIN_CUE) return cues;+ const cue = { start: round(prevEnd), end: round(Math.min(nextStart, prevEnd + 2)), text: "" };+ return [...cues.slice(0, a.index + 1), cue, ...cues.slice(a.index + 1)];+ }+ const c = cues[a.index];+ if (!c) return cues;+ const out = cues.slice();+ switch (a.type) {+ case "text":+ out[a.index] = { ...c, text: a.text };+ return out;+ case "time": {+ const lo = a.index > 0 ? out[a.index - 1].end : 0;+ const hi = out[a.index + 1]?.start ?? Infinity;+ let start = a.start ?? c.start;+ let end = a.end ?? c.end;+ start = Math.max(lo, Math.min(start, hi - MIN_CUE));+ end = Math.min(hi, Math.max(end, start + MIN_CUE));+ if (a.start !== undefined && a.end === undefined && end - start < MIN_CUE) start = end - MIN_CUE;+ out[a.index] = { ...c, start: round(start), end: round(end) };+ return out;+ }+ case "split": {+ const parts = splitText(c.text, a.caret);+ const span = c.end - c.start;+ if (!parts || span < MIN_CUE * 2) return cues;+ const share = parts[0].length / (parts[0].length + parts[1].length);+ const mid = round(Math.min(c.end - MIN_CUE, Math.max(c.start + MIN_CUE, c.start + span * share)));+ out.splice(a.index, 1, { start: c.start, end: mid, text: parts[0] }, { start: mid, end: c.end, text: parts[1] });+ return out;+ }+ case "merge": {+ const next = out[a.index + 1];+ if (!next) return cues;+ out.splice(a.index, 2, { start: c.start, end: next.end, text: [c.text.trim(), next.text.trim()].filter(Boolean).join(" ") });+ return out;+ }+ case "remove":+ out.splice(a.index, 1);+ return out;+ }+ return cues;+}++/** What's wrong with a cue list before it's burned or voiced (empty lines, times past the clip). */+export function cueProblems(cues: Cue[], duration?: number): string[] {+ const problems: string[] = [];+ if (!cues.length) problems.push("There are no lines yet");+ const empty = cues.filter((c) => !c.text.trim()).length;+ if (empty) problems.push(`${empty} empty line${empty === 1 ? "" : "s"}`);+ if (duration && cues.some((c) => c.start >= duration)) problems.push("A line starts after the end of the video");+ return problems;+}++/** "1:02.5" for a time in seconds. */+export function formatCueTime(t: number): string {+ const s = Math.max(0, t);+ const m = Math.floor(s / 60);+ const rest = s - m * 60;+ return `${m}:${rest < 10 ? "0" : ""}${rest.toFixed(1)}`;+}++/** Parse "1:02.5", "62.5" or "1:02" back into seconds; null when it isn't a time. */+export function parseCueTime(text: string): number | null {+ const parts = text.trim().split(":");+ if (!parts.length || parts.length > 3 || parts.some((p) => !/^\d+(\.\d+)?$/.test(p))) return null;+ return round(parts.reduce((acc, p) => acc * 60 + Number(p), 0));+}diff --git a/src/lib/av/dub.ts b/src/lib/av/dub.tsnew file mode 100644index 00000000..09aeadb8--- /dev/null+++ b/src/lib/av/dub.ts@@ -0,0 +1,288 @@+import type { Cue } from "@/lib/cues";+import type { ChainSlot, Engine, Generation, GenerationRequest } from "@/lib/catalog/types";+import { languageByCode, supportsTarget, type DubLanguage, type DubRoute } from "./languages";++/**+ * Translate & dub, planned as plain data (client and server). Two ways to dub:+ *+ * - One shot (cloud): HeyGen Translate or ElevenLabs Dubbing take the video and return it dubbed.+ * - Step by step (both engines), as two pipelines with a review in between:+ * prepare: voice stem (+ background on the open engine) → timed transcript → translation per language+ * review: the person edits the translated lines (nothing is spoken yet)+ * voice: speech in the cloned voice → lips re-synced → the new voice over the background+ *+ * Open engine: MelBand RoFormer splits voice and background (oss-voice-separate), Qwen3-ASR times the+ * voice stem, the local LLM translates the cues (oss-text-llm), Chatterbox Multilingual speaks in the+ * cloned voice, InfiniteTalk re-syncs the lips and the mux mixes the voice over the background stem.+ * Cloud: ElevenLabs Voice Isolation (the clean voice to clone), Scribe v2 on it (transcript), Claude or Ollama+ * (translation), ElevenLabs v4 speaks it and Chatterbox voice conversion turns it into the speaker's voice,+ * Sync Lipsync 3 re-syncs the lips. No cloud model in the catalog mixes two audio tracks (fal's+ * merge-audio-video takes one), so the cloud result carries the dubbed voice only — the background+ * music and effects are kept by the open route and by the one-shot models.+ */++export const DUB_FEATURE = "dub";++export const ONE_SHOT_MODELS = ["heygen-translate", "heygen-translate-fast", "elevenlabs-dubbing"] as const;+export type OneShotModel = (typeof ONE_SHOT_MODELS)[number];++export const DUB_STEP_MODELS = {+ cloud: { voice: "elevenlabs-voice-isolation", words: "scribe-v2", translate: "text-llm", speech: "elevenlabs-v4", clone: "chatterbox-vc-cloud", lips: "sync-lipsync-3", mux: "merge-audio-video" },+ open: { stems: "oss-voice-separate", words: "oss-qwen3-asr", translate: "oss-text-llm", speech: "oss-chatterbox", lips: "oss-infinitetalk-v2v", mux: "oss-mux" },+} as const;++/** The ElevenLabs voice the cloud route speaks with before it's converted into the speaker's own voice. */+export const CLOUD_BASE_VOICE = "JBFqnCBsd6RMkjVDRZzb"; // George++export interface DubStep {+ key: string;+ request: GenerationRequest;+ after?: string | string[];+ chain?: ChainSlot[];+}++export const translateKey = (code: string) => `translate:${code}`;++const step = (label: string, index: number, of: number) => ({ label, index, of });++function targetsFor(route: DubRoute, codes: string[]): DubLanguage[] {+ const out: DubLanguage[] = [];+ for (const code of codes) {+ const lang = languageByCode(code);+ if (!lang) throw new Error(`Unknown language “${code}”`);+ if (!supportsTarget(route, lang)) throw new Error(`${lang.name} isn't available ${route === "open" ? "on the open engine (Chatterbox speaks 23 languages)" : "on this model"}`);+ if (!out.includes(lang)) out.push(lang);+ }+ if (!out.length) throw new Error("Pick at least one language to dub into");+ return out;+}++export interface PrepareInput {+ engine: Engine;+ video: string;+ /** ISO code of the spoken language, or "auto". */+ source?: string;+ targets: string[];+ title?: string;+}++/** Step 1 (both engines): the voice to clone, the timed transcript and one translation per target language. */+export function prepareSteps(o: PrepareInput): DubStep[] {+ const targets = targetsFor(o.engine === "open" ? "open" : "cloud-steps", o.targets);+ const source = o.source && o.source !== "auto" ? o.source : undefined;+ const from = languageByCode(source)?.name;+ const n = targets.length + 2;+ const base = { feature: DUB_FEATURE, ...(o.title && { batchTitle: o.title }) };+ const translate = (lang: DubLanguage, i: number, after: string): DubStep => ({+ key: translateKey(lang.code),+ after,+ chain: [{ slot: "prompt" }],+ request: {+ ...base,+ modelId: o.engine === "open" ? DUB_STEP_MODELS.open.translate : DUB_STEP_MODELS.cloud.translate,+ op: "translate",+ params: { targetLanguage: lang.name, ...(from && { sourceLanguage: from }) },+ step: step(`Translate · ${lang.name}`, i, n),+ },+ });+ const lang = source ? { params: { sourceLanguage: source } } : {};+ // The transcript is made from the clean voice stem (music and effects removed), so the timings follow the speech.+ if (o.engine === "open") {+ return [+ { key: "stems", request: { ...base, modelId: DUB_STEP_MODELS.open.stems, op: "separate-audio", inputs: { video: o.video }, step: step("Voice and background", 0, n) } },+ { key: "words", after: "stems", chain: [{ slot: "audio", stem: "voice" }], request: { ...base, modelId: DUB_STEP_MODELS.open.words, op: "transcribe", ...lang, step: step("Transcript", 1, n) } },+ ...targets.map((l, i) => translate(l, i + 2, "words")),+ ];+ }+ return [+ { key: "voice", request: { ...base, modelId: DUB_STEP_MODELS.cloud.voice, op: "separate-audio", inputs: { video: o.video }, step: step("Clean voice", 0, n) } },+ { key: "words", after: "voice", chain: [{ slot: "audio" }], request: { ...base, modelId: DUB_STEP_MODELS.cloud.words, op: "transcribe", ...lang, step: step("Transcript", 1, n) } },+ ...targets.map((l, i) => translate(l, i + 2, "words")),+ ];+}++export interface VoiceInput {+ engine: Engine;+ video: string;+ lang: string;+ /** The reviewed lines, in order. */+ cues: Cue[];+ /** The clean voice to clone (the voice stem / isolated voice). */+ voiceRef: string;+ /** Open engine: the background stem mixed back under the new voice. */+ background?: string;+ /** Re-sync the lips (default on). Off: the new voice is laid over the original picture. */+ lipsync?: boolean;+ title?: string;+}++/** The words the voice speaks: the reviewed lines, one per line. */+export function spokenText(cues: Cue[]): string {+ return cues+ .map((c) => c.text.replace(/\s+/g, " ").trim())+ .filter(Boolean)+ .join("\n");+}++/** Step 2: speak the reviewed translation in the cloned voice, re-sync the lips and put the new voice on the video. */+export function voiceSteps(o: VoiceInput): DubStep[] {+ const lang = languageByCode(o.lang);+ if (!lang) throw new Error(`Unknown language “${o.lang}”`);+ const text = spokenText(o.cues);+ if (!text) throw new Error("There are no lines to speak — write at least one");+ const lips = o.lipsync !== false;+ const base = { feature: DUB_FEATURE, ...(o.title && { batchTitle: o.title }) };+ const tag = (label: string) => `${label} · ${lang.name}`;+ if (o.engine === "open") {+ if (!supportsTarget("open", lang)) throw new Error(`${lang.name} isn't available on the open engine`);+ const m = DUB_STEP_MODELS.open;+ const n = lips ? 3 : 2;+ const steps: DubStep[] = [+ {+ key: "speech",+ request: { ...base, modelId: m.speech, op: "tts", prompt: text, inputs: { voiceAudio: o.voiceRef }, params: { targetLanguage: lang.chatterbox }, step: step(tag("Voice"), 0, n) },+ },+ ];+ if (lips) {+ steps.push({ key: "lips", after: "speech", chain: [{ slot: "audio" }], request: { ...base, modelId: m.lips, op: "lipsync", inputs: { video: o.video }, step: step(tag("Lips"), 1, n) } });+ }+ steps.push({+ key: "film",+ after: lips ? ["lips", "speech"] : "speech",+ chain: lips ? [{ slot: "video" }, { slot: "audio" }] : [{ slot: "audio" }],+ request: {+ ...base,+ modelId: m.mux,+ op: "mux",+ inputs: { ...(lips ? {} : { video: o.video }), ...(o.background && { audio2: o.background }) },+ // The background stem sits a little under the new voice.+ ...(o.background && { params: { extra: { backgroundVolumeDb: -3 } } }),+ step: step(tag("Dubbed video"), n - 1, n),+ },+ });+ return steps;+ }+ const m = DUB_STEP_MODELS.cloud;+ const n = 3;+ const steps: DubStep[] = [+ { key: "speech", request: { ...base, modelId: m.speech, op: "tts", prompt: text, params: { voice: CLOUD_BASE_VOICE }, step: step(tag("Speech"), 0, n) } },+ { key: "clone", after: "speech", chain: [{ slot: "audio" }], request: { ...base, modelId: m.clone, op: "voice-change", inputs: { voiceAudio: o.voiceRef }, step: step(tag("Their voice"), 1, n) } },+ ];+ steps.push(+ lips+ ? { key: "film", after: "clone", chain: [{ slot: "audio" }], request: { ...base, modelId: m.lips, op: "lipsync", inputs: { video: o.video }, step: step(tag("Dubbed video"), 2, n) } }+ : { key: "film", after: "clone", chain: [{ slot: "audio" }], request: { ...base, modelId: m.mux, op: "mux", inputs: { video: o.video }, step: step(tag("Dubbed video"), 2, n) } },+ );+ return steps;+}++/** One-shot cloud dubs: one job per language. */+export function oneShotRequests(o: { model: OneShotModel; video: string; source?: string; targets: string[]; title?: string }): { lang: DubLanguage; request: GenerationRequest }[] {+ const targets = targetsFor(o.model, o.targets);+ const source = o.source && o.source !== "auto" ? o.source : undefined;+ return targets.map((lang, i) => ({+ lang,+ request: {+ feature: DUB_FEATURE,+ ...(o.title && { batchTitle: o.title }),+ modelId: o.model,+ op: "dub",+ inputs: { video: o.video },+ params: {+ targetLanguage: o.model === "elevenlabs-dubbing" ? lang.eleven : lang.heygen,+ ...(o.model === "elevenlabs-dubbing" && source && { sourceLanguage: source }),+ },+ step: { label: `Dub · ${lang.name}`, index: i, of: targets.length },+ },+ }));+}++// ---------------------------------------------------------------------------+// Sessions (stored by the server, shown by the studio)++export interface DubVoiceRun {+ /** Generation id per step key ("speech", "clone", "lips", "film"). */+ ids: Record<string, string>;+ at: number;+ lipsync: boolean;+}++export interface DubSession {+ id: string;+ title: string;+ engine: Engine;+ mode: "oneshot" | "steps";+ video: string;+ source: string;+ targets: string[];+ model?: OneShotModel;+ batchId: string;+ /** Step mode: the prepare pipeline's generation ids by step key. */+ prepare?: Record<string, string>;+ /** Reviewed lines per language (saved as the person edits). */+ drafts?: Record<string, Cue[]>;+ /** Voice runs per language, newest last. */+ voices?: Record<string, DubVoiceRun[]>;+ /** One-shot jobs per language. */+ oneshot?: Record<string, string>;+ createdAt: number;+ updatedAt: number;+}++export type DubStage = "preparing" | "review" | "voicing" | "done" | "failed";++/** A session with its generations, as the studio shows it. */+export interface DubSessionView extends DubSession {+ generations: Record<string, Generation>;+}++const done = (g?: Generation) => g?.status === "succeeded";+const broken = (g?: Generation) => g?.status === "failed" || g?.status === "canceled";++/** The translated lines of a language: the saved draft, else the translation step's cues. */+export function reviewCues(s: DubSessionView, code: string): Cue[] | null {+ if (s.drafts?.[code]) return s.drafts[code];+ const g = s.generations[s.prepare?.[translateKey(code)] ?? ""];+ const out = g?.outputs.find((o) => o.kind === "text");+ const cues = out?.meta?.cues;+ if (Array.isArray(cues) && cues.length) return (cues as Cue[]).map((c) => ({ start: c.start, end: c.end, text: c.text }));+ if (typeof out?.text === "string" && out.text.trim()) {+ // A translation without timings (plain text): one line per cue, spread evenly is the best we can do.+ const lines = out.text.split("\n").filter((l) => l.trim());+ return lines.map((text, i) => ({ start: i * 3, end: i * 3 + 2.8, text }));+ }+ return null;+}++/** The stage of one language: still preparing, ready for review, being voiced, done or failed. */+export function languageStage(s: DubSessionView, code: string): DubStage {+ if (s.mode === "oneshot") {+ const g = s.generations[s.oneshot?.[code] ?? ""];+ return done(g) ? "done" : broken(g) ? "failed" : "voicing";+ }+ const prepIds = Object.entries(s.prepare ?? {}).filter(([k]) => !k.startsWith("translate:") || k === translateKey(code)).map(([, id]) => s.generations[id]);+ if (prepIds.some(broken)) return "failed";+ if (!prepIds.every(done)) return "preparing";+ const run = s.voices?.[code]?.at(-1);+ if (!run) return "review";+ const film = s.generations[run.ids.film];+ const all = Object.values(run.ids).map((id) => s.generations[id]);+ if (all.some(broken)) return "failed";+ return done(film) ? "done" : "voicing";+}++/** The clean voice to clone and (open engine) the background, from the finished prepare step. */+export function prepareMedia(s: DubSessionView): { voice?: string; background?: string } {+ const g = s.generations[s.prepare?.[s.engine === "open" ? "stems" : "voice"] ?? ""];+ const audio = (g?.outputs ?? []).filter((o) => o.kind === "audio");+ const stem = (names: string[]) => audio.find((o) => typeof o.meta?.stem === "string" && names.includes(String(o.meta.stem).toLowerCase()))?.url;+ if (s.engine === "open") return { voice: stem(["voice", "vocals", "speech", "target"]) ?? audio[0]?.url, background: stem(["background", "accompaniment", "instrumental", "residual", "no_vocals"]) };+ return { voice: audio[0]?.url };+}++/** The finished dub of a language, if any. */+export function dubResult(s: DubSessionView, code: string): Generation | undefined {+ const id = s.mode === "oneshot" ? s.oneshot?.[code] : s.voices?.[code]?.at(-1)?.ids.film;+ const g = id ? s.generations[id] : undefined;+ return done(g) ? g : undefined;+}diff --git a/src/lib/av/languages.ts b/src/lib/av/languages.tsnew file mode 100644index 00000000..3c6c18d7--- /dev/null+++ b/src/lib/av/languages.ts@@ -0,0 +1,78 @@+/**+ * Languages for Translate & dub and Captions, with the name each model wants: the LLM translates into the+ * English name, Chatterbox Multilingual (open TTS) takes "Spanish (es)", HeyGen takes its display names and+ * ElevenLabs Dubbing ISO codes. A language without a value for an engine can't be a target there.+ */+export interface DubLanguage {+ /** ISO 639-1 (or -2) code, also what transcribers take as the spoken language. */+ code: string;+ name: string;+ /** Chatterbox Multilingual's combo value (open engine voice). */+ chatterbox?: string;+ /** HeyGen Translate's output_language. */+ heygen?: string;+ /** ElevenLabs Dubbing's target_lang. */+ eleven?: string;+}++/** cb: Chatterbox speaks it; heygen: HeyGen's name when it isn't the plain name; eleven: ElevenLabs Dubbing has it. */+const L = (code: string, name: string, o: { cb?: boolean; heygen?: string; eleven?: boolean } = {}): DubLanguage => ({+ code,+ name,+ ...(o.cb && { chatterbox: `${name} (${code})` }),+ heygen: o.heygen ?? name,+ ...(o.eleven && { eleven: code }),+});++export const DUB_LANGUAGES: DubLanguage[] = [+ L("en", "English", { cb: true, eleven: true }),+ L("es", "Spanish", { cb: true, eleven: true }),+ L("fr", "French", { cb: true, eleven: true }),+ L("de", "German", { cb: true, eleven: true }),+ L("it", "Italian", { cb: true, eleven: true }),+ L("pt", "Portuguese", { cb: true, eleven: true }),+ L("nl", "Dutch", { cb: true, eleven: true }),+ L("pl", "Polish", { cb: true, eleven: true }),+ L("ru", "Russian", { cb: true, eleven: true }),+ L("tr", "Turkish", { cb: true, eleven: true }),+ L("ar", "Arabic", { cb: true, eleven: true }),+ L("he", "Hebrew", { cb: true, heygen: "Hebrew (Israel)" }),+ L("hi", "Hindi", { cb: true, eleven: true }),+ L("ja", "Japanese", { cb: true, eleven: true }),+ L("ko", "Korean", { cb: true, eleven: true }),+ L("zh", "Chinese", { cb: true, eleven: true }),+ L("ms", "Malay", { cb: true, eleven: true }),+ L("sv", "Swedish", { cb: true, eleven: true }),+ L("da", "Danish", { cb: true, eleven: true }),+ L("no", "Norwegian", { cb: true, heygen: "Norwegian Bokmål (Norway)", eleven: true }),+ L("fi", "Finnish", { cb: true, eleven: true }),+ L("el", "Greek", { cb: true, eleven: true }),+ L("sw", "Swahili", { cb: true, heygen: "Swahili (Kenya)" }),+ L("id", "Indonesian", { eleven: true }),+ L("uk", "Ukrainian", { eleven: true }),+ L("cs", "Czech", { eleven: true }),+ L("ro", "Romanian", { eleven: true }),+ L("vi", "Vietnamese", { heygen: "Vietnamese (Vietnam)", eleven: true }),+ L("ta", "Tamil", { eleven: true }),+ L("fil", "Filipino", { eleven: true }),+ L("hu", "Hungarian", { heygen: "Hungarian (Hungary)", eleven: true }),+ L("bg", "Bulgarian", { eleven: true }),+ L("hr", "Croatian", { eleven: true }),+ L("sk", "Slovak", { eleven: true }),+ L("th", "Thai", { heygen: "Thai (Thailand)" }),+ L("bn", "Bengali", { heygen: "Bengali (India)" }),+];++export const languageByCode = (code: string | undefined): DubLanguage | undefined => DUB_LANGUAGES.find((l) => l.code === code);++/** The dubbing routes a target language can go through. */+export type DubRoute = "open" | "cloud-steps" | "heygen-translate" | "heygen-translate-fast" | "elevenlabs-dubbing";++/** Whether `lang` can be a target on a route (the LLM translates into any of them; the voice is the limit). */+export function supportsTarget(route: DubRoute, lang: DubLanguage): boolean {+ if (route === "open") return !!lang.chatterbox;+ if (route === "elevenlabs-dubbing") return !!lang.eleven;+ if (route === "heygen-translate" || route === "heygen-translate-fast") return !!lang.heygen;+ // Cloud steps: ElevenLabs v4 speaks the translation (it reads any of these), then the voice is converted.+ return true;+}diff --git a/src/lib/catalog/apps.ts b/src/lib/catalog/apps.tsindex daa06c9b..bcb7c6e9 100644--- a/src/lib/catalog/apps.ts+++ b/src/lib/catalog/apps.ts@@ -91,6 +91,13 @@ function videoApp(a: Omit<AppSpec, "cloud" | "open">): Preset {return app({ ...a, cloud: VIDEO_CLOUD, open: VIDEO_OPEN });}+/** An option whose choices also set one of the model's settings (params.extra[param]). */+const angleOption = (key: string, label: string, param: string, choices: [string, string, number][]): PresetOption => ({+ key,+ label,+ choices: choices.map(([l, p, v]) => ({ value: slug(l), label: l, prompt: p, extra: { [param]: v } })),+});+const opt = (key: string, label: string, choices: [string, string][]): PresetOption => ({key,label,@@ -248,25 +255,42 @@ export const APPS: Preset[] = [icon: "Rotate3d",hue: 190,badges: ["top"],+ // The cloud model turns its rotate / tilt / zoom settings into the Multiple-Angles LoRA's own words; the open+ // route runs that LoRA on Qwen-Image-Edit 2511 with the same words ("<sks> front-left quarter view …").options: [- opt("angle", "Angle", [- ["Front", "a straight-on front view at eye level"],- ["Left 45°", "rotated 45 degrees to the left around the subject"],- ["Right 45°", "rotated 45 degrees to the right around the subject"],- ["Left profile", "a full left side profile view"],- ["Right profile", "a full right side profile view"],- ["Back", "a view from directly behind"],- ["High angle", "a high-angle view looking down at the subject"],- ["Bird's eye", "a top-down bird's-eye view from directly above"],- ["Low angle", "a low-angle view looking up at the subject"],- ["Worm's eye", "an extreme worm's-eye view from the ground"],- ["Close-up", "a tight close-up"],- ["Wide", "a wide shot showing the full environment"],+ angleOption("angle", "Angle", "horizontal_angle", [+ ["Front", "front view", 0],+ ["Front right", "front-right quarter view", 45],+ ["Right side", "right side view", 90],+ ["Back right", "back-right quarter view", 135],+ ["Back", "back view", 180],+ ["Back left", "back-left quarter view", 225],+ ["Left side", "left side view", 270],+ ["Front left", "front-left quarter view", 315],+ ]),+ angleOption("height", "Height", "vertical_angle", [+ ["Eye level", "eye-level shot", 0],+ ["Low angle", "low-angle shot", -30],+ ["Elevated", "elevated shot", 30],+ ["High angle", "high-angle shot", 60],+ ]),+ angleOption("distance", "Distance", "zoom", [+ ["Medium", "medium shot", 5],+ ["Close-up", "close-up", 10],+ ["Wide", "wide shot", 0],]),],- prompt:- "Show the exact same scene and subject from {option:angle}, as if the camera physically moved. Keep identity, outfit, props, lighting direction and environment consistent; reveal plausible unseen sides.",- parity: "Open version should add the Qwen-Edit multiple-angles LoRA for best results",+ userPrompt: "optional",+ placeholder: "Anything to keep in mind (optional)",+ prompt: "Show the exact same scene and subject as a {option:angle}, {option:height}, {option:distance}, as if the camera physically moved. Keep identity, outfit, props, lighting and environment consistent. {prompt}",+ cloud: { modelId: "qwen-multiple-angles", op: "edit", promptTemplate: "{prompt}" },+ open: {+ modelId: "oss-qwen-edit",+ op: "edit",+ loras: [{ file: "qwen-image-edit-2511-multiple-angles-lora.safetensors", url: "https://huggingface.co/fal/Qwen-Image-Edit-2511-Multiple-Angles-LoRA/resolve/main/qwen-image-edit-2511-multiple-angles-lora.safetensors", strength: 1 }],+ promptTemplate: "<sks> {option:angle} {option:height} {option:distance}. {prompt}",+ },+ parity: "Both engines run the same Multiple-Angles LoRA: hosted by fal on the cloud, added to Qwen-Image-Edit 2511 on the open engine (0.3 GB)",}),app({name: "Shots",@@ -472,6 +496,31 @@ export const APPS: Preset[] = ["Create a professional product packshot of the product from the image on {option:bg}. Keep the product's exact shape, label, text and colors. Commercial photography, crisp focus.",parity: "Higgsfield renders it as an animated end-card video; Fuobe makes the still (animate it with Product 360)",}),+ app({+ name: "Product Shot",+ category: "Product",+ description: "Your product photo, relit into a new scene",+ icon: "Aperture",+ hue: 30,+ badges: ["new"],+ inputs: [product, { key: "image2", label: "Scene reference", hint: "Optional: a photo of the setting you want", accept: "image", required: false }],+ options: [+ opt("scene", "Scene", [+ ["Marble counter", "on a white marble kitchen counter, soft morning window light"],+ ["Studio podium", "on a minimal stone podium in a studio, soft key light and gentle shadows"],+ ["Nature", "outdoors on a mossy rock in a sunlit forest, dappled light"],+ ["Beach", "on warm sand at the beach at golden hour, the sea softly blurred behind"],+ ["Dark luxury", "on dark slate with dramatic rim light and reflections, luxury mood"],+ ["Bathroom shelf", "on a clean bathroom shelf with plants, bright and airy"],+ ]),+ ],+ userPrompt: "optional",+ placeholder: "Or describe your own scene (optional)",+ prompt: "The product {option:scene}. {prompt}",+ cloud: { modelId: "bria-product-shot", op: "edit" },+ open: { modelId: "oss-product-shot", op: "edit" },+ parity: "The open version cuts the product out, puts it on white and relights it into the scene with Qwen-Image-Edit 2509 + the White_to_Scene LoRA; the scene reference photo is used on the cloud only",+ }),app({name: "Product Placement",category: "Product",@@ -555,6 +604,19 @@ export const APPS: Preset[] = [cloud: VIDEO_CLOUD,open: VIDEO_OPEN,}),+ app({+ name: "Image to 3D",+ category: "Product",+ description: "A 3D model of your product (.glb) to spin, download and animate",+ icon: "Box",+ hue: 240,+ badges: ["new"],+ inputs: [product],+ prompt: "",+ cloud: { modelId: "hunyuan-3d-3-1-pro", op: "image-to-3d" },+ open: { modelId: "oss-trellis2", op: "image-to-3d" },+ parity: "The open version (TRELLIS.2) also renders a turntable video; for cloud models the 3D page records one in your browser",+ }),videoApp({name: "Billboard Ad",category: "Product",@@ -767,6 +829,8 @@ export const APPS: Preset[] = [],prompt:"Dress the person from the first image in the garment from the second image. Keep the person's face, body, pose and background; reproduce the garment's fabric, color, pattern, logo and fit realistically, with natural folds and shadows.",+ // FASHN Try-On 1.6 was built for exactly this (Garment / Quality settings); it takes no prompt.+ cloud: { modelId: "fashn-tryon", op: "edit" },}),app({name: "Outfit Swap",@@ -1608,8 +1672,10 @@ export const APPS: Preset[] = ["Create an exploded knolling layout of everything in the image: each object, garment and accessory separated and neatly arranged on a clean light background, each with a small label naming it. Keep every item's exact design, colors and logos.",parity: "Approximation: Higgsfield's AI Lens also identifies brands and prices; Fuobe only produces the breakdown image",}),+ // Higgsfield's Virality Predictor (a brain-response model) is the /virality page: a labelled heuristic hook+ // analysis. This app is the "make a stronger opening frame" step it links to.app({- name: "Virality Predictor",+ name: "Hook Frame",category: "Utility",description: "Turn your opening frame into a stronger hook",icon: "TrendingUp",@@ -1617,8 +1683,6 @@ export const APPS: Preset[] = [inputs: [{ key: "image", label: "Opening frame", hint: "The first frame of your video", accept: "image", required: true }],prompt:"Rework this opening frame into a scroll-stopping hook thumbnail: stronger contrast and color, clearer focal point on the face or product, a more expressive moment and bold composition. Keep the same people, product and setting; add no text.",- parity:- "Not reproducible: Higgsfield scores a clip with a proprietary engagement model (score, hold rate, heatmap). Fuobe has no analysis model, so this app only improves the hook frame",}),app({name: "Similarity Score",diff --git a/src/lib/catalog/cloud-models.generated.ts b/src/lib/catalog/cloud-models.generated.tsindex 547e1516..3c71fdad 100644--- a/src/lib/catalog/cloud-models.generated.ts+++ b/src/lib/catalog/cloud-models.generated.ts@@ -11449,6 +11449,34 @@ export const CLOUD_MODELS: ModelDef[] = ["usd": 0.0007}},+ {+ "id": "elevenlabs-voice-isolation",+ "name": "ElevenLabs Voice Isolation",+ "vendor": "ElevenLabs",+ "family": "elevenlabs",+ "engine": "cloud",+ "kind": "audio",+ "tagline": "Clean speech from a video or recording \u2014 music and noise removed",+ "routes": [+ {+ "op": "separate-audio",+ "provider": "fal",+ "endpoint": "fal-ai/elevenlabs/audio-isolation",+ "map": {+ "prompt": false,+ "video": "video_url",+ "audio": "audio_url"+ }+ }+ ],+ "options": {+ "promptless": true+ },+ "pricing": {+ "unit": "minute",+ "usd": 0.1+ }+ },{"id": "hunyuan-3d-3-1-pro","name": "Hunyuan3D 3.1 Pro",diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.tsindex 32e7eb4e..b9ab2ca0 100644--- a/src/lib/catalog/plan.ts+++ b/src/lib/catalog/plan.ts@@ -136,6 +136,9 @@ export function planGeneration(// Preset params/LoRAs are tuned for the preset's own model; other compatible models only get the prompt.const sameModel = route.modelId === model.id;params = { ...model.defaults, ...(sameModel ? route.params : {}), ...req.params };+ // Option choices that set model settings (Angles: rotate / tilt / zoom); a value the user set wins.+ const chosen = Object.assign({}, ...(preset.options ?? []).map((o) => o.choices.find((c) => c.value === (req.presetOptions?.[o.key] ?? o.default ?? o.choices[0]?.value))?.extra ?? {}));+ if (sameModel && Object.keys(chosen).length) params = { ...params, extra: { ...chosen, ...params.extra } };loras = sameModel ? (route.loras ?? []) : [];if (sameModel) op = op ?? route.op;}diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex 7c8b75ef..5ef2e137 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -543,6 +543,8 @@ export interface PresetChoice {label: string;/** Text substituted for {option:<key>} in the prompt template. */prompt: string;+ /** Model settings this choice sets (params.extra), e.g. the camera angle sliders of Qwen Multiple Angles; what the user set wins. */+ extra?: Record<string, number | string>;}export interface PresetOption {diff --git a/src/server/db.ts b/src/server/db.tsindex 73575c8d..bdc08269 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -175,6 +175,21 @@ const MIGRATIONS: string[] = [edited_at INTEGER);CREATE INDEX IF NOT EXISTS canvases_updated ON canvases(updated_at DESC);`,+ // Translate & dub sessions and Katana jobs (av-tools): what the person asked for and the generation ids of each step.+ `CREATE TABLE IF NOT EXISTS dub_sessions (+ id TEXT PRIMARY KEY,+ data_json TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS dub_sessions_updated ON dub_sessions(updated_at DESC);+ CREATE TABLE IF NOT EXISTS katana_jobs (+ id TEXT PRIMARY KEY,+ data_json TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS katana_jobs_updated ON katana_jobs(updated_at DESC);`,];declare global {diff --git a/src/server/dub.ts b/src/server/dub.tsnew file mode 100644index 00000000..4f7e0c4f--- /dev/null+++ b/src/server/dub.ts@@ -0,0 +1,164 @@+import "server-only";+import { nanoid } from "nanoid";+import { z } from "zod";+import type { Cue } from "@/lib/cues";+import {+ DUB_FEATURE,+ languageStage,+ oneShotRequests,+ prepareMedia,+ prepareSteps,+ reviewCues,+ voiceSteps,+ type DubSession,+ type DubSessionView,+ type OneShotModel,+} from "@/lib/av/dub";+import { normalizeCues } from "@/lib/av/cue-edit";+import type { Engine, Generation } from "@/lib/catalog/types";+import { createPipeline } from "./chains";+import { db } from "./db";+import { createGenerations, getGeneration } from "./generations";++/**+ * Translate & dub sessions. A session remembers the source video, the languages and which generations+ * make each step; the steps themselves are ordinary chained generations (createPipeline), so they run,+ * survive restarts and show in the Library like everything else. Step mode is two pipelines with a+ * review in between: prepare (stems → transcript → translations) and, per language, voice.+ */++/** A cue as the browser sends it (review and captions editors). */+export const CueSchema = z.object({ start: z.number().min(0).max(36_000), end: z.number().min(0).max(36_000), text: z.string().max(2000) });++interface Row {+ id: string;+ data_json: string;+ created_at: number;+ updated_at: number;+}++const toSession = (r: Row): DubSession => ({ ...(JSON.parse(r.data_json) as Omit<DubSession, "id" | "createdAt" | "updatedAt">), id: r.id, createdAt: r.created_at, updatedAt: r.updated_at });++function save(s: DubSession): DubSession {+ const { id, createdAt, ...data } = s;+ const now = Date.now();+ delete (data as Partial<DubSession>).updatedAt;+ db()+ .prepare("INSERT INTO dub_sessions (id, data_json, created_at, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET data_json = excluded.data_json, updated_at = excluded.updated_at")+ .run(id, JSON.stringify(data), createdAt, now);+ return { ...s, updatedAt: now };+}++export function getDubSession(id: string): DubSession | null {+ const r = db().prepare("SELECT * FROM dub_sessions WHERE id = ?").get(id) as Row | undefined;+ return r ? toSession(r) : null;+}++/** Every generation id a session refers to. */+function sessionIds(s: DubSession): string[] {+ return [+ ...Object.values(s.prepare ?? {}),+ ...Object.values(s.oneshot ?? {}),+ ...Object.values(s.voices ?? {}).flatMap((runs) => runs.flatMap((r) => Object.values(r.ids))),+ ];+}++export function dubView(s: DubSession): DubSessionView {+ const generations: Record<string, Generation> = {};+ for (const id of sessionIds(s)) {+ // Trashed steps still count for the session (their status), like Cinema's takes.+ const g = getGeneration(id, { includeDeleted: true });+ if (g) generations[id] = g;+ }+ return { ...s, generations };+}++export function listDubSessions(limit = 30): DubSessionView[] {+ const rows = db().prepare("SELECT * FROM dub_sessions ORDER BY updated_at DESC LIMIT ?").all(Math.max(1, Math.min(100, limit))) as Row[];+ return rows.map((r) => dubView(toSession(r)));+}++export interface CreateDubInput {+ engine: Engine;+ mode: "oneshot" | "steps";+ video: string;+ title?: string;+ source?: string;+ targets: string[];+ model?: OneShotModel;+}++export function createDubSession(input: CreateDubInput): DubSessionView {+ if (input.mode === "oneshot" && input.engine === "open") throw new Error("One-shot dubbing is a cloud service — the open engine dubs step by step");+ const now = Date.now();+ const title = input.title?.trim().slice(0, 120) || "Dubbed video";+ const base: DubSession = {+ id: nanoid(10),+ title,+ engine: input.engine,+ mode: input.mode,+ video: input.video,+ source: input.source || "auto",+ targets: [...new Set(input.targets)],+ batchId: nanoid(10),+ createdAt: now,+ updatedAt: now,+ };+ if (input.mode === "oneshot") {+ const model = input.model ?? "heygen-translate";+ const jobs = oneShotRequests({ model, video: input.video, source: input.source, targets: base.targets, title });+ const oneshot: Record<string, string> = {};+ const made: Generation[] = [];+ try {+ for (const j of jobs) {+ const g = createGenerations(j.request, { batchId: base.batchId })[0];+ made.push(g);+ oneshot[j.lang.code] = g.id;+ }+ } catch (e) {+ throw new Error(made.length ? `${(e as Error).message} (the other languages were started)` : (e as Error).message);+ }+ return dubView(save({ ...base, model, oneshot }));+ }+ const steps = prepareSteps({ engine: input.engine, video: input.video, source: input.source, targets: base.targets, title });+ const run = createPipeline(steps, { batchId: base.batchId });+ const prepare = Object.fromEntries(Object.entries(run.byKey).map(([k, g]) => [k, g.id]));+ return dubView(save({ ...base, prepare }));+}++/** Save the reviewed lines of one language (nothing is spoken until voiceDub). */+export function saveDubDraft(id: string, lang: string, cues: Cue[]): DubSessionView {+ const s = getDubSession(id);+ if (!s) throw new Error("This dub no longer exists");+ if (!s.targets.includes(lang)) throw new Error("That language isn't part of this dub");+ return dubView(save({ ...s, drafts: { ...s.drafts, [lang]: normalizeCues(cues) } }));+}++/** Speak the reviewed lines of one language: the voice pipeline. */+export function voiceDub(id: string, lang: string, opts: { cues?: Cue[]; lipsync?: boolean } = {}): DubSessionView {+ const s = getDubSession(id);+ if (!s) throw new Error("This dub no longer exists");+ if (s.mode !== "steps") throw new Error("This dub was made in one go — there's nothing to voice");+ if (!s.targets.includes(lang)) throw new Error("That language isn't part of this dub");+ const current: DubSession = opts.cues ? { ...s, drafts: { ...s.drafts, [lang]: normalizeCues(opts.cues) } } : s;+ const view = dubView(current);+ const stage = languageStage(view, lang);+ if (stage === "preparing") throw new Error("The translation isn't ready yet");+ if (stage === "failed" && !view.voices?.[lang]?.length) throw new Error("An earlier step failed — start a new dub");+ const cues = reviewCues(view, lang);+ if (!cues?.length) throw new Error("There are no translated lines to speak");+ const media = prepareMedia(view);+ if (!media.voice) throw new Error("The voice to clone is missing from the first step");+ const lipsync = opts.lipsync !== false;+ const steps = voiceSteps({ engine: s.engine, video: s.video, lang, cues, voiceRef: media.voice, background: media.background, lipsync, title: s.title });+ const run = createPipeline(steps, { batchId: s.batchId });+ const ids = Object.fromEntries(Object.entries(run.byKey).map(([k, g]) => [k, g.id]));+ const voices = { ...s.voices, [lang]: [...(s.voices?.[lang] ?? []), { ids, at: Date.now(), lipsync }] };+ return dubView(save({ ...current, voices }));+}++export function deleteDubSession(id: string): boolean {+ return db().prepare("DELETE FROM dub_sessions WHERE id = ?").run(id).changes > 0;+}++export { DUB_FEATURE };diff --git a/tests/av-dub.test.ts b/tests/av-dub.test.tsnew file mode 100644index 00000000..0814d311--- /dev/null+++ b/tests/av-dub.test.ts@@ -0,0 +1,223 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import type { Generation } from "@/lib/catalog/types";+import { cueReducer, cueProblems, formatCueTime, normalizeCues, parseCueTime } from "@/lib/av/cue-edit";+import { languageStage, oneShotRequests, prepareSteps, reviewCues, spokenText, voiceSteps, type DubSessionView } from "@/lib/av/dub";+import { DUB_LANGUAGES, supportsTarget } from "@/lib/av/languages";+import { getModel } from "@/lib/catalog";++vi.setConfig({ testTimeout: 120_000 });++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-av-dub-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.OLLAMA_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+const gens = await import("@/server/generations");+const dub = await import("@/server/dub");+const { saveFile } = await import("@/server/storage");++beforeAll(() => setSetting("demoMode", "auto"));+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++async function settle(id: string, ms = 100_000): Promise<Generation> {+ const end = Date.now() + ms;+ for (;;) {+ const g = gens.getGeneration(id)!;+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;+ if (Date.now() > end) throw new Error(`timed out: ${g.status} ${g.message}`);+ await new Promise((r) => setTimeout(r, 250));+ }+}++const clip = () => saveFile({ data: fs.readFileSync(path.join(process.cwd(), "public/samples/demo-landscape.mp4")), contentType: "video/mp4", source: "upload" }).url;++describe("dub languages", () => {+ it("name each language the way its model expects", () => {+ const heygen = new Set(getModel("heygen-translate")!.options.languages);+ const eleven = new Set(getModel("elevenlabs-dubbing")!.options.languages);+ const chatterbox = new Set(getModel("oss-chatterbox")!.options.languages);+ for (const l of DUB_LANGUAGES) {+ if (l.heygen) expect(heygen.has(l.heygen), l.heygen).toBe(true);+ if (l.eleven) expect(eleven.has(l.eleven), l.eleven).toBe(true);+ if (l.chatterbox) expect(chatterbox.has(l.chatterbox), l.chatterbox).toBe(true);+ }+ // Every Chatterbox language is a dub target on the open engine.+ expect(DUB_LANGUAGES.filter((l) => supportsTarget("open", l))).toHaveLength(23);+ });+});++describe("dub pipeline DAGs", () => {+ const video = "/api/files/uploads/clip.mp4";++ it("open: stems → transcript of the voice stem → one translation per language", () => {+ const steps = prepareSteps({ engine: "open", video, source: "en", targets: ["es", "de"] });+ expect(steps.map((s) => [s.key, s.request.modelId, s.request.op, s.after ?? null])).toEqual([+ ["stems", "oss-voice-separate", "separate-audio", null],+ ["words", "oss-qwen3-asr", "transcribe", "stems"],+ ["translate:es", "oss-text-llm", "translate", "words"],+ ["translate:de", "oss-text-llm", "translate", "words"],+ ]);+ expect(steps[1].chain).toEqual([{ slot: "audio", stem: "voice" }]);+ expect(steps[1].request.params?.sourceLanguage).toBe("en");+ expect(steps[2].chain).toEqual([{ slot: "prompt" }]);+ expect(steps[2].request.params).toEqual({ targetLanguage: "Spanish", sourceLanguage: "English" });+ expect(() => prepareSteps({ engine: "open", video, targets: ["th"] })).toThrow(/Thai isn't available on the open engine/);+ });++ it("cloud: isolated voice → Scribe → translations", () => {+ const steps = prepareSteps({ engine: "cloud", video, targets: ["fr"] });+ expect(steps.map((s) => [s.key, s.request.modelId, s.after ?? null])).toEqual([+ ["voice", "elevenlabs-voice-isolation", null],+ ["words", "scribe-v2", "voice"],+ ["translate:fr", "text-llm", "words"],+ ]);+ expect(steps[0].request.inputs).toEqual({ video });+ expect(steps[1].request.params).toBeUndefined(); // "auto" = detect+ });++ const cues = [+ { start: 0, end: 2, text: "Hola a todos" },+ { start: 2.2, end: 4, text: " bienvenidos " },+ ];++ it("open voice: cloned speech → lip re-sync → mixed over the background", () => {+ const steps = voiceSteps({ engine: "open", video, lang: "es", cues, voiceRef: "/v.wav", background: "/bg.wav" });+ expect(steps.map((s) => [s.key, s.request.modelId, s.request.op, s.after ?? null])).toEqual([+ ["speech", "oss-chatterbox", "tts", null],+ ["lips", "oss-infinitetalk-v2v", "lipsync", "speech"],+ ["film", "oss-mux", "mux", ["lips", "speech"]],+ ]);+ expect(steps[0].request).toMatchObject({ prompt: "Hola a todos\nbienvenidos", inputs: { voiceAudio: "/v.wav" }, params: { targetLanguage: "Spanish (es)" } });+ expect(steps[2].chain).toEqual([{ slot: "video" }, { slot: "audio" }]);+ expect(steps[2].request.inputs).toEqual({ audio2: "/bg.wav" });+ // Without lip re-sync the new voice goes over the original picture.+ const flat = voiceSteps({ engine: "open", video, lang: "es", cues, voiceRef: "/v.wav", background: "/bg.wav", lipsync: false });+ expect(flat.map((s) => s.key)).toEqual(["speech", "film"]);+ expect(flat[1].request.inputs).toEqual({ video, audio2: "/bg.wav" });+ });++ it("cloud voice: ElevenLabs speech → converted to the speaker's voice → Sync lipsync", () => {+ const steps = voiceSteps({ engine: "cloud", video, lang: "ja", cues, voiceRef: "/v.mp3" });+ expect(steps.map((s) => [s.key, s.request.modelId, s.request.op])).toEqual([+ ["speech", "elevenlabs-v4", "tts"],+ ["clone", "chatterbox-vc-cloud", "voice-change"],+ ["film", "sync-lipsync-3", "lipsync"],+ ]);+ expect(steps[1].request.inputs).toEqual({ voiceAudio: "/v.mp3" });+ expect(voiceSteps({ engine: "cloud", video, lang: "ja", cues, voiceRef: "/v.mp3", lipsync: false })[2].request.modelId).toBe("merge-audio-video");+ expect(() => voiceSteps({ engine: "cloud", video, lang: "ja", cues: [{ start: 0, end: 1, text: " " }], voiceRef: "/v" })).toThrow(/no lines to speak/);+ });++ it("one shot: HeyGen display names, ElevenLabs codes", () => {+ expect(oneShotRequests({ model: "heygen-translate", video, targets: ["es", "he"] }).map((r) => r.request.params?.targetLanguage)).toEqual(["Spanish", "Hebrew (Israel)"]);+ const eleven = oneShotRequests({ model: "elevenlabs-dubbing", video, source: "en", targets: ["pt"] })[0].request;+ expect(eleven).toMatchObject({ modelId: "elevenlabs-dubbing", op: "dub", params: { targetLanguage: "pt", sourceLanguage: "en" } });+ expect(() => oneShotRequests({ model: "elevenlabs-dubbing", video, targets: ["he"] })).toThrow(/isn't available on this model/);+ });++ it("spoken text is the reviewed lines, trimmed", () => {+ expect(spokenText(cues)).toBe("Hola a todos\nbienvenidos");+ });+});++describe("cue edit reducer", () => {+ const base = normalizeCues([+ { start: 2, end: 4, text: "second line" },+ { start: 0, end: 2.5, text: "first line here" },+ ]);++ it("sorts and removes overlaps", () => {+ expect(base).toEqual([+ { start: 0, end: 2, text: "first line here" },+ { start: 2, end: 4, text: "second line" },+ ]);+ });++ it("edits text and keeps timings between the neighbours", () => {+ expect(cueReducer(base, { type: "text", index: 1, text: "changed" })[1].text).toBe("changed");+ expect(cueReducer(base, { type: "time", index: 1, start: 1 })[1]).toEqual({ start: 2, end: 4, text: "second line" });+ expect(cueReducer(base, { type: "time", index: 0, end: 9 })[0].end).toBe(2);+ expect(cueReducer(base, { type: "time", index: 1, end: 2.05 })[1]).toEqual({ start: 2, end: 2.2, text: "second line" });+ });++ it("splits at the nearest space and shares the time by length", () => {+ const out = cueReducer(base, { type: "split", index: 0, caret: 6 });+ expect(out.map((c) => c.text)).toEqual(["first", "line here", "second line"]);+ expect(out[0].start).toBe(0);+ expect(out[1].end).toBe(2);+ expect(out[0].end).toBeCloseTo(2 * (5 / 14), 2);+ // A single word can't be split.+ expect(cueReducer([{ start: 0, end: 1, text: "word" }], { type: "split", index: 0 })).toHaveLength(1);+ });++ it("merges with the next line, removes, inserts in a gap and shifts", () => {+ expect(cueReducer(base, { type: "merge", index: 0 })).toEqual([{ start: 0, end: 4, text: "first line here second line" }]);+ expect(cueReducer(base, { type: "remove", index: 0 })).toHaveLength(1);+ expect(cueReducer(base, { type: "insert", index: 1 })[2]).toEqual({ start: 4, end: 6, text: "" });+ // No room between two touching cues.+ expect(cueReducer(base, { type: "insert", index: 0 })).toHaveLength(2);+ expect(cueReducer(base, { type: "shift", seconds: -5 })[0].start).toBe(0);+ expect(cueReducer(base, { type: "shift", seconds: 1.5 })[1]).toEqual({ start: 3.5, end: 5.5, text: "second line" });+ });++ it("reports problems and reads times back", () => {+ expect(cueProblems([{ start: 0, end: 1, text: "" }], 10)).toEqual(["1 empty line"]);+ expect(cueProblems([{ start: 12, end: 13, text: "late" }], 10)).toEqual(["A line starts after the end of the video"]);+ expect(formatCueTime(62.5)).toBe("1:02.5");+ expect(parseCueTime("1:02.5")).toBe(62.5);+ expect(parseCueTime("abc")).toBeNull();+ });+});++describe("dub sessions (demo mode)", () => {+ async function prepared(engine: "open" | "cloud") {+ const s = dub.createDubSession({ engine, mode: "steps", video: clip(), title: "My clip", source: "en", targets: ["es"] });+ for (const id of Object.values(s.prepare!)) expect((await settle(id)).status).toBe("succeeded");+ return dub.dubView(dub.getDubSession(s.id)!);+ }++ it.each(["open", "cloud"] as const)("%s: prepare, review, edit and voice a language", async (engine) => {+ const view = await prepared(engine);+ expect(languageStage(view, "es")).toBe("review");+ const lines = reviewCues(view, "es")!;+ expect(lines.length).toBeGreaterThan(1);+ expect(lines[0].text).toMatch(/^\[Spanish\]/);+ // Edits are saved per language and spoken as edited.+ const edited = cueReducer(lines, { type: "text", index: 0, text: "Hola, esto es una prueba" });+ const saved = dub.saveDubDraft(view.id, "es", edited);+ expect(reviewCues(saved, "es")![0].text).toBe("Hola, esto es una prueba");+ const voiced = dub.voiceDub(view.id, "es");+ const run = voiced.voices!.es[0];+ expect(Object.keys(run.ids)).toEqual(engine === "open" ? ["speech", "lips", "film"] : ["speech", "clone", "film"]);+ expect(voiced.generations[run.ids.speech].request.prompt).toContain("Hola, esto es una prueba");+ if (engine === "open") {+ // The background stem rides along to the mix.+ expect(voiced.generations[run.ids.film].request.inputs?.audio2).toMatch(/^\/api\/files\//);+ expect(voiced.generations[run.ids.speech].request.inputs?.voiceAudio).toMatch(/^\/api\/files\//);+ }+ expect(languageStage(voiced, "es")).toBe("voicing");+ expect((await settle(run.ids.film)).status).toBe("succeeded");+ expect(languageStage(dub.dubView(dub.getDubSession(view.id)!), "es")).toBe("done");+ // All steps share the session's batch (one stack in the Library).+ expect(new Set(Object.values(dub.dubView(dub.getDubSession(view.id)!).generations).map((g) => g.batchId))).toEqual(new Set([view.batchId]));+ });++ it("refuses to voice before the translation is ready, and one-shot on the open engine", () => {+ const s = dub.createDubSession({ engine: "open", mode: "steps", video: clip(), targets: ["fr"] });+ expect(() => dub.voiceDub(s.id, "fr")).toThrow(/isn't ready yet/);+ expect(() => dub.createDubSession({ engine: "open", mode: "oneshot", video: clip(), targets: ["fr"] })).toThrow(/cloud service/);+ });++ it("one shot (cloud): one dub job per language", async () => {+ const s = dub.createDubSession({ engine: "cloud", mode: "oneshot", model: "heygen-translate", video: clip(), targets: ["es", "fr"] });+ expect(Object.keys(s.oneshot!)).toEqual(["es", "fr"]);+ const g = await settle(s.oneshot!.es);+ expect(g.request.params?.targetLanguage).toBe("Spanish");+ expect(languageStage(dub.dubView(dub.getDubSession(s.id)!) as DubSessionView, "es")).toBe("done");+ expect(dub.listDubSessions().map((x) => x.id)).toContain(s.id);+ });+});diff --git a/tests/cloud-catalog.test.ts b/tests/cloud-catalog.test.tsindex a6aa5f5b..88b9ad34 100644--- a/tests/cloud-catalog.test.ts+++ b/tests/cloud-catalog.test.ts@@ -152,7 +152,7 @@ describe("round-3 cloud models", () => {expect(ids("model3d", ["image-to-3d"])[0]).toBe("hunyuan-3d-3-1-pro");expect(ids("text", ["transcribe"])[0]).toBe("scribe-v2");expect(ids("video", ["captions"])[0]).toBe("auto-subtitle");- expect(ids("audio", ["separate-audio"])).toEqual(["demucs"]);+ expect(ids("audio", ["separate-audio"])).toEqual(["demucs", "elevenlabs-voice-isolation"]);// Utility steps never show up in a picker.expect(modelsFor({ ops: ["trim", "mux"] }).filter((m) => m.engine === "cloud")).toEqual([]);});