Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Remove object: server and API

Claude4392910f0482
diff --git a/src/app/api/remove-object/estimate/route.ts b/src/app/api/remove-object/estimate/route.ts
new file mode 100644
index 00000000..57e638d1
--- /dev/null
+++ b/src/app/api/remove-object/estimate/route.ts
@@ -0,0 +1,10 @@
+import { estimateRemoval, RemovalEstimateSchema } from "@/server/remove-object";
+import { body, handle } from "@/server/shorts-schemas";
+
+/** The price, the pieces and the notes for the current settings, before anything runs. */
+export async function POST(request: Request) {
+ return handle(async () => {
+ const input = await body(request, RemovalEstimateSchema, "Add a clip and pick how to point at what goes");
+ return Response.json(await estimateRemoval(input));
+ });
+}
diff --git a/src/app/api/remove-object/preview/route.ts b/src/app/api/remove-object/preview/route.ts
new file mode 100644
index 00000000..d85dc9b0
--- /dev/null
+++ b/src/app/api/remove-object/preview/route.ts
@@ -0,0 +1,11 @@
+import { createRemovalPreview, RemovalBodySchema } from "@/server/remove-object";
+import { body, handle, once } from "@/server/shorts-schemas";
+
+/** A mask preview of the first seconds: what the engine would remove (SAM 3.1). */
+export async function POST(request: Request) {
+ return handle(async () => {
+ const input = await body(request, RemovalBodySchema, "Add a clip and say, click or paint what to remove");
+ const preview = await once("remove-object-preview", input.requestId, () => createRemovalPreview(input));
+ return Response.json(preview, { status: 201 });
+ });
+}
diff --git a/src/app/api/remove-object/route.ts b/src/app/api/remove-object/route.ts
new file mode 100644
index 00000000..d172ad22
--- /dev/null
+++ b/src/app/api/remove-object/route.ts
@@ -0,0 +1,12 @@
+import { createRemoval, RemovalBodySchema } from "@/server/remove-object";
+import { body, handle, once } from "@/server/shorts-schemas";
+
+/** Remove an object from a clip: the pieces or windows are erased, joined, and the clip's sound put back. */
+export async function POST(request: Request) {
+ return handle(async () => {
+ const input = await body(request, RemovalBodySchema, "Add a clip and say, click or paint what to remove");
+ // A repeated requestId (a second click on Remove) gets the run the first one started.
+ const { final, items } = await once("remove-object", input.requestId, () => createRemoval(input));
+ return Response.json({ final, items }, { status: 201 });
+ });
+}
diff --git a/src/server/remove-object.ts b/src/server/remove-object.ts
new file mode 100644
index 00000000..46eb8422
--- /dev/null
+++ b/src/server/remove-object.ts
@@ -0,0 +1,277 @@
+import "server-only";
+import { z } from "zod";
+import { getModel } from "@/lib/catalog";
+import {
+ chooseEraser,
+ paintedPoints,
+ pieceSeconds,
+ planMaskPreview,
+ planRemoval,
+ rangeProblem,
+ REMOVE,
+ removalProblem,
+ removalTitle,
+ scalePoints,
+ wholeClip,
+ type Eraser,
+ type RemovalPlanInput,
+ type RemoveMode,
+ type RemoveRange,
+ type RemoveSource,
+} from "@/lib/catalog/remove-object";
+import type { PlanStep } from "@/lib/catalog/shorts";
+import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";
+import { createPipeline } from "./chains";
+import { previewChained } from "./generations";
+import { decodePng } from "./png";
+import { engineMode } from "./settings";
+import { probeSource, ShortsError } from "./shorts";
+import { readRef } from "./storage";
+
+/**
+ * Video tools → Remove object: plans, prices and starts a removal (src/lib/catalog/remove-object.ts) as one
+ * pipeline of ordinary generations: feature "remove-object" for the finished video, "remove-object-step" for
+ * the cuts, tracks, pieces and joins, "remove-object-preview" for mask previews. No table of its own: the
+ * page's history is a feed.
+ */
+
+export { ShortsError as RemovalError };
+
+export interface RemovalBody {
+ engine: Engine;
+ mode: RemoveMode;
+ /** The eraser picked (defaults per engine and mode). */
+ modelId?: string;
+ /** "Shadows and reflections too": VOID. */
+ effects?: boolean;
+ /** Type it: what to remove. */
+ prompt?: string;
+ /** Click it: points on the first frame of the range, in `frame` pixels. */
+ points?: PixelPoint[];
+ /** The picture the points or the paint were made on (the first frame the browser showed). */
+ frame?: { width: number; height: number };
+ /** Paint it: the mask of that frame (white = remove), an uploaded PNG. */
+ mask?: string;
+ source: { url: string; name?: string; duration?: number; fps?: number; width?: number; height?: number; hasAudio?: boolean };
+ range?: RemoveRange;
+ seed?: number;
+}
+
+const fileUrl = z.string().startsWith("/api/files/").max(500);
+const seconds = z.number().finite().min(0).max(3600);
+const point = z.object({ x: z.number().finite().min(0).max(20000), y: z.number().finite().min(0).max(20000), label: z.enum(["positive", "negative"]).optional() });
+
+/** The body of /api/remove-object (and /estimate, /preview). */
+export const RemovalBodySchema = z.object({
+ engine: z.enum(["cloud", "open"]),
+ mode: z.enum(["type", "click", "paint"]),
+ modelId: z.string().max(80).optional(),
+ effects: z.boolean().optional(),
+ prompt: z.string().max(2500).optional(),
+ points: z.array(point).max(REMOVE.maxPoints).optional(),
+ frame: z.object({ width: z.number().int().positive().max(20000), height: z.number().int().positive().max(20000) }).optional(),
+ mask: fileUrl.optional(),
+ 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(),
+ }),
+ range: z.object({ start: seconds, end: seconds }).optional(),
+ seed: z.number().int().min(0).max(2 ** 48).optional(),
+ /** A client nonce for one submit: a repeat gets the first answer (see once()). */
+ requestId: z.string().trim().min(8).max(64).optional(),
+});
+
+/** The estimate is asked for before the upload finishes: any URL stands in. */
+export const RemovalEstimateSchema = RemovalBodySchema.extend({
+ source: RemovalBodySchema.shape.source.extend({ url: z.string().max(500).default("/api/files/placeholder.mp4") }),
+ mask: z.string().max(500).optional(),
+});
+
+/**
+ * Kling O3 edit is priced per generated second ($0.168/s, paid-model-apis-4.md §3), but the catalog model has no
+ * price of its own (its text- and image-to-video routes cost less): the removal estimate uses the edit price.
+ */
+const EDIT_USD_PER_SECOND: Record<string, number> = { "kling-o3": 0.168 };
+
+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 cloud models only (Settings → Engine mode)", 422);
+ }
+};
+
+/** Points a SAM 3.1 track starts from: the deepest points of the paint, in the clip's pixels. */
+async function pointsFromPaint(mask: string, size: { width?: number; height?: number }): Promise<PixelPoint[]> {
+ let png: ReturnType<typeof decodePng>;
+ try {
+ png = decodePng((await readRef(mask)).data);
+ } catch {
+ throw new ShortsError("Couldn't read the painted mask — paint it again", 400);
+ }
+ const on = new Uint8Array(png.width * png.height);
+ for (let i = 0; i < on.length; i++) on[i] = png.data[i * 4] > 127 ? 1 : 0;
+ const found = paintedPoints(on, png.width, png.height);
+ if (!found.length) throw new ShortsError("Paint over what to remove first");
+ return size.width && size.height ? scalePoints(found, png, { width: size.width, height: size.height }) : found;
+}
+
+interface Planned {
+ input: RemovalPlanInput;
+ eraser: Eraser;
+ notes: string[];
+}
+
+async function planInput(body: RemovalBody, opts: { probe: boolean; preview?: boolean }): Promise<Planned> {
+ mustMatchMode(body.engine);
+ const picked = chooseEraser({ engine: body.engine, mode: body.mode, effects: body.effects, modelId: body.modelId });
+ if ("problem" in picked) throw new ShortsError(picked.problem, 422);
+ const eraser = picked.eraser;
+ // The header's facts win over what the browser read (the estimate runs before the upload is read).
+ const info = opts.probe ? await probeSource(body.source.url) : {};
+ const source: RemoveSource = {
+ 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 erasing was paid for).
+ hasAudio: opts.probe ? (info.hasAudio ?? false) : (body.source.hasAudio ?? false),
+ };
+ const range = body.range ?? (source.duration ? { start: 0, end: source.duration } : null);
+ if (!range) throw new ShortsError("Reading the clip… try again in a moment");
+ // A mask preview runs on SAM 3.1 alone: the eraser's own limits don't apply to it.
+ const problem = opts.preview ? rangeProblem(source, range) : removalProblem(eraser, source, range);
+ if (problem) throw new ShortsError(problem, 422);
+
+ let points: PixelPoint[] | undefined;
+ if (body.mode === "type" && !eraser.everyone && !body.prompt?.trim()) throw new ShortsError("Say what to remove, e.g. “the coffee cup in her hand”");
+ if (body.mode === "click") {
+ const given = (body.points ?? []).slice(0, REMOVE.maxPoints);
+ if (!given.some((p) => p.label !== "negative")) throw new ShortsError("Click what to remove on the first frame");
+ points = body.frame && source.width && source.height ? scalePoints(given, body.frame, { width: source.width, height: source.height }) : given;
+ }
+ if (body.mode === "paint") {
+ if (!body.mask) throw new ShortsError("Paint over what to remove first");
+ // The cloud's tracker takes points, not paint; the open graph reads the mask itself.
+ if (eraser.engine === "cloud") points = opts.probe ? await pointsFromPaint(body.mask, source) : [{ x: 1, y: 1, label: "positive" }];
+ }
+
+ const notes: string[] = [];
+ const len = range.end - range.start;
+ const model = getModel(eraser.id);
+ if (eraser.window) {
+ const fps = source.fps ?? 30;
+ const per = eraser.window.cap / fps;
+ if (len > per + 0.01) {
+ notes.push(`${model?.name ?? eraser.label} works on ${eraser.window.cap} frames at a time (${per.toFixed(1)} s of this clip): the clip runs as ${Math.ceil((len * fps) / eraser.window.cap)} windows, joined with its own sound. Seams between windows aren't tested on a GPU yet`);
+ if (eraser.modes.includes("paint")) notes.push("SAM 3.1 hands what you painted on from window to window, so the windows run one after another");
+ }
+ notes.push(eraser.effects ? "VOID needs a 24–40 GB GPU (unverified). Its CogVideoX base is licensed for commercial use only after registering, up to 1 million visits a month" : "Wan 2.1 VACE 14B needs a 24 GB GPU · Apache-2.0 (SAM 3.1: Meta's SAM License)");
+ } else {
+ const max = pieceSeconds(eraser, source.fps);
+ if (len > max + 0.01) notes.push(`${model?.name ?? eraser.label} takes ${max < 5 ? "clips under 5 s" : `up to ${Math.floor(max)} s`}: the clip is cut into ${Math.ceil(len / max - 1e-9)} pieces, erased one by one and joined, with its own sound put back. Seams between pieces aren't tested yet`);
+ if (body.mode !== "type" && (body.mode === "paint" || len > max + 0.01)) notes.push("SAM 3.1 first follows what you " + (body.mode === "paint" ? "painted" : "clicked") + " through the whole selection; Bria then erases that mask");
+ if (eraser.everyone) notes.push("LTX Clean Plate removes every person in the shot — it doesn't take a target");
+ }
+ if (!wholeClip(range, source.duration)) notes.push("Only the selected part comes out (the rest of the clip isn't kept)");
+
+ const name = (body.source.name ?? "").replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, 40);
+ const title = removalTitle({ mode: body.mode, prompt: body.prompt, everyone: eraser.everyone });
+ return {
+ eraser,
+ notes,
+ input: {
+ engine: body.engine,
+ mode: body.mode,
+ eraser,
+ title: name ? `${title} · ${name}` : title,
+ source,
+ range,
+ prompt: body.prompt?.trim() || undefined,
+ points,
+ mask: body.mode === "paint" && eraser.engine === "open" ? body.mask : undefined,
+ ...(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;
+ const edit = EDIT_USD_PER_SECOND[s.request.modelId];
+ const usd = p.costUsd ?? (edit !== undefined ? edit * (s.request.params?.duration ?? 0) : null);
+ cost = cost === null || usd === null ? null : cost + usd;
+ }
+ return { costUsd: cost === null ? null : Math.round(cost * 10000) / 10000, demo };
+}
+
+export interface RemovalEstimate {
+ costUsd: number | null;
+ demo: boolean;
+ /** The eraser that runs (the default for the mode, or the one picked). */
+ modelId: string;
+ modelName: string;
+ /** Pieces (cloud) or windows (open) the clip is erased in. */
+ pieces: number;
+ seconds: number;
+ steps: number;
+ notes: string[];
+ /** The mask preview's price, or null when this engine and mode have none. */
+ previewUsd: number | null;
+}
+
+export async function estimateRemoval(body: RemovalBody): Promise<RemovalEstimate> {
+ const { input, eraser, notes } = await planInput(body, { probe: false });
+ const plan = planRemoval(input);
+ const preview = planMaskPreview({ ...input, prompt: input.prompt, points: input.points });
+ return {
+ ...price(plan.steps),
+ modelId: eraser.id,
+ modelName: getModel(eraser.id)?.name ?? eraser.label,
+ pieces: plan.pieces.length,
+ seconds: Math.round((input.range.end - input.range.start) * 100) / 100,
+ steps: plan.steps.length,
+ notes,
+ previewUsd: preview ? price(preview).costUsd : null,
+ };
+}
+
+function run(steps: PlanStep[]) {
+ try {
+ return createPipeline(steps);
+ } catch (e) {
+ throw new ShortsError((e as Error).message, 422);
+ }
+}
+
+/** Start the removal; returns the finished video's generation (the other steps wait for each other). */
+export async function createRemoval(body: RemovalBody): Promise<{ final: Generation; items: Generation[] }> {
+ const { input } = await planInput(body, { probe: true });
+ const plan = planRemoval(input);
+ const p = run(plan.steps);
+ return { final: p.byKey[plan.final], items: p.items };
+}
+
+/** A mask preview of the first seconds: what the engine would remove. */
+export async function createRemovalPreview(body: RemovalBody): Promise<Generation> {
+ const { input } = await planInput(body, { probe: true, preview: true });
+ const steps = planMaskPreview(input);
+ if (!steps) throw new ShortsError(input.engine === "open" ? "The open engine previews masks of what you type — your paint is the preview here" : "Name, click or paint what to remove first", 422);
+ return run(steps).byKey.preview;
+}
diff --git a/tests/remove-object-api.test.ts b/tests/remove-object-api.test.ts
new file mode 100644
index 00000000..44254aff
--- /dev/null
+++ b/tests/remove-object-api.test.ts
@@ -0,0 +1,222 @@
+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/remove-object end to end in demo mode (no keys, no ComfyUI): every way of pointing on both engines
+// becomes one pipeline of ordinary generations, which the mock provider runs through.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-remove-object-"));
+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 { encodePng } = await import("@/server/png");
+const { db } = await import("@/server/db");
+const createRoute = await import("@/app/api/remove-object/route");
+const estimateRoute = await import("@/app/api/remove-object/estimate/route");
+const previewRoute = await import("@/app/api/remove-object/preview/route");
+const { CLICK_OPEN_PROBLEM, REMOVE } = await import("@/lib/catalog/remove-object");
+
+const json = (body?: unknown) => new Request("http://x/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+
+let clip = "";
+let mask = "";
+beforeAll(() => {
+ setSetting("demoMode", "auto");
+ // A 12 s, 16 fps, 72×128 clip with a sound track.
+ clip = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "skate.mp4" }).url;
+ // The first frame painted where the skateboard is (white = remove).
+ const data = Buffer.alloc(72 * 128 * 4);
+ for (let y = 0; y < 128; y++)
+ for (let x = 0; x < 72; x++) {
+ const at = (y * 72 + x) * 4;
+ data.fill(x >= 20 && x < 50 && y >= 80 && y < 110 ? 255 : 0, at, at + 3);
+ data[at + 3] = 255;
+ }
+ mask = saveFile({ data: encodePng({ width: 72, height: 128, data }), contentType: "image/png", source: "upload", name: "mask.png" }).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));
+ }
+}
+
+/** Wait until a step has been handed its chained inputs (it left "Waits for the earlier steps"). */
+async function launched(id: string, ms = 60_000): Promise<Generation> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id)!;
+ if (g.status === "failed" || g.status === "canceled") throw new Error(`${g.id} ${g.status}: ${g.error}`);
+ if (!/Waits for/.test(g.message ?? "")) 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, depends_on, request_json FROM generations WHERE batch_id = ? ORDER BY created_at, id").all(b) as {
+ id: string;
+ model_id: string;
+ op: string;
+ feature: string;
+ depends_on: string | null;
+ request_json: string;
+ }[];
+};
+
+const body = (over: Record<string, unknown> = {}) => ({ engine: "cloud", mode: "type", prompt: "the skateboard", source: { url: clip, name: "skate.mp4" }, ...over });
+
+describe("Remove object: estimates", () => {
+ // Estimates submit nothing: a fal key makes the routes real, so the prices are the providers' own.
+ beforeAll(() => setSetting("falKey", "fal-test-key"));
+ afterAll(() => setSetting("falKey", ""));
+
+ it("prices the pieces before anything runs, with what happens in words", async () => {
+ const res = await estimateRoute.POST(json(body({ modelId: "bria-video-erase", source: { url: clip, duration: 12, fps: 16, width: 72, height: 128, hasAudio: true } })));
+ expect(res.status).toBe(200);
+ const e = await res.json();
+ expect(e).toMatchObject({ modelId: "bria-video-erase", modelName: "Bria Video Eraser", pieces: 3, seconds: 12, demo: false });
+ // 3 cuts + 3 erasures + a join + the sound.
+ expect(e.steps).toBe(8);
+ // Bria at $0.14/s for 12 s, plus the cuts, join and mux.
+ expect(e.costUsd).toBeGreaterThanOrEqual(1.68);
+ expect(e.costUsd).toBeLessThan(1.7);
+ expect(e.notes.join(" ")).toMatch(/cut into 3 pieces/);
+ expect(e.previewUsd).toBeGreaterThan(0);
+ });
+
+ it("prices Kling O3 edit at its edit price, and refuses clips it can't take", async () => {
+ const big = { url: clip, duration: 10, fps: 24, width: 1280, height: 720, hasAudio: true };
+ const e = await (await estimateRoute.POST(json(body({ source: big })))).json();
+ expect(e).toMatchObject({ modelId: "kling-o3", pieces: 1 });
+ expect(e.costUsd).toBeCloseTo(1.68, 3);
+ const small = await estimateRoute.POST(json(body({ source: { ...big, width: 72, height: 128 } })));
+ expect(small.status).toBe(422);
+ expect((await small.json()).error).toMatch(/720 px on each side/);
+ });
+
+ it("open engine: free, in windows, with the GPU and licence said", async () => {
+ const e = await (await estimateRoute.POST(json(body({ engine: "open", source: { url: clip, duration: 12, fps: 16, width: 72, height: 128, hasAudio: true } })))).json();
+ expect(e).toMatchObject({ modelId: "oss-vace-remove", pieces: 3, costUsd: 0 });
+ expect(e.notes.join(" ")).toMatch(/81 frames at a time/);
+ expect(e.notes.join(" ")).toMatch(/24 GB GPU/);
+ const effects = await (await estimateRoute.POST(json(body({ engine: "open", effects: true, source: { url: clip, duration: 12, fps: 16 } })))).json();
+ expect(effects.modelId).toBe("oss-void-remove");
+ expect(effects.notes.join(" ")).toMatch(/CogVideoX/);
+ });
+
+ it("says what's missing", async () => {
+ const click = await estimateRoute.POST(json(body({ engine: "open", mode: "click", source: { url: clip, duration: 12, fps: 16 } })));
+ expect(click.status).toBe(422);
+ expect((await click.json()).error).toBe(CLICK_OPEN_PROBLEM);
+ const words = await estimateRoute.POST(json(body({ prompt: " ", modelId: "bria-video-erase", source: { url: clip, duration: 12, fps: 16 } })));
+ expect((await words.json()).error).toMatch(/Say what to remove/);
+ const points = await estimateRoute.POST(json(body({ mode: "click", points: [{ x: 3, y: 3, label: "negative" }], source: { url: clip, duration: 12, fps: 16 } })));
+ expect((await points.json()).error).toMatch(/Click what to remove/);
+ setSetting("engineMode", "open");
+ const cloud = await estimateRoute.POST(json(body({ source: { url: clip, duration: 12, fps: 16 } })));
+ expect((await cloud.json()).error).toMatch(/open-source models only/);
+ setSetting("engineMode", "both");
+ });
+});
+
+describe("Remove object: runs", () => {
+ it("Type it on Bria: a 12 s clip is cut, erased and joined, and the clip's sound put back", async () => {
+ const res = await createRoute.POST(json(body({ modelId: "bria-video-erase", requestId: "type-bria-0001" })));
+ expect(res.status).toBe(201);
+ const { final, items } = (await res.json()) as { final: Generation; items: Generation[] };
+ expect(items).toHaveLength(8);
+ expect(final).toMatchObject({ feature: REMOVE.feature, op: "mux", modelId: "merge-audio-video" });
+ expect(final.request.title).toMatch(/^Remove · the skateboard · skate/);
+ expect(items.filter((g) => g.feature === REMOVE.stepFeature)).toHaveLength(7);
+ // A repeated request id gets the first run, not a second one.
+ const again = (await (await createRoute.POST(json(body({ modelId: "bria-video-erase", requestId: "type-bria-0001" })))).json()) as { final: Generation };
+ expect(again.final.id).toBe(final.id);
+ });
+
+ it("Click it, longer than 5 s: SAM 3.1 tracks the clicks (scaled to the clip), Bria erases each piece's mask", async () => {
+ const points = [{ x: 72, y: 190, label: "positive" }];
+ const res = await createRoute.POST(json(body({ mode: "click", prompt: undefined, points, frame: { width: 144, height: 256 } })));
+ const { final } = (await res.json()) as { final: Generation };
+ const rows = batchOf(final.id);
+ const track = rows.find((r) => r.model_id === "sam-3-1-video-mask")!;
+ expect(JSON.parse(track.request_json).params.points).toEqual([{ x: 36, y: 95, label: "positive" }]);
+ const erasers = rows.filter((r) => r.op === "remove-object");
+ expect(erasers.map((r) => r.model_id)).toEqual(["bria-video-erase-mask", "bria-video-erase-mask", "bria-video-erase-mask"]);
+ for (const r of erasers) expect(JSON.parse(r.request_json).chain).toEqual([{ slot: "video" }, { slot: "mask" }]);
+ // The cut track and the cut clip reach each eraser (cut ∥ track, then the track's cut).
+ for (const r of erasers) {
+ const g = await launched(r.id);
+ expect(g.request.inputs?.mask).toMatch(/^\/api\/files\//);
+ expect(g.request.inputs?.video).toMatch(/^\/api\/files\//);
+ expect(g.request.inputs?.mask).not.toBe(g.request.inputs?.video);
+ }
+ });
+
+ it("Paint it on the cloud: points found in the paint start the SAM 3.1 track", async () => {
+ const res = await createRoute.POST(json(body({ mode: "paint", prompt: undefined, mask, source: { url: clip }, range: { start: 0, end: 4 } })));
+ const { final } = (await res.json()) as { final: Generation };
+ const rows = batchOf(final.id);
+ expect(rows.map((r) => r.model_id).sort()).toEqual(["bria-video-erase-mask", "sam-3-1-video-mask", "trim-video"]);
+ const p = JSON.parse(rows.find((r) => r.model_id === "sam-3-1-video-mask")!.request_json).params.points as { x: number; y: number }[];
+ expect(p.length).toBeGreaterThan(0);
+ for (const q of p) {
+ expect(q.x).toBeGreaterThanOrEqual(20);
+ expect(q.x).toBeLessThan(50);
+ expect(q.y).toBeGreaterThanOrEqual(80);
+ expect(q.y).toBeLessThan(110);
+ }
+ });
+
+ it("open engine, Paint it: windows chained by the tracked mask, joined, the sound put back", async () => {
+ const res = await createRoute.POST(json(body({ engine: "open", mode: "paint", prompt: undefined, mask })));
+ expect(res.status).toBe(201);
+ const { final } = (await res.json()) as { final: Generation };
+ const rows = batchOf(final.id);
+ const windows = rows.filter((r) => r.op === "remove-object").sort((a, b) => JSON.parse(a.request_json).step.index - JSON.parse(b.request_json).step.index);
+ expect(windows).toHaveLength(3);
+ expect(JSON.parse(windows[0].request_json).inputs.mask).toBe(mask);
+ expect(windows[1].depends_on).toBe(windows[0].id);
+ expect(JSON.parse(windows[2].request_json).chain).toEqual([{ slot: "mask" }]);
+ expect(rows.map((r) => r.model_id)).toEqual(expect.arrayContaining(["oss-join-clips", "oss-mux"]));
+ // The first window's last tracked frame starts the second one.
+ const second = await launched(windows[1].id);
+ expect(second.request.inputs?.mask).toMatch(/^\/api\/files\//);
+ expect(second.request.inputs?.mask).not.toBe(mask);
+ // …the mask image the window saved (meta.role "mask"), not its video.
+ expect(second.request.inputs?.mask).toMatch(/\.svg$/);
+ });
+
+ it("open engine, Type it, one window: the eraser's own result is the video", async () => {
+ const res = await createRoute.POST(json(body({ engine: "open", range: { start: 0, end: 3 } })));
+ const { final, items } = (await res.json()) as { final: Generation; items: Generation[] };
+ expect(items).toHaveLength(1);
+ expect(final).toMatchObject({ modelId: "oss-vace-remove", feature: REMOVE.feature });
+ // 3 s at 16 fps is 48 frames: the window is the largest 4n+1, 45 frames (2.8125 s).
+ expect(final.request.params).toMatchObject({ startTime: 0, endTime: 2.8125 });
+ });
+
+ it("mask preview: SAM 3.1 on the first 2 s (cloud), the SAM 3 cut-out (open)", async () => {
+ const cloud = (await (await previewRoute.POST(json(body({ requestId: "preview-cloud-1" })))).json()) as Generation;
+ expect(cloud).toMatchObject({ feature: REMOVE.previewFeature, modelId: "sam-3-1-video-mask", op: "bg-remove-video", prompt: "the skateboard" });
+ expect(cloud.request.params?.duration).toBe(2);
+ const open = (await (await previewRoute.POST(json(body({ engine: "open" })))).json()) as Generation;
+ expect(open.modelId).toBe("oss-video-matte-sam3");
+ const none = await previewRoute.POST(json(body({ engine: "open", mode: "paint", mask })));
+ expect(none.status).toBe(422);
+ expect((await settle(cloud.id)).status).toBe("succeeded");
+ });
+});