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
Restore 3: /api/restore, its estimate and the prompt writer
Claude739a23a0ab66
diff --git a/src/app/api/restore/estimate/route.ts b/src/app/api/restore/estimate/route.tsnew file mode 100644index 00000000..c1477a36--- /dev/null+++ b/src/app/api/restore/estimate/route.ts@@ -0,0 +1,11 @@+import { estimateRestore, RestoreEstimateSchema } from "@/server/restore";+import { body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";++/** The price, the windows or pieces and the notes for the current settings, before anything runs ("Free" on your GPU). */+export const POST = handler({ access: "signed-in" }, async (request: Request) => {+ return handle(async () => {+ const input = await body(request, RestoreEstimateSchema, "Add the clip to restore and pick an engine");+ return Response.json(estimateRestore(input));+ });+});diff --git a/src/app/api/restore/prompt/route.ts b/src/app/api/restore/prompt/route.tsnew file mode 100644index 00000000..121d8883--- /dev/null+++ b/src/app/api/restore/prompt/route.ts@@ -0,0 +1,11 @@+import { PromptSchema, writeRestorePrompt } from "@/server/restore";+import { body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";++/** Write the period / place / light sentence and the negative from a few frames: Claude, Ollama, or Fuobe's offline template. Never generates. */+export const POST = handler({ access: "signed-in" }, async (request: Request) => {+ return handle(async () => {+ const input = await body(request, PromptSchema, "Add a few frames of the clip or a few words about it");+ return Response.json(await writeRestorePrompt(input));+ });+});diff --git a/src/app/api/restore/route.ts b/src/app/api/restore/route.tsnew file mode 100644index 00000000..40068fbc--- /dev/null+++ b/src/app/api/restore/route.ts@@ -0,0 +1,13 @@+import { createRestore, RestoreBodySchema } from "@/server/restore";+import { body, handle, once } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";++/** Restore & colourise a clip (Fuobe Restore): the prompt is written first when none is given; windows or pieces are joined and the sound put back. */+export const POST = handler({ access: "signed-in" }, async (request: Request) => {+ return handle(async () => {+ const input = await body(request, RestoreBodySchema, "Add the clip to restore and pick an engine");+ // A repeated requestId (a second click on Restore) gets the run the first one started.+ const result = await once("restore", input.requestId, () => createRestore(input));+ return Response.json(result, { status: 201 });+ });+});diff --git a/src/server/restore.ts b/src/server/restore.tsnew file mode 100644index 00000000..c7d378f9--- /dev/null+++ b/src/server/restore.ts@@ -0,0 +1,273 @@+import "server-only";+import { z } from "zod";+import { getModel } from "@/lib/catalog";+import {+ CLOUD_NOTE,+ GATED_NOTE,+ GPU_NOTE,+ offlineRestorePrompt,+ parsePromptAnswer,+ planRestore,+ PROMPT_SYSTEM,+ promptRequest,+ RESTORE,+ restoreNegative,+ restoreProblem,+ restoreTitle,+ tileGrid,+ type RestorePlanInput,+ type Size,+} from "@/lib/catalog/restore";+import type { PlanStep } from "@/lib/catalog/shorts";+import type { Engine, Generation } from "@/lib/catalog/types";+import { ACCESS_PLACE } from "@/lib/model-access";+import { createPipeline } from "./chains";+import { llmText, llmTextBackend } from "./enhance";+import { previewChained } from "./generations";+import { hasHfToken } from "./loras";+import { isOffered, offeredModel } from "./model-access";+import { probeOllama } from "./providers/llm";+import { engineMode, getSetting } from "./settings";+import { probeSource, ShortsError } from "./shorts";++/**+ * Video tools → Restore & colourise (Fuobe Restore, package archive-restore): plans, prices and starts a run+ * (src/lib/catalog/restore.ts) as one pipeline of ordinary generations: feature "restore" for the finished video,+ * "restore-step" for the windows, pieces, hand-off frames and joins. The prompt is written by an LLM from a few frames+ * (Claude, or Ollama on the open engine), else by Fuobe's offline template. No table of its own: the page's history is a+ * feed. The gated Restore IC-LoRA is fetched before the first window with the user's Hugging Face token (src/server/loras.ts).+ */++export { ShortsError as RestoreError };++const fileUrl = z.string().startsWith("/api/files/").max(500);++const source = z.object({+ url: fileUrl,+ name: z.string().max(200).optional(),+ duration: z.number().finite().positive().max(3600).optional(),+ fps: z.number().finite().positive().max(240).optional(),+ width: z.number().int().positive().max(20000).optional(),+ height: z.number().int().positive().max(20000).optional(),+ hasAudio: z.boolean().optional(),+});++/** The body of /api/restore (and /estimate). */+export const RestoreBodySchema = z.object({+ engine: z.enum(["cloud", "open"]),+ source,+ /** Period, place, light, materials, clothing; empty: written before the run (LLM or the offline template). */+ prompt: z.string().max(4000).optional(),+ /** What it must not invent; empty: the default list. */+ negative: z.string().max(4000).optional(),+ /** Your few words for the writer, when the prompt is left to it. */+ hint: z.string().max(600).optional(),+ /** GPU only: Restore to 4K (the Detail Refine pass). */+ refine: z.boolean().optional(),+ /** GPU only: keep one field of interlaced frames first. */+ deinterlace: z.boolean().optional(),+ /** A reference picture (true colours, a face, a sign). */+ reference: fileUrl.optional(),+ resolution: z.string().max(10).optional(),+ seed: z.number().int().min(0).max(2 ** 48).optional(),+ requestId: z.string().trim().min(8).max(64).optional(),+});+export type RestoreBody = z.input<typeof RestoreBodySchema>;++/** The estimate is asked for before the upload finishes: any URL stands in. */+export const RestoreEstimateSchema = RestoreBodySchema.extend({+ source: source.extend({ url: z.string().max(500).default("/api/files/placeholder.mp4") }),+ reference: z.string().max(500).optional(),+});++const frame = z+ .string()+ .max(2_000_000)+ .regex(/^data:image\/(jpeg|png|webp);base64,[A-Za-z0-9+/=]+$/);++/** The body of /api/restore/prompt: what the writer works from. */+export const PromptSchema = z.object({+ engine: z.enum(["cloud", "open"]),+ hint: z.string().max(600).optional(),+ /** A few frames of the clip the browser grabbed (JPEG or PNG data URLs, about 1.5 MB each at most). */+ frames: z.array(frame).max(4).default([]),+ seconds: z.number().finite().positive().max(3600).optional(),+});++const mustMatchMode = (engine: Engine) => {+ const mode = engineMode();+ if (mode !== "both" && mode !== engine) {+ throw new ShortsError(+ mode === "open" ? "This install runs open-source models only (Settings → Engine mode)" : "This install runs paid cloud APIs only (Settings → Engine mode), and this runs on your GPU (open source)",+ 422,+ );+ }+};++const mustBeOffered = (engine: Engine) => {+ if (!isOffered(RESTORE.model, engine)) throw new ShortsError(`Fuobe Restore is switched off ${engine === "open" ? "on your GPU" : "in the cloud"} in ${ACCESS_PLACE}`, 422);+};++// ---------------------------------------------------------------------------+// The prompt++export interface PromptAnswer {+ prompt: string;+ negative: string;+ by: "claude" | "ollama" | "offline";+ why?: string;+}++/**+ * Write the prompt and the negative: Claude (cloud engine) or Ollama with a vision model (open engine, or no Claude key)+ * sees up to four frames; without one (no key, Ollama not running, demo mode, the text model switched off) Fuobe's+ * offline template is filled with the user's words. Never generates video.+ */+export async function writeRestorePrompt(body: z.infer<typeof PromptSchema>): Promise<PromptAnswer> {+ mustMatchMode(body.engine);+ const offline = (why: string): PromptAnswer => ({ ...offlineRestorePrompt(body.hint), by: "offline", why });+ if (getSetting("demoMode") === "on") return offline("demo mode");+ const textModel = getModel(body.engine === "open" ? "oss-text-llm" : "text-llm");+ if (!textModel || !offeredModel(textModel)) return offline(`the text model is switched off in ${ACCESS_PLACE}`);+ const backend = llmTextBackend();+ const ollama = backend === "ollama" || (backend === "claude" && body.engine === "open");+ if (!backend) return offline("no text model is set up (Settings → Prompt enhancement)");+ if (ollama && !(await probeOllama())) return offline("Ollama isn't running");+ const images = body.frames.map((f) => ({ data: Buffer.from(f.split(",")[1], "base64"), contentType: f.slice(5, f.indexOf(";")) }));+ const answer = parsePromptAnswer(await llmText(PROMPT_SYSTEM, promptRequest({ hint: body.hint, frames: images.length, seconds: body.seconds }), images, { ollamaOnly: body.engine === "open" }));+ if (!answer) return offline(ollama ? "Ollama didn't answer (it needs a vision model to see the frames: qwen3-vl, gemma3…)" : "the text model didn't answer");+ return { ...answer, by: ollama ? "ollama" : "claude" };+}++// ---------------------------------------------------------------------------+// Plan, price, run++function planInput(body: z.infer<typeof RestoreBodySchema>, info: Awaited<ReturnType<typeof probeSource>> | Record<string, never>, prompt: string, probed: boolean): { input: RestorePlanInput; notes: string[] } {+ const engine = body.engine;+ const src = {+ url: body.source.url,+ duration: info.duration ?? body.source.duration,+ fps: info.fps ?? body.source.fps,+ width: info.width ?? body.source.width,+ height: info.height ?? body.source.height,+ // Sound we couldn't read counts as none (putting it back would fail after the run was paid for).+ hasAudio: probed ? (info.hasAudio ?? false) : (body.source.hasAudio ?? false),+ };+ const resolution = engine === "cloud" ? (body.resolution ?? RESTORE.cloudResolution) : undefined;+ const problem = restoreProblem({ engine, source: src, refine: body.refine, resolution });+ if (problem) throw new ShortsError(problem, 422);+ if (engine === "cloud" && body.deinterlace) throw new ShortsError("Deinterlacing runs on your GPU: the cloud endpoint takes the clip as it is", 422);+ const notes: string[] = [];+ if (engine === "open") {+ notes.push(GPU_NOTE);+ if (body.deinterlace) notes.push("Deinterlacing keeps one field of each frame (ComfyUI has no field-matching filter; telecined film keeps its repeated frames)");+ if (body.refine) notes.push("Restore to 4K adds a detail pass at twice the size with Lightricks' Detail Refine IC-LoRA (1.3 GB, also gated): restore first, refine second");+ } else {+ notes.push(CLOUD_NOTE);+ notes.push("Each piece of up to 97 frames starts from the last restored frame of the one before, so the colour carries over");+ }+ if (body.reference) notes.push(engine === "open" ? "Your reference picture goes to every window at frame_idx −1 (true colours, faces, signs)" : "In the cloud your picture is the first frame: give the clip's first frame already in colour");+ if (!hasHfToken()) notes.push(GATED_NOTE);+ if (src.hasAudio) notes.push("Your clip's own sound is put back on the result");+ return {+ notes,+ input: {+ engine,+ title: restoreTitle(prompt, body.source.name),+ source: src,+ prompt,+ negative: body.negative?.trim() || restoreNegative(),+ ...(engine === "open" && body.refine ? { refine: true } : {}),+ ...(engine === "open" && body.deinterlace ? { deinterlace: true } : {}),+ ...(body.reference ? { reference: body.reference } : {}),+ ...(resolution ? { resolution } : {}),+ ...(body.seed !== undefined ? { seed: body.seed } : {}),+ },+ };+}++const withChain = (s: PlanStep) => ({ ...s.request, ...(s.chain ? { chain: s.chain } : {}) });++/** What the steps cost together (null when a price is unknown) and whether they would run as a demo. */+function price(steps: PlanStep[]): { costUsd: number | null; demo: boolean } {+ let cost: number | null = 0;+ let demo = false;+ for (const s of steps) {+ let p: ReturnType<typeof previewChained>;+ try {+ p = previewChained(withChain(s), s.after?.length ?? 0);+ } catch (e) {+ throw new ShortsError((e as Error).message, 422);+ }+ demo ||= p.demo;+ cost = cost === null || p.costUsd === null ? null : cost + p.costUsd;+ }+ return { costUsd: cost === null ? null : Math.round(cost * 10000) / 10000, demo };+}++export interface RestoreEstimate {+ costUsd: number | null;+ demo: boolean;+ engine: Engine;+ /** Windows (GPU) or pieces (cloud). */+ pieces: number;+ canvas: Size;+ tiles: number;+ refined?: Size;+ seconds: number;+ dropped: number;+ steps: number;+ resolution?: string;+ /** A Hugging Face token is set (the gated LoRA downloads with it). */+ hfToken: boolean;+ notes: string[];+}++export function estimateRestore(body: z.infer<typeof RestoreEstimateSchema>): RestoreEstimate {+ mustMatchMode(body.engine);+ mustBeOffered(body.engine);+ // The price doesn't depend on the words: a stand-in prompt when none is written yet.+ const { input, notes } = planInput(body as z.infer<typeof RestoreBodySchema>, {}, body.prompt?.trim() || offlineRestorePrompt(body.hint).prompt, false);+ const plan = planRestore(input);+ return {+ ...price(plan.steps),+ engine: body.engine,+ pieces: plan.pieces,+ canvas: plan.canvas,+ tiles: body.engine === "open" ? tileGrid(plan.canvas).tiles : 1,+ ...(plan.refined ? { refined: plan.refined } : {}),+ seconds: Math.round((input.source.duration ?? 0) * 100) / 100,+ dropped: plan.dropped,+ steps: plan.steps.length,+ ...(input.resolution ? { resolution: input.resolution } : {}),+ hfToken: hasHfToken(),+ notes,+ };+}++/** Start the run; a run with no prompt gets one written first. Returns the finished video's generation and the words used. */+export async function createRestore(body: z.infer<typeof RestoreBodySchema>): Promise<{ final: Generation; items: Generation[]; prompt: string; negative: string; by: PromptAnswer["by"] | "you" }> {+ mustMatchMode(body.engine);+ mustBeOffered(body.engine);+ const info = await probeSource(body.source.url);+ let prompt = body.prompt?.trim() ?? "";+ let negative = body.negative?.trim() ?? "";+ let by: PromptAnswer["by"] | "you" = "you";+ // Refused before the writer is asked (a clip too long, 4K in the cloud).+ if (!prompt) planInput(body, info, "the scene, natural colour", true);+ if (!prompt) {+ const written = await writeRestorePrompt({ engine: body.engine, hint: body.hint, frames: [], seconds: info.duration ?? body.source.duration });+ prompt = written.prompt;+ negative ||= written.negative;+ by = written.by;+ }+ const { input } = planInput({ ...body, negative }, info, prompt, true);+ const plan = planRestore(input);+ let p: ReturnType<typeof createPipeline>;+ try {+ p = createPipeline(plan.steps);+ } catch (e) {+ throw new ShortsError((e as Error).message, 422);+ }+ return { final: p.byKey[plan.final], items: p.items, prompt, negative: input.negative, by };+}diff --git a/tests/restore-api.test.ts b/tests/restore-api.test.tsnew file mode 100644index 00000000..90373309--- /dev/null+++ b/tests/restore-api.test.ts@@ -0,0 +1,136 @@+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";++vi.setConfig({ testTimeout: 120_000 });++// /api/restore end to end in demo mode (no keys, no ComfyUI, no LLM): a run on either engine becomes one pipeline of+// ordinary generations the mock provider runs through; estimates with a fal key price the real LTX-2.3 route.+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-restore-"));+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 { saveFile } = await import("@/server/storage");+const { db } = await import("@/server/db");+const createRoute = await import("@/app/api/restore/route");+const estimateRoute = await import("@/app/api/restore/estimate/route");+const promptRoute = await import("@/app/api/restore/prompt/route");++const json = (body?: unknown) => new Request("http://x/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });++let clip = "";+beforeAll(() => {+ setSetting("demoMode", "auto");+ // A 12 s, 16 fps, 72×128 clip with a sound track: 192 frames.+ clip = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "reel.mp4" }).url;+});+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++async function settle(id: string, ms = 90_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, 300));+ }+}++const batchOf = (id: string) => {+ const b = (db().prepare("SELECT batch_id FROM generations WHERE id = ?").get(id) as { batch_id: string }).batch_id;+ return db().prepare("SELECT id, model_id, op, feature, engine FROM generations WHERE batch_id = ? ORDER BY created_at, id").all(b) as { id: string; model_id: string; op: string; feature: string; engine: string }[];+};++const src = { duration: 12, fps: 16, width: 72, height: 128, hasAudio: true };+const body = (over: Record<string, unknown> = {}) => ({ engine: "open", source: { url: clip, name: "reel.mp4", ...src }, prompt: "a harbour in the 1930s, natural colour", ...over });++describe("Restore: estimates", () => {+ it("the GPU is free: three windows, the canvas, the tiles, the gated download said while no HF token is set", async () => {+ const e = await (await estimateRoute.POST(json(body()))).json();+ expect(e).toMatchObject({ engine: "open", pieces: 3, costUsd: 0, canvas: { width: 1088, height: 1920 }, hfToken: false, dropped: 7 });+ expect(e.notes.join(" ")).toMatch(/LTX-2.5 22B distilled with tiled latent fusion/);+ expect(e.notes.join(" ")).toMatch(/gated on Hugging Face/);+ const four = await (await estimateRoute.POST(json(body({ refine: true })))).json();+ expect(four.refined).toEqual({ width: 2176, height: 3840 });+ });++ it("refuses Restore to 4K and deinterlacing in the cloud, and a clip over two minutes, in words", async () => {+ const r = await estimateRoute.POST(json(body({ engine: "cloud", refine: true })));+ expect(r.status).toBe(422);+ expect((await r.json()).error).toMatch(/Restore to 4K runs on your GPU/);+ expect((await (await estimateRoute.POST(json(body({ engine: "cloud", deinterlace: true })))).json()).error).toMatch(/Deinterlacing runs on your GPU/);+ expect((await (await estimateRoute.POST(json(body({ source: { url: clip, ...src, duration: 200 } })))).json()).error).toMatch(/up to 2 minutes/);+ });++ describe("with a fal key (estimates submit nothing)", () => {+ beforeAll(() => setSetting("falKey", "fal-test-key"));+ afterAll(() => setSetting("falKey", ""));++ it("prices each piece per megapixel of video at the tier's size for the clip's shape, then the joins and the sound", async () => {+ const e = await (await estimateRoute.POST(json(body({ engine: "cloud" })))).json();+ expect(e).toMatchObject({ engine: "cloud", demo: false, pieces: 2, resolution: "720p", canvas: { width: 704, height: 1280 } });+ // Two pieces of 97 and 89 frames at 704 × 1280: 87.4 + 80.2 MP → (88 + 81) × $0.001805, plus the helpers.+ expect(e.costUsd).toBeGreaterThanOrEqual((88 + 81) * 0.001805);+ expect(e.costUsd).toBeLessThan((88 + 81) * 0.001805 + 0.05);+ const hd = await (await estimateRoute.POST(json(body({ engine: "cloud", resolution: "1080p" })))).json();+ expect(hd.costUsd).toBeGreaterThan(e.costUsd * 1.8);+ });+ });++ it("Engine mode holds: paid APIs only refuses the GPU run and says it runs on your GPU", async () => {+ setSetting("engineMode", "cloud");+ try {+ const r = await estimateRoute.POST(json(body()));+ expect(r.status).toBe(422);+ expect((await r.json()).error).toMatch(/paid cloud APIs only .* runs on your GPU \(open source\)/);+ } finally {+ setSetting("engineMode", "both");+ }+ });+});++describe("Restore: the prompt writer", () => {+ it("offline (no Claude key, no Ollama): the template from your words, and the default negative", async () => {+ const r = await (await promptRoute.POST(json({ engine: "open", hint: "fishing boats in a harbour in the 1930s" }))).json();+ expect(r.by).toBe("offline");+ expect(r.prompt).toMatch(/^fishing boats in a harbour in 1930s, .*natural colour/);+ expect(r.negative).toMatch(/modern cars.*blocky compression/);+ });+});++describe("Restore: runs in demo mode", () => {+ it("GPU: the windows chained by their prefix, the packet-copy join and the sound back, all done", async () => {+ const res = await createRoute.POST(json(body({ seed: 3 })));+ expect(res.status).toBe(201);+ const out = await res.json();+ expect(out.by).toBe("you");+ const rows = batchOf(out.final.id);+ expect(rows.map((r) => [r.model_id, r.op])).toEqual([+ ["fuobe-restore", "restore-video"],+ ["fuobe-restore", "restore-video"],+ ["fuobe-restore", "restore-video"],+ ["oss-join-encoded", "concat"],+ ["oss-mux", "mux"],+ ]);+ expect(rows.filter((r) => r.feature === "restore")).toHaveLength(1);+ const done = await settle(out.final.id);+ expect(done.status).toBe("succeeded");+ const req = JSON.parse((db().prepare("SELECT request_json FROM generations WHERE id = ?").get(out.final.id) as { request_json: string }).request_json);+ expect(req.title).toMatch(/^Restored · A harbour in the 1930s · reel$/);+ });++ it("cloud: cut pieces, a hand-off frame, the join and the sound, written words kept", async () => {+ const res = await createRoute.POST(json(body({ engine: "cloud", prompt: "", hint: "a harbour" })));+ const out = await res.json();+ expect(out.by).toBe("offline");+ expect(out.prompt).toMatch(/natural colour/);+ const ops = batchOf(out.final.id).map((r) => r.op);+ expect(ops).toEqual(expect.arrayContaining(["trim", "frame", "restore-video", "concat", "mux"]));+ expect((await settle(out.final.id)).status).toBe("succeeded");+ });+});