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
ComfyUI provider: words for SAM 3.1, mattes to keep, depth colour maps
Claude25a78d27b008
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 5d58d128..2980f919 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -30,6 +30,7 @@ import {} from "@/lib/comfy";import { expandTimelineWorkflow, readTimeline } from "@/lib/av/timeline";import { guessKind } from "@/lib/catalog/payload";+import { CLICK_OPEN_PROBLEM, REMOVE_SCENE } from "@/lib/catalog/remove-object";import type { GenInput, MediaKind, Operation } from "@/lib/catalog/types";import { probeMedia, type MediaInfo } from "@/lib/media-probe";import { getSetting } from "../settings";@@ -571,6 +572,26 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,values[key] = def.replaceAll("{columns}", String(columns)).replaceAll("{rows}", String(rows)).replaceAll("{count}", String(columns * rows)).replaceAll("{language}", languageName(input.targetLanguage));}+ // Remove object: the words name what SAM 3.1 follows (maskPrompt) and the gap is filled with the scene without it+ // (params.extra.prompt, else a neutral default). No graph takes clicked points.+ if (ctx.op === "remove-object") {+ const words = input.prompt?.trim();+ if (b.maskPrompt) {+ if (!words && typeof extra.maskPrompt !== "string") throw new ProviderError(input.points?.length ? CLICK_OPEN_PROBLEM : "Say what to remove, e.g. “the coffee cup in her hand”");+ values.maskPrompt = words;+ }+ if (b.prompt) values.prompt = REMOVE_SCENE;+ }+ // Depth colour maps: Video Depth Anything has gray and inferno; the other graphs are grayscale only.+ if (ctx.op === "depth-video" && input.colormap) {+ const want = input.colormap.toLowerCase() === "grayscale" ? "gray" : input.colormap.toLowerCase();+ if (b.colormap && (want === "gray" || want === "inferno")) values.colormap = want;+ else if (want !== "gray") throw new ProviderError(b.colormap ? "The open engine's depth maps come in grayscale or inferno — turbo, magma and viridis are on the cloud" : "This depth model makes grayscale maps only — pick Video Depth Anything for inferno");+ }+ // Matte graphs save a cut-out and a black-and-white matte: params.extra.keepOutput ("cutout" | "matte") keeps one.+ const keepRole = typeof extra.keepOutput === "string" ? extra.keepOutput : undefined;+ delete extra.keepOutput;+if (b.filenamePrefix) values.filenamePrefix = `fuobe/${ctx.generationId}`;const cues = manifest.expand === "captions" ? captionCues(input, extra) : [];delete extra.cues;@@ -635,6 +656,8 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,}}if (input.loras?.length) wf = injectLoras(wf, input.loras);+ // The output not asked for isn't saved (nor encoded: ComfyUI runs only what an output node needs).+ if (keepRole && manifest.outputs.some((o) => o.role === keepRole)) for (const o of manifest.outputs) if (o.role && o.role !== keepRole) delete wf[o.node];const metaBatch = Object.values(wf).some((n) => n.class_type === "VHS_BatchManager");return {manifest,diff --git a/src/server/providers/mock.ts b/src/server/providers/mock.tsindex 2f547810..2c6278a2 100644--- a/src/server/providers/mock.ts+++ b/src/server/providers/mock.ts@@ -228,6 +228,12 @@ function demoOcr(brief: string): DemoOutput {return textOutput(lines.map((l) => l.text).join("\n"), null, { lines, demo: true });}+/** A black-and-white mask (white = the object) in the picture's shape. */+function demoMaskSvg(ar: string): string {+ const [w, h] = ar === "9:16" || ar === "3:4" || ar === "2:3" ? [360, 640] : ar === "1:1" ? [512, 512] : [640, 360];+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}"><rect width="100%" height="100%" fill="#000"/><ellipse cx="${w * 0.55}" cy="${h * 0.6}" rx="${w * 0.12}" ry="${h * 0.14}" fill="#fff"/></svg>`;+}+const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, Number.isFinite(n) ? n : lo));function demoOutputs(op: Operation | undefined, kind: MediaKind, prompt: string, ar: string, meta: Record<string, unknown>): DemoOutput[] {@@ -283,6 +289,11 @@ function demoOutputs(op: Operation | undefined, kind: MediaKind, prompt: string,case "audio-join":return [{ url: toDataUri(demoWav(clamp(3 * Number(meta.clips ?? 2), 4, 30), [330, 495]), "audio/wav"), kind: "audio", contentType: "audio/wav", meta: { demo: true } }];case "remove-object":+ return [+ { url: `sample:${sampleClip(ar)}`, kind: "video", contentType: "video/mp4", meta: { demo: true } },+ // The painted eraser also hands the window's last tracked mask to the next window.+ ...(meta.lastMask ? [{ url: svgUri(demoMaskSvg(ar)), kind: "image" as const, contentType: "image/svg+xml", meta: { role: "mask", demo: true } }] : []),+ ];case "video-swap":case "video-insert":case "keyframes":@@ -338,6 +349,8 @@ export const mockProvider: ProviderAdapter = {duration: input.duration,format: input.format,clips: input.audios?.length,+ // The painted eraser's second output: the window's last tracked mask (video-inpaint-wan-vace-painted).+ lastMask: route.provider === "comfyui" && route.endpoint === "video-inpaint-wan-vace-painted",// Workflows whose second output is the cut's first frame (video-segment-resample).firstFrame: route.provider === "comfyui" && route.endpoint === "video-segment-resample",// A stem split that also transcribes (ComfyUI's dub-prepare-separate-transcribe).diff --git a/tests/remove-object-comfy.test.ts b/tests/remove-object-comfy.test.tsnew file mode 100644index 00000000..93ec9d48--- /dev/null+++ b/tests/remove-object-comfy.test.ts@@ -0,0 +1,125 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, describe, expect, it } from "vitest";+import type { GenInput, Operation, OutputFile } from "@/lib/catalog/types";+import type { MediaInfo } from "@/lib/media-probe";+import { CLICK_OPEN_PROBLEM, REMOVE_SCENE } from "@/lib/catalog/remove-object";++// The comfyui provider driving the remove-object graphs (SAM 3.1 + VACE / VOID), the matte graphs' two outputs and+// the depth graphs' colour map and side-by-side switch, bound for real on the library graphs.+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-remove-object-comfy-"));+process.env.FUOBE_DATA_DIR = tmp;+process.env.COMFYUI_URL = "http://comfy.test:8188";+const { collectOutputs, getWorkflow, prepareWorkflow } = await import("@/server/providers/comfyui");+const { pickOutput } = await import("@/server/generations");+afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));++const clip: MediaInfo = { container: "mp4", hasVideo: true, hasAudio: true, duration: 8, videoDuration: 8, width: 1280, height: 720, fps: 30, frames: 240 };+const prepare = (id: string, input: Partial<GenInput>, op: Operation = "remove-object") =>+ prepareWorkflow(id, { video: "clip.mp4", ...input } as GenInput, { generationId: "g1", op, upload: async (_d, _t, name) => `up_${name}`, media: (n) => (n === "clip.mp4" ? clip : undefined) });+const at = (wf: Record<string, { inputs: Record<string, unknown> }>, node: string, input: string) => wf[node]?.inputs[input];++describe("remove-object graphs through the provider", () => {+ it("VACE: the words become SAM 3.1's maskPrompt, the gap gets the scene without it, the window in seconds", async () => {+ const { workflow: wf } = await prepare("video-inpaint-wan-vace", { prompt: "the coffee cup", startTime: 2.691667, endTime: 5.391667, seed: 3 });+ expect(at(wf, "8", "text")).toBe("the coffee cup");+ expect(at(wf, "16", "text")).toBe(REMOVE_SCENE);+ expect(at(wf, "85", "start_time")).toBe(2.691667);+ expect(at(wf, "82", "value")).toBeCloseTo(2.7, 6);+ expect(at(wf, "23", "seed")).toBe(3);+ // The work-size budget stays the graph's default; it renders in the clip's own shape.+ expect([at(wf, "87", "value"), at(wf, "88", "value")]).toEqual([832, 480]);+ });++ it("a described scene (params.extra.prompt) fills the gap instead", async () => {+ const { workflow: wf } = await prepare("video-inpaint-wan-vace", { prompt: "the man", extra: { prompt: "An empty beach at sunset" } });+ expect(at(wf, "8", "text")).toBe("the man");+ expect(at(wf, "16", "text")).toBe("An empty beach at sunset");+ });++ it("refuses to run without words, and says clicking is cloud-only when points were sent", async () => {+ await expect(prepare("video-inpaint-wan-vace", { prompt: "" })).rejects.toThrow(/Say what to remove/);+ await expect(prepare("video-erase-void", { points: [{ x: 1, y: 2 }] })).rejects.toThrow(CLICK_OPEN_PROBLEM);+ });++ it("painted VACE: the first-frame mask is uploaded into its loader, the scene prompt is the default", async () => {+ const { workflow: wf, manifest } = await prepare("video-inpaint-wan-vace-painted", { mask: "mask.png", startTime: 0, endTime: 2.7 });+ expect(at(wf, "70", "image")).toBe("mask.png");+ expect(at(wf, "16", "text")).toBe(REMOVE_SCENE);+ // Its second output is the last frame's tracked mask, which starts the next window.+ expect(manifest.outputs).toEqual([+ { node: "38", kind: "video" },+ { node: "77", kind: "image", role: "mask" },+ ]);+ expect(at(wf, "77", "filename_prefix")).toBe("fuobe/g1");+ expect(wf["76"].inputs).toMatchObject({ image: ["74", 0], batch_index: ["75", 1], length: 1 });+ expect(wf["74"].inputs).toEqual({ mask: ["10", 0] });+ });++ it("VOID: maskPrompt, the scene, and pass 2 can be skipped", async () => {+ const { workflow: wf } = await prepare("video-erase-void", { prompt: "the skateboarder", extra: { skipPass2: true } });+ expect(at(wf, "8", "text")).toBe("the skateboarder");+ expect(at(wf, "16", "text")).toBe(REMOVE_SCENE);+ expect(at(wf, "49", "value")).toBe(true);+ });++ it("a painted window's outputs: the video, and its last mask as meta.role 'mask', which a mask chain slot picks", () => {+ const { manifest } = getWorkflow("video-inpaint-wan-vace-painted");+ const outs = collectOutputs(+ {+ status: { status_str: "success", completed: true },+ outputs: {+ "38": { images: [{ filename: "w_00001_.mp4", subfolder: "fuobe", type: "output" }], animated: [true] },+ "77": { images: [{ filename: "w_00001_.png", subfolder: "fuobe", type: "output" }] },+ },+ },+ manifest,+ );+ expect(outs.map((o) => [o.kind, o.meta?.role])).toEqual([+ ["video", undefined],+ ["image", "mask"],+ ]);+ const files = outs.map((o) => ({ url: o.url, kind: o.kind, meta: o.meta }) as OutputFile);+ expect(pickOutput(files, { slot: "mask" })?.url).toMatch(/w_00001_\.png/);+ expect(pickOutput(files, { slot: "videos" })?.url).toMatch(/w_00001_\.mp4/);+ // A SAM 3.1 track (cloud) is a mask video: the first video.+ expect(pickOutput([{ url: "/m.mp4", kind: "video" }, { url: "/b.zip", kind: "image" }], { slot: "mask" })?.url).toBe("/m.mp4");+ });+});++describe("matte graphs: Cutout video or Alpha mask", () => {+ it("keeps only the asked-for output (the other save node is dropped, so it isn't encoded)", async () => {+ const both = await prepare("video-bg-remove-sam3", { prompt: "the dog" }, "bg-remove-video");+ expect(Object.keys(both.workflow)).toEqual(expect.arrayContaining(["9", "12"]));+ expect(both.manifest.outputs.map((o) => o.role)).toEqual(["cutout", "matte"]);+ const matte = await prepare("video-bg-remove-sam3", { prompt: "the dog", extra: { keepOutput: "matte" } }, "bg-remove-video");+ expect(matte.workflow["9"]).toBeUndefined();+ expect(matte.workflow["12"].class_type).toBe("SaveVideo");+ expect(at(matte.workflow, "4", "text")).toBe("the dog");+ const cut = await prepare("video-bg-remove-birefnet", { extra: { keepOutput: "cutout" } }, "bg-remove-video");+ expect(cut.workflow["10"]).toBeUndefined();+ expect(cut.workflow["7"].class_type).toBe("SaveWEBM");+ // keepOutput is not a graph input.+ expect(JSON.stringify(cut.workflow)).not.toContain("keepOutput");+ });+});++describe("depth graphs: colour map and side by side", () => {+ it("Video Depth Anything takes gray or inferno, and puts the original next to the depth on request", async () => {+ const gray = await prepare("video-depth-vda-small", { colormap: "grayscale" }, "depth-video");+ expect(at(gray.workflow, "5", "colormap")).toBe("gray");+ expect(at(gray.workflow, "9", "value")).toBe(false);+ const inferno = await prepare("video-depth-vda-small", { colormap: "inferno", extra: { sideBySide: true } }, "depth-video");+ expect(at(inferno.workflow, "5", "colormap")).toBe("inferno");+ expect(at(inferno.workflow, "9", "value")).toBe(true);+ expect(inferno.workflow["10"].inputs).toEqual({ switch: ["9", 0], on_true: ["8", 0], on_false: ["5", 0] });+ await expect(prepare("video-depth-vda-small", { colormap: "turbo" }, "depth-video")).rejects.toThrow(/grayscale or inferno/);+ });++ it("Depth Anything 3 is grayscale only (and can go side by side too)", async () => {+ await expect(prepare("video-depth-da3", { colormap: "inferno" }, "depth-video")).rejects.toThrow(/grayscale maps only/);+ const sbs = await prepare("video-depth-da3", { colormap: "grayscale", extra: { sideBySide: true } }, "depth-video");+ expect(at(sbs.workflow, "9", "value")).toBe(true);+ });+});