One-click character swap for videos: an open-source, local Higgsfield Genjutsu alternative built on ComfyUI and MiniMax H3, with FLUX.3 Klein relighting.
Make Simple mode single-person and add a mask check
D3vozab17d1b66425
diff --git a/README.md b/README.mdindex 7de0e25..73c7b74 100644--- a/README.md+++ b/README.md@@ -1,13 +1,13 @@# Openjutsu-An open-source, Genjutsu-style character swap for video. Drop a video and 1–4 character photos, press **Generate**, and every person in the video is replaced by your characters. The camera, cuts, motion and soundtrack stay. Everything runs on open weights on your own GPU: MiniMax H3 for the video, SAM 3.1 to track people, and Qwen3-VL 8B to describe the pictures and shots.+An open-source, Genjutsu-style character swap for video. Drop a video and a character photo, press **Generate**, and the main person in the video is replaced by your character. The camera, cuts, motion and soundtrack stay. Everything runs on open weights on your own GPU: MiniMax H3 for the video, SAM 3.1 to track people, and Qwen3-VL 8B to describe the pictures and shots.The app is a small Next.js front end over a ComfyUI workflow. It uses [`@comfyorg/sdk`](https://www.npmjs.com/package/@comfyorg/sdk), following Comfy's [comfy-reshoot](https://github.com/Comfy-Org/comfy-reshoot) reference app.## Modes-- **Simple motion transfer**: available. Runs `workflows/simple.api.json`.-- **Advanced motion transfer** (pick who becomes who with role-coloured tracks) and **Object swap**: coming soon, as separate workflow files.+- **Simple motion transfer**: available. One character replaces the main person (the one who fills the most of the frame). Runs `workflows/simple.api.json`, exported from `H3 One-Click Single Swap (DMAD 6 step).json`.+- **Advanced motion transfer** (several people, pick who becomes who) and **Object swap**: coming soon, as separate workflow files.## Requirements@@ -68,22 +68,26 @@ A 6 s clip at 480p takes about 6–13 minutes on a 4060 Ti, most of it in H3 sam## Tips-- One photo per person in the video. Every person SAM finds is regenerated.-- **Replaces who?** names a role or position (`the singer`, `the drummer`, `the person on the left`), never clothes: clothing words leak into the result. Leave all of them blank to match pictures to people by screen time.-- **Hat fix** also masks hats, so they are replaced too (about 45 s more per clip).+- Only the main person is regenerated; anyone else in the video stays as they are.+- **Who do they replace?** names the person for the prompt by role (`the singer`), never by clothes: clothing words leak into the result. Leave it blank and the describer names them.+- **Hat fix** also masks the hat, so it is replaced too (about 45 s more per clip).+- **Check mask** runs only SAM and the mask (about a minute per 3 s of video) and shows a preview you can scrub frame by frame: cyan is the area H3 regenerates, orange the tracked person, and on the right the grey mannequin H3 copies the motion from. Anything outside the cyan area stays as it is.- Change the **seed** (under Advanced) for a new take. Running the same inputs again resumes from the last finished clip.## How it works-`workflows/simple.api.json` is one API export of the ComfyUI workflow with all four picture branches and the hat fix enabled. For each request, `lib/simple.ts`:+Each clip, SAM 3.1 tracks everyone at 1008 px (its own working size), and H3 People Mask keeps the largest person. The edit mask adds 10% headroom above the head, holds each pose for 2 frames and grows by 40 px, so a differently built character has room; it does not affect the motion. The motion reference H3 follows is the source clip with that person turned into a sharp grey mannequin of their exact silhouette, so the pose, arms and fingers stay readable.++`workflows/simple.api.json` is one API export of that workflow with the hat fix enabled. For each request, `lib/simple.ts`:-- removes the picture branches (Load Image → Shrink → Describe) for unused pictures, and their links into the Swap Plan (`picture_k`, `picture_k_text`) and Reference Conditioning (`ref_images.ref_image_k`);- without the hat fix, removes the hat nodes and connects Grow Mask to the People Mask output;-- sets the Swap Plan's resolution, seed, clip length and roles (one line per picture).+- sets the Swap Plan's resolution, seed, clip length and role.++`lib/comfy.ts` binds the uploaded video to `VHS_LoadVideo` and the photo to the `LoadImage` node, then submits with the SDK. `/api/jobs/[id]/events` streams `job.events()` to the page as server-sent events. Node ids are turned into node titles and clip numbers there: each clip after the first is a graph expansion whose node ids carry a prefix per clip (`58`, `64.0.0.58`, `64.0.0.Recurse.0.0.58`). The final MP4 is the output of the Final Video node (`MiniMaxH3ChainAssemble`, node `65`).-`lib/comfy.ts` binds the uploaded video to `VHS_LoadVideo` and the photos to the `LoadImage` nodes, then submits with the SDK. `/api/jobs/[id]/events` streams `job.events()` to the page as server-sent events. Node ids are turned into node titles and clip numbers there: each clip after the first is a graph expansion whose node ids carry a prefix per clip (`64`, `70.0.0.64`, `70.0.0.Recurse.0.0.64`). The final MP4 is the output of the Final Video node (`MiniMaxH3ChainAssemble`, node `71`).+`workflows/mask.api.json` is the mask check: the same SAM, People Mask and grow settings over the whole video, with the mask tinted over the frames next to the mannequin, saved as an MP4.-To change the workflow, open it in ComfyUI, enable every picture group and the hat-fix group, export **Workflow (API)**, and replace `workflows/simple.api.json`. If node ids change, update `NODES` in `lib/simple.ts`. `npm test` checks the pruning against the export.+To change the workflow, edit `user/default/oneclick_single_build.js` in ComfyUI (or the workflow itself), enable the hat-fix group, export **Workflow (API)**, and replace `workflows/simple.api.json`. If node ids change, update `NODES` in `lib/simple.ts`. `npm test` checks the pruning against the export.## Deploy on the Comfy Developer Platformdiff --git a/app/api/jobs/[id]/events/route.ts b/app/api/jobs/[id]/events/route.tsindex 701fafd..9c27c83 100644--- a/app/api/jobs/[id]/events/route.ts+++ b/app/api/jobs/[id]/events/route.ts@@ -1,4 +1,4 @@-import { getJob, loadSimpleGraph, publicJob, rawJobEvents, TERMINAL } from "../../../../../lib/comfy.ts";+import { getJob, loadGraph, publicJob, rawJobEvents, TERMINAL } from "../../../../../lib/comfy.ts";import { nodeDescriber } from "../../../../../lib/progress.ts";export const runtime = "nodejs";@@ -8,7 +8,7 @@ export const dynamic = "force-dynamic";// numbers. One upstream connection per request; the page's EventSource reconnects.export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {const { id } = await params;- const describe = nodeDescriber(await loadSimpleGraph());+ const describe = nodeDescriber(await loadGraph(new URL(request.url).searchParams.get("kind") === "mask" ? "mask" : "simple"));const encoder = new TextEncoder();const stream = new ReadableStream({diff --git a/app/api/jobs/route.ts b/app/api/jobs/route.tsindex a80d7d0..2695660 100644--- a/app/api/jobs/route.ts+++ b/app/api/jobs/route.ts@@ -1,26 +1,20 @@import { NextResponse } from "next/server";-import { submitSimple } from "../../../lib/comfy.ts";-import { CLIP_SECONDS, MAX_PICTURES, MAX_SEED, RESOLUTIONS, type Resolution, type SimpleSettings } from "../../../lib/simple.ts";+import { submitMask, submitSimple } from "../../../lib/comfy.ts";+import { CLIP_SECONDS, MAX_SEED, RESOLUTIONS, type Resolution, type SimpleSettings } from "../../../lib/simple.ts";export const runtime = "nodejs";-function parse(form: FormData) {- if (form.get("mode") !== "simple") throw new Error("Only Simple motion transfer is available so far.");-+function parseVideo(form: FormData) {const video = form.get("video");if (!(video instanceof File) || video.size === 0) throw new Error("Drop a source video.");if (!video.type.startsWith("video/") && !/\.(mp4|mov|mkv|webm|avi)$/i.test(video.name)) throw new Error("The source must be a video file.");+ return video;+}- const pictures: File[] = [];- const roles: string[] = [];- for (let i = 1; i <= MAX_PICTURES; i++) {- const picture = form.get(`picture_${i}`);- if (!(picture instanceof File) || picture.size === 0) break;- if (!picture.type.startsWith("image/")) throw new Error(`Character ${i} must be an image.`);- pictures.push(picture);- roles.push(String(form.get(`role_${i}`) ?? "").slice(0, 200));- }- if (!pictures.length) throw new Error("Add at least one character photo.");+function parseSimple(form: FormData) {+ const picture = form.get("picture");+ if (!(picture instanceof File) || picture.size === 0) throw new Error("Add a character photo.");+ if (!picture.type.startsWith("image/")) throw new Error("The character photo must be an image.");const resolution = String(form.get("resolution"));if (!RESOLUTIONS.includes(resolution as Resolution)) throw new Error("Choose a supported resolution.");@@ -31,20 +25,31 @@ function parse(form: FormData) {throw new Error(`Clip length must be ${CLIP_SECONDS.min}-${CLIP_SECONDS.max} s.`);}- const settings: SimpleSettings = { roles, resolution: resolution as Resolution, hatFix: form.get("hat_fix") === "true", seed, clipSeconds };- return { video, pictures, settings };+ const settings: SimpleSettings = { role: String(form.get("role") ?? "").slice(0, 200), resolution: resolution as Resolution, hatFix: form.get("hat_fix") === "true", seed, clipSeconds };+ return { picture, settings };}export async function POST(request: Request) {- let input: ReturnType<typeof parse>;+ let submit: () => ReturnType<typeof submitSimple>;try {- input = parse(await request.formData());+ const form = await request.formData();+ const mode = form.get("mode");+ const video = parseVideo(form);+ if (mode === "mask") {+ const hatFix = form.get("hat_fix") === "true";+ submit = () => submitMask(video, hatFix);+ } else if (mode === "simple") {+ const { picture, settings } = parseSimple(form);+ submit = () => submitSimple(video, picture, settings);+ } else {+ throw new Error("Only Simple motion transfer is available so far.");+ }} catch (error) {return NextResponse.json({ error: error instanceof Error ? error.message : "Invalid request." }, { status: 400 });}try {- return NextResponse.json(await submitSimple(input.video, input.pictures, input.settings), { status: 202 });+ return NextResponse.json(await submit(), { status: 202 });} catch (error) {return NextResponse.json({ error: error instanceof Error ? error.message : "Unable to submit the job." }, { status: 502 });}diff --git a/app/globals.css b/app/globals.cssindex dfac909..e261dd3 100644--- a/app/globals.css+++ b/app/globals.css@@ -132,3 +132,13 @@ input[type="range"] { accent-color: var(--accent); width: 220px; max-width: 100%.modes, .inputs { grid-template-columns: 1fr; }.drop.big { min-height: 180px; }}++.go .row { justify-content: center; }+.mask-check video { max-height: 60vh; }+.scrub { width: 100%; accent-color: var(--accent); }+.steps { display: flex; gap: 6px; }+.steps .secondary { padding: 6px 12px; }+.legend { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }+.swatch { display: inline-block; width: 12px; height: 12px; border-radius: 3px; }+.swatch.cyan { background: rgb(0, 200, 255); }+.swatch.orange { background: rgb(255, 140, 0); }diff --git a/components/openjutsu.tsx b/components/openjutsu.tsxindex 2be164e..45c3b51 100644--- a/components/openjutsu.tsx+++ b/components/openjutsu.tsx@@ -1,21 +1,22 @@"use client";-import { useEffect, useState, type DragEvent, type ReactNode } from "react";+import { useEffect, useRef, useState, type DragEvent, type ReactNode } from "react";import type { PublicJob } from "../lib/comfy.ts";import type { NodeInfo } from "../lib/progress.ts";-import { clipCount } from "../lib/clips.ts";-import { CLIP_SECONDS, MAX_PICTURES, MAX_SEED, RESOLUTIONS, type Resolution } from "../lib/simple.ts";+import { clipCount, clipStarts } from "../lib/clips.ts";+import { CLIP_SECONDS, MAX_SEED, RESOLUTIONS, type Resolution } from "../lib/simple.ts";type Character = { file: File; url: string; role: string };-type Run = { id: string; clips: number; startedAt: number };+type Kind = "simple" | "mask";+type Run = { id: string; kind: Kind; clips: number; clipSeconds: number; startedAt: number };type Progress = NodeInfo & { step: number | null; steps: number | null };const TERMINAL = new Set(["succeeded", "failed", "canceled", "expired"]);const RUN_KEY = "openjutsu.run";const MODES = [- { id: "simple", title: "Simple motion transfer", text: "Swap everyone in a video for your characters.", ready: true },- { id: "advanced", title: "Advanced motion transfer", text: "Pick who becomes who by colour-coded tracks.", ready: false },+ { id: "simple", title: "Simple motion transfer", text: "Swap the main person in a video for your character.", ready: true },+ { id: "advanced", title: "Advanced motion transfer", text: "Several people, pick who becomes who.", ready: false },{ id: "object", title: "Object swap", text: "Replace a prop or product instead of a person.", ready: false },];@@ -71,7 +72,7 @@ function DropZone({ accept, onFiles, multiple, children, className }: {export function Openjutsu() {const [video, setVideo] = useState<{ file: File; url: string; duration: number } | null>(null);- const [characters, setCharacters] = useState<Character[]>([]);+ const [character, setCharacter] = useState<Character | null>(null);const [resolution, setResolution] = useState<Resolution>("736p");const [hatFix, setHatFix] = useState(false);const [seed, setSeed] = useState(0);@@ -90,7 +91,7 @@ export function Openjutsu() {useEffect(() => {if (!run) return;- const source = new EventSource(`/api/jobs/${run.id}/events`);+ const source = new EventSource(`/api/jobs/${run.id}/events?kind=${run.kind ?? "simple"}`);source.onmessage = (message) => {const event = JSON.parse(message.data);if (event.type === "job") {@@ -129,40 +130,40 @@ export function Openjutsu() {probe.src = url;}- function addCharacters(files: File[]) {- setCharacters((current) => [- ...current,- ...files.slice(0, MAX_PICTURES - current.length).map((file) => ({ file, url: URL.createObjectURL(file), role: "" })),- ]);+ function chooseCharacter(files: File[]) {+ const file = files[0];+ if (!file) return;+ if (character) URL.revokeObjectURL(character.url);+ setCharacter({ file, url: URL.createObjectURL(file), role: character?.role ?? "" });}- function removeCharacter(index: number) {- URL.revokeObjectURL(characters[index].url);- setCharacters(characters.filter((_, i) => i !== index));+ function removeCharacter() {+ if (character) URL.revokeObjectURL(character.url);+ setCharacter(null);}const clips = video?.duration ? clipCount(video.duration, clipSeconds) : 0;- async function generate() {- if (!video || !characters.length) return;+ async function submit(kind: Kind) {+ if (!video || (kind === "simple" && !character)) return;setSubmitting(true);setFormError("");const form = new FormData();- form.set("mode", "simple");+ form.set("mode", kind);form.set("video", video.file);- characters.forEach((character, i) => {- form.set(`picture_${i + 1}`, character.file);- form.set(`role_${i + 1}`, character.role);- });- form.set("resolution", resolution);form.set("hat_fix", String(hatFix));- form.set("seed", String(seed));- form.set("clip_seconds", String(clipSeconds));+ if (kind === "simple" && character) {+ form.set("picture", character.file);+ form.set("role", character.role);+ form.set("resolution", resolution);+ form.set("seed", String(seed));+ form.set("clip_seconds", String(clipSeconds));+ }try {const response = await fetch("/api/jobs", { method: "POST", body: form });const body = await response.json();if (!response.ok) throw new Error(body.error ?? "Could not start the job.");- const next = { id: body.id, clips: Math.max(clips, 1), startedAt: Date.now() };+ const next: Run = { id: body.id, kind, clips: Math.max(clips, 1), clipSeconds, startedAt: Date.now() };writeRun(next);setJob(body);setProgress(null);@@ -198,7 +199,7 @@ export function Openjutsu() {<span className="mark" aria-hidden>忍</span><div><h1>Openjutsu</h1>- <p>Swap the people in any video for your own characters. Open weights, on your own GPU.</p>+ <p>Swap the person in any video for your own character. Open weights, on your own GPU.</p></div></div></header>@@ -216,7 +217,7 @@ export function Openjutsu() {{run ? (<RunViewrun={run} job={job} progress={progress} preview={preview} streamError={streamError} now={now}- onCancel={cancel} onReset={reset}+ onCancel={cancel} onReset={reset} onGenerate={video && character && !submitting ? () => submit("simple") : null}/>) : (<>@@ -240,33 +241,32 @@ export function Openjutsu() {</div><div className="panel">- <h2><span>2</span> Characters <small>{characters.length}/{MAX_PICTURES}</small></h2>+ <h2><span>2</span> Character</h2><div className="characters">- {characters.map((character, i) => (- <div className="character" key={character.url}>- <img src={character.url} alt={`Character ${i + 1}`} />- <button className="remove" onClick={() => removeCharacter(i)} aria-label={`Remove character ${i + 1}`}>×</button>+ {character ? (+ <div className="character">+ <img src={character.url} alt="Character" />+ <button className="remove" onClick={removeCharacter} aria-label="Remove the character">×</button><label>- <span>Replaces who?</span>+ <span>Who do they replace? (optional)</span><inputvalue={character.role}maxLength={200}- placeholder={i === 0 ? "e.g. the singer" : "e.g. the drummer"}- onChange={(event) => setCharacters(characters.map((c, j) => (j === i ? { ...c, role: event.target.value } : c)))}+ placeholder="e.g. the singer"+ onChange={(event) => setCharacter({ ...character, role: event.target.value })}/></label></div>- ))}- {characters.length < MAX_PICTURES && (- <DropZone accept="image/*" multiple onFiles={addCharacters} className="add">+ ) : (+ <DropZone accept="image/*" onFiles={chooseCharacter} className="add"><strong>+</strong>- <span>{characters.length ? "Add another" : "Drop 1-4 photos"}</span>+ <span>Drop a photo</span></DropZone>)}</div><p className="hint">- One photo per person in the video. Leave “replaces who?” blank to match by screen time. Name a role or position- (“the drummer”, “the person on the left”), not clothes.+ The character replaces the main person in the video, the one who fills the most of the frame. Everyone else stays.+ To name them for the prompt, use a role (“the singer”), not clothes.</p></div></section>@@ -304,10 +304,13 @@ export function Openjutsu() {<div className="go">{formError && <p className="error">{formError}</p>}- <button className="primary" disabled={!video || !characters.length || submitting} onClick={generate}>- {submitting ? "Uploading…" : "Generate"}- </button>- <small>{clips ? `${clips} clip${clips > 1 ? "s" : ""} at ${resolution}` : "Add a video and at least one character."}</small>+ <div className="row">+ <button className="secondary" disabled={!video || submitting} onClick={() => submit("mask")}>Check mask</button>+ <button className="primary" disabled={!video || !character || submitting} onClick={() => submit("simple")}>+ {submitting ? "Uploading…" : "Generate"}+ </button>+ </div>+ <small>{clips ? `${clips} clip${clips > 1 ? "s" : ""} at ${resolution}` : "Add a video and a character photo."}</small></div></>)}@@ -315,12 +318,17 @@ export function Openjutsu() {);}-function RunView({ run, job, progress, preview, streamError, now, onCancel, onReset }: {+function RunView({ run, job, progress, preview, streamError, now, onCancel, onReset, onGenerate }: {run: Run; job: PublicJob | null; progress: Progress | null; preview: string; streamError: string; now: number;- onCancel: () => void; onReset: () => void;+ onCancel: () => void; onReset: () => void; onGenerate: (() => void) | null;}) {const status = job?.status ?? "queued";const clips = Math.max(run.clips, progress?.clip ?? 1);+ const mask = run.kind === "mask";++ if (mask && status === "succeeded" && job?.video) {+ return <MaskCheck url={job.video.url} clipSeconds={run.clipSeconds} onGenerate={onGenerate} onBack={onReset} />;+ }if (status === "succeeded" && job?.video) {return (@@ -346,13 +354,14 @@ function RunView({ run, job, progress, preview, streamError, now, onCancel, onRe}let fraction = 0;- if (progress?.classType === "MiniMaxH3ChainAssemble") fraction = 0.99;+ if (mask) fraction = progress?.classType === "SAM3_VideoTrack" && progress.steps ? (progress.step ?? 0) / progress.steps : 0;+ else if (progress?.classType === "MiniMaxH3ChainAssemble") fraction = 0.99;else if (progress?.clip) fraction = (progress.clip - 1 + clipShare(progress)) / clips;return (<section className="panel progress"><div className="row">- <h2>{status === "queued" ? `Queued${job?.queuePosition ? ` (#${job.queuePosition})` : ""}` : progress?.clip ? `Clip ${progress.clip} of ${clips}` : "Preparing"}</h2>+ <h2>{status === "queued" ? `Queued${job?.queuePosition ? ` (#${job.queuePosition})` : ""}` : mask ? "Checking the mask" : progress?.clip ? `Clip ${progress.clip} of ${clips}` : "Preparing"}</h2><span className="time">{elapsed(now - run.startedAt)}</span></div><div className="bar"><div style={{ width: `${Math.round(fraction * 100)}%` }} /></div>@@ -362,8 +371,67 @@ function RunView({ run, job, progress, preview, streamError, now, onCancel, onRe</p>{preview && <img className="preview" src={preview} alt="Mask preview: white areas are regenerated" />}{streamError && <p className="error">{streamError}</p>}- <p className="hint">Each clip is saved as it finishes, so a rerun with the same inputs resumes where it stopped. You can close this page and come back.</p>+ <p className="hint">{mask ? "SAM tracks the whole video once, about a minute per 3 s of video." : "Each clip is saved as it finishes, so a rerun with the same inputs resumes where it stopped."} You can close this page and come back.</p><button className="secondary" onClick={onCancel}>Cancel</button></section>);}++function MaskCheck({ url, clipSeconds, onGenerate, onBack }: {+ url: string; clipSeconds: number; onGenerate: (() => void) | null; onBack: () => void;+}) {+ const player = useRef<HTMLVideoElement>(null);+ const [frames, setFrames] = useState(0);+ const [frame, setFrame] = useState(0);+ const [playing, setPlaying] = useState(false);+ const starts = frames ? clipStarts(frames / 24, clipSeconds) : [0];++ function seek(target: number) {+ const v = player.current;+ if (!v || !frames) return;+ v.pause();+ setPlaying(false);+ const next = Math.max(0, Math.min(frames - 1, target));+ setFrame(next);+ v.currentTime = (next + 0.5) / 24;+ }++ function toggle() {+ const v = player.current;+ if (!v) return;+ if (playing) v.pause();+ else v.play();+ setPlaying(!playing);+ }++ return (+ <section className="panel mask-check">+ <h2>Check the mask</h2>+ <video+ ref={player} src={url} muted playsInline preload="auto"+ onLoadedMetadata={(event) => setFrames(Math.round(event.currentTarget.duration * 24))}+ onTimeUpdate={(event) => playing && setFrame(Math.min(frames - 1, Math.floor(event.currentTarget.currentTime * 24)))}+ onEnded={() => setPlaying(false)}+ />+ <input className="scrub" type="range" min={0} max={Math.max(frames - 1, 0)} value={frame} aria-label="Frame" onChange={(event) => seek(Number(event.target.value))} />+ <div className="row">+ <div className="steps">+ <button className="secondary" onClick={() => seek(frame - 1)} aria-label="Previous frame">◀</button>+ <button className="secondary" onClick={toggle}>{playing ? "Pause" : "Play"}</button>+ <button className="secondary" onClick={() => seek(frame + 1)} aria-label="Next frame">▶</button>+ </div>+ <small>Frame {frame + 1} / {frames} · {(frame / 24).toFixed(2)} s · clip {starts.filter((start) => start <= frame).length} of {starts.length}</small>+ </div>+ <p className="hint legend">+ <i className="swatch cyan" /> regenerated <i className="swatch orange" /> tracked person · right: the grey mannequin H3 copies the motion from.+ Anything outside the cyan area stays as it is, so the new character should fit inside it.+ </p>+ <p className="hint">The check tracks the whole video at once and the render tracks each clip, so they can differ slightly.</p>+ <div className="row">+ <button className="primary" disabled={!onGenerate} onClick={() => onGenerate?.()}>Looks good, generate</button>+ <button className="secondary" onClick={onBack}>Back to settings</button>+ </div>+ {!onGenerate && <p className="hint">Add a character photo in the settings to generate.</p>}+ </section>+ );+}diff --git a/lib/clips.ts b/lib/clips.tsindex b017fa2..5fcee5f 100644--- a/lib/clips.ts+++ b/lib/clips.ts@@ -5,17 +5,28 @@ const OVERLAP = 39;const gridFloor = (frames: number) => Math.floor((frames - 5) / 17) * 17 + 5;const gridCeil = (frames: number) => Math.ceil((frames - 5) / 17) * 17 + 5;-export function clipCount(durationSeconds: number, clipSeconds: number) {+function clipLengths(durationSeconds: number, clipSeconds: number) {const total = Math.floor(durationSeconds * FPS);const clipFrames = Math.floor(clipSeconds * FPS);- let rem = total - Math.min(gridFloor(clipFrames), gridFloor(total));+ const lengths = [Math.min(gridFloor(clipFrames), gridFloor(total))];+ let rem = total - lengths[0];const count = rem >= 17 ? Math.ceil(rem / (gridFloor(clipFrames) - OVERLAP)) : 0;- let clips = 1;for (let j = 0; j < count; j++) {const length = Math.min(gridCeil(Math.ceil(rem / (count - j)) + OVERLAP), gridFloor(rem + OVERLAP));if (length - OVERLAP < 17) break;- clips++;+ lengths.push(length);rem -= length - OVERLAP;}- return clips;+ return lengths;+}++export function clipCount(durationSeconds: number, clipSeconds: number) {+ return clipLengths(durationSeconds, clipSeconds).length;+}++// First source frame of each clip (clips after the first start OVERLAP frames early).+export function clipStarts(durationSeconds: number, clipSeconds: number) {+ const starts = [0];+ for (const length of clipLengths(durationSeconds, clipSeconds).slice(0, -1)) starts.push(starts.at(-1)! + length - OVERLAP);+ return starts;}diff --git a/lib/comfy.ts b/lib/comfy.tsindex b53da92..990b1a7 100644--- a/lib/comfy.ts+++ b/lib/comfy.ts@@ -2,7 +2,7 @@ import { readFile } from "node:fs/promises";import { join } from "node:path";import { Comfy, resolveBaseUrl, resolveCredentials, type Job } from "@comfyorg/sdk";import { ComfyLow } from "@comfyorg/sdk/low";-import { NODES, pruneSimple, type ApiGraph, type SimpleSettings } from "./simple.ts";+import { MASK_NODES, NODES, pruneMask, pruneSimple, type ApiGraph, type SimpleSettings } from "./simple.ts";export type PublicJob = {id: string;@@ -26,8 +26,10 @@ export function rawJobEvents(job: Job, signal: AbortSignal) {return new ComfyLow(resolveBaseUrl(), resolveCredentials(), { clientInfo: "openjutsu" }).getJobEvents(job.urls.events || job.id, { signal });}-export async function loadSimpleGraph(): Promise<ApiGraph> {- return JSON.parse(await readFile(join(process.cwd(), "workflows", "simple.api.json"), "utf8"));+export type JobKind = "simple" | "mask";++export async function loadGraph(kind: JobKind): Promise<ApiGraph> {+ return JSON.parse(await readFile(join(process.cwd(), "workflows", `${kind}.api.json`), "utf8"));}function jobErrorMessage(error: unknown) {@@ -40,7 +42,7 @@ function jobErrorMessage(error: unknown) {}export function publicJob(job: Job): PublicJob {- const video = job.outputs.find((output) => output.nodeId === NODES.final && output.contentType.startsWith("video/"));+ const video = job.outputs.find((output) => output.contentType.startsWith("video/"));return {id: job.id,status: job.status,@@ -59,11 +61,18 @@ function upload(comfy: Comfy, file: File) {);}-export async function submitSimple(video: File, pictures: File[], settings: SimpleSettings) {+export async function submitSimple(video: File, picture: File, settings: SimpleSettings) {const comfy = client();- const workflow = comfy.workflows.fromJson(pruneSimple(await loadSimpleGraph(), settings));+ const workflow = comfy.workflows.fromJson(pruneSimple(await loadGraph("simple"), settings));workflow.setInput(NODES.video, "video", await upload(comfy, video));- for (const [i, picture] of pictures.entries()) workflow.setInput(NODES.pictures[i].load, "image", await upload(comfy, picture));+ workflow.setInput(NODES.picture, "image", await upload(comfy, picture));+ return publicJob(await comfy.submit(workflow));+}++export async function submitMask(video: File, hatFix: boolean) {+ const comfy = client();+ const workflow = comfy.workflows.fromJson(pruneMask(await loadGraph("mask"), hatFix));+ workflow.setInput(MASK_NODES.video, "video", await upload(comfy, video));return publicJob(await comfy.submit(workflow));}diff --git a/lib/simple.ts b/lib/simple.tsindex 716cdd9..c49707c 100644--- a/lib/simple.ts+++ b/lib/simple.ts@@ -1,5 +1,6 @@-// Simple motion transfer: workflows/simple.api.json is one export with all four-// picture branches and the hat fix enabled. Each request prunes what it does not use.+// Simple motion transfer: one character replaces the main person in the video.+// workflows/simple.api.json (the swap) and workflows/mask.api.json (the mask check) are exported+// with the hat fix enabled; each request prunes what it does not use.export type ApiNode = { class_type: string; inputs: Record<string, unknown>; _meta?: { title?: string } };export type ApiGraph = Record<string, ApiNode>;@@ -7,86 +8,68 @@ export type ApiGraph = Record<string, ApiNode>;export const RESOLUTIONS = ["480p", "576p", "736p", "768p", "1080p"] as const;export type Resolution = (typeof RESOLUTIONS)[number];-export const MAX_PICTURES = 4;export const CLIP_SECONDS = { min: 2.5, max: 15, default: 6 };export const MAX_SEED = 0xffffffff;export type SimpleSettings = {- roles: string[]; // one entry per picture, "" when the user left it blank+ role: string; // who the character replaces, "" to let the describer name the main personresolution: Resolution;hatFix: boolean;seed: number;clipSeconds: number;};+type HatNodes = { hat: string[]; growMask: string; peopleMask: string };+// Node ids in workflows/simple.api.json.export const NODES = {- video: "14",- plan: "20",- reference: "39",- peopleMask: "46",- growMask: "48",- loopStart: "37",- loopEnd: "70",- final: "71",- pictures: [- { load: "2", shrink: "3", describe: "4" },- { load: "5", shrink: "6", describe: "7" },- { load: "8", shrink: "9", describe: "10" },- { load: "11", shrink: "12", describe: "13" },- ],- hat: ["53", "54", "55", "56"],+ picture: "2",+ video: "5",+ plan: "11",+ loopStart: "28",+ peopleMask: "39",+ growMask: "42",+ loopEnd: "66",+ final: "67",+ hat: ["47", "48", "49", "50", "51", "52"],+};++// Node ids in workflows/mask.api.json.+export const MASK_NODES = {+ video: "1",+ peopleMask: "7",+ growMask: "9",+ hat: ["10", "11", "12", "13", "19", "20"],};export function isLink(value: unknown): value is [string, number] {return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number";}-// The Swap Plan falls back to "the person with the most screen time", "... second most ..." when roles is blank.-// A partly filled list keeps that fallback for the blank lines so every line stays on its own picture.-function ordinalRole(index: number, count: number) {- if (count === 1) return "the main person";- return `the person with the ${["", "second ", "third ", "fourth "][index]}most screen time`;-}--export function rolesText(roles: string[]) {- const clean = roles.map((role) => role.replace(/\s+/g, " ").trim());- if (clean.every((role) => !role)) return "";- return clean.map((role, i) => role || ordinalRole(i, clean.length)).join("\n");-}--export function pruneSimple(source: ApiGraph, settings: SimpleSettings): ApiGraph {- const count = settings.roles.length;- if (count < 1 || count > MAX_PICTURES) throw new Error(`Use 1 to ${MAX_PICTURES} pictures.`);-+function withoutHats(source: ApiGraph, hatFix: boolean, nodes: HatNodes): ApiGraph {const graph: ApiGraph = structuredClone(source);- const plan = graph[NODES.plan].inputs;- const reference = graph[NODES.reference].inputs;-- for (const [i, picture] of NODES.pictures.entries()) {- if (i < count) continue;- delete graph[picture.load];- delete graph[picture.shrink];- delete graph[picture.describe];- delete plan[`picture_${i + 1}`];- delete plan[`picture_${i + 1}_text`];- delete reference[`ref_images.ref_image_${i}`];- }-- if (!settings.hatFix) {- for (const id of NODES.hat) delete graph[id];- graph[NODES.growMask].inputs.mask = [NODES.peopleMask, 0];+ if (!hatFix) {+ for (const id of nodes.hat) delete graph[id];+ graph[nodes.growMask].inputs.mask = [nodes.peopleMask, 0];}-for (const [id, node] of Object.entries(graph)) {for (const [name, value] of Object.entries(node.inputs)) {if (isLink(value) && !graph[value[0]]) throw new Error(`Node ${id}.${name} still links to removed node ${value[0]}.`);}}+ return graph;+}+export function pruneSimple(source: ApiGraph, settings: SimpleSettings): ApiGraph {+ const graph = withoutHats(source, settings.hatFix, NODES);+ const plan = graph[NODES.plan].inputs;plan.resolution = settings.resolution;plan.seed = settings.seed;plan.clip_seconds = settings.clipSeconds;- plan.roles = rolesText(settings.roles);+ plan.roles = settings.role.replace(/\s+/g, " ").trim();return graph;}++export function pruneMask(source: ApiGraph, hatFix: boolean): ApiGraph {+ return withoutHats(source, hatFix, MASK_NODES);+}diff --git a/test/simple.test.ts b/test/simple.test.tsindex 1eb239e..a435830 100644--- a/test/simple.test.ts+++ b/test/simple.test.ts@@ -1,54 +1,64 @@import assert from "node:assert/strict";import { readFileSync } from "node:fs";import test from "node:test";-import { clipCount } from "../lib/clips.ts";+import { clipCount, clipStarts } from "../lib/clips.ts";import { nodeDescriber } from "../lib/progress.ts";-import { NODES, pruneSimple, rolesText, type ApiGraph, type SimpleSettings } from "../lib/simple.ts";+import { MASK_NODES, NODES, pruneMask, pruneSimple, type ApiGraph, type SimpleSettings } from "../lib/simple.ts";-const graph: ApiGraph = JSON.parse(readFileSync(new URL("../workflows/simple.api.json", import.meta.url), "utf8"));-const settings = (roles: string[], hatFix = false): SimpleSettings => ({ roles, resolution: "480p", hatFix, seed: 7, clipSeconds: 6 });+const load = (name: string): ApiGraph => JSON.parse(readFileSync(new URL(`../workflows/${name}.api.json`, import.meta.url), "utf8"));+const graph = load("simple");+const mask = load("mask");+const HAT_TYPES = ["CLIPTextEncode", "SAM3_VideoTrack", "SAM3_TrackToMask", "GrowMaskWithBlur", "MaskComposite", "MaskComposite"];+const settings = (hatFix: boolean): SimpleSettings => ({ role: " the singer ", resolution: "480p", hatFix, seed: 7, clipSeconds: 6 });-test("one picture without hat fix drops pictures 2-4 and the hat nodes", () => {- const pruned = pruneSimple(graph, settings(["the singer"]));- for (const id of ["5", "6", "7", "8", "9", "10", "11", "12", "13", ...NODES.hat]) assert.equal(pruned[id], undefined);- const plan = pruned[NODES.plan].inputs;- assert.deepEqual(Object.keys(plan).filter((k) => k.startsWith("picture_")), ["picture_1", "picture_1_text"]);- assert.deepEqual(Object.keys(pruned[NODES.reference].inputs).filter((k) => k.startsWith("ref_images.")), ["ref_images.ref_image_0"]);- assert.deepEqual(pruned[NODES.growMask].inputs.mask, [NODES.peopleMask, 0]);- assert.equal(plan.resolution, "480p");- assert.equal(plan.seed, 7);- assert.equal(plan.roles, "the singer");- assert.ok(graph["13"], "the source graph is not modified");+test("the node ids match the export", () => {+ const types = { picture: "LoadImage", video: "VHS_LoadVideo", plan: "H3OneClickSwapPlan", loopStart: "MiniMaxH3ChainLoopStart", peopleMask: "H3PeopleMask",+ growMask: "GrowMaskWithBlur", loopEnd: "MiniMaxH3ChainLoopEnd", final: "MiniMaxH3ChainAssemble" } as const;+ for (const [key, type] of Object.entries(types)) assert.equal(graph[NODES[key as keyof typeof types]].class_type, type, key);+ assert.deepEqual(NODES.hat.map((id) => graph[id].class_type), HAT_TYPES);+ assert.deepEqual(MASK_NODES.hat.map((id) => mask[id].class_type).sort(), [...HAT_TYPES].sort());+ assert.equal(mask[MASK_NODES.video].class_type, "VHS_LoadVideo");});-test("four pictures with hat fix keep the full graph", () => {- const pruned = pruneSimple(graph, settings(["", "", "", ""], true));- assert.equal(Object.keys(pruned).length, Object.keys(graph).length);- assert.deepEqual(pruned[NODES.growMask].inputs.mask, ["56", 0]);- assert.equal(pruned[NODES.plan].inputs.roles, "");+test("without hat fix the hat nodes go and the grow mask reads the people mask", () => {+ const pruned = pruneSimple(graph, settings(false));+ for (const id of NODES.hat) assert.equal(pruned[id], undefined);+ assert.deepEqual(pruned[NODES.growMask].inputs.mask, [NODES.peopleMask, 0]);+ const plan = pruned[NODES.plan].inputs;+ assert.deepEqual([plan.resolution, plan.seed, plan.clip_seconds, plan.roles], ["480p", 7, 6, "the singer"]);+ assert.ok(graph[NODES.hat[0]], "the source graph is not modified");});-test("blank roles keep their line with the plan's own fallback", () => {- assert.equal(rolesText(["", " the drummer "]), "the person with the most screen time\nthe drummer");- assert.equal(rolesText(["", ""]), "");+test("with hat fix the full graph is kept", () => {+ const pruned = pruneSimple(graph, settings(true));+ assert.equal(Object.keys(pruned).length, Object.keys(graph).length);+ assert.deepEqual(pruned[NODES.growMask].inputs.mask, [NODES.hat[5], 0]);});test("node ids map to titles and clip numbers", () => {const describe = nodeDescriber(graph);assert.deepEqual(describe("4"), { title: "Describe picture 1", classType: "TextGenerate", clip: null });- assert.equal(describe("64")?.clip, 1);- assert.equal(describe("70.0.0.64")?.clip, 2);- assert.equal(describe("70.0.0.Recurse.0.0.64")?.clip, 3);- assert.equal(describe("70.0.0.Recurse")?.title, "Loop End");- assert.equal(describe("71")?.clip, null);+ assert.equal(describe("60")?.clip, 1);+ assert.equal(describe("66.0.0.60")?.clip, 2);+ assert.equal(describe("66.0.0.Recurse.0.0.60")?.clip, 3);+ assert.equal(describe("66.0.0.Recurse")?.title, "Loop End");+ assert.equal(describe(NODES.final)?.clip, null);});test("clip count follows the Swap Plan grid", () => {assert.equal(clipCount(6, 6), 1);assert.equal(clipCount(16, 6), 4);-});--test("clip count matches the Python plan on longer videos", () => {assert.equal(clipCount(30, 6), 7);assert.equal(clipCount(10, 15), 1);});++test("the mask check drops the hat nodes without hat fix", () => {+ const pruned = pruneMask(mask, false);+ for (const id of MASK_NODES.hat) assert.equal(pruned[id], undefined);+ assert.deepEqual(pruned[MASK_NODES.growMask].inputs.mask, [MASK_NODES.peopleMask, 0]);+ assert.equal(Object.keys(pruneMask(mask, true)).length, Object.keys(mask).length);+});++test("clip starts follow the Swap Plan's 39-frame overlap", () => {+ assert.deepEqual(clipStarts(339 / 24, 6), [0, 102, 204]);+});diff --git a/workflows/mask.api.json b/workflows/mask.api.jsonnew file mode 100644index 0000000..433b51e--- /dev/null+++ b/workflows/mask.api.json@@ -0,0 +1,22 @@+{+ "1": {"class_type": "VHS_LoadVideo", "_meta": {"title": "Source video"}, "inputs": {"video": "", "force_rate": 24, "custom_width": 0, "custom_height": 0, "frame_load_cap": 0, "skip_first_frames": 0, "select_every_nth": 1, "format": "None"}},+ "2": {"class_type": "CheckpointLoaderSimple", "_meta": {"title": "SAM 3.1"}, "inputs": {"ckpt_name": "sam3.1_multiplex_fp16.safetensors"}},+ "3": {"class_type": "CLIPTextEncode", "_meta": {"title": "SAM: what to replace"}, "inputs": {"text": "person", "clip": ["2", 1]}},+ "4": {"class_type": "ImageScaleToMaxDimension", "_meta": {"title": "Motion reference video (~512 px)"}, "inputs": {"upscale_method": "area", "largest_size": 512, "image": ["1", 0]}},+ "5": {"class_type": "ImageScaleToMaxDimension", "_meta": {"title": "SAM video (1008 px)"}, "inputs": {"upscale_method": "area", "largest_size": 1008, "image": ["1", 0]}},+ "6": {"class_type": "SAM3_VideoTrack", "_meta": {"title": "SAM 3.1 track every person"}, "inputs": {"detection_threshold": 0.35, "max_objects": 0, "detect_interval": 1, "images": ["5", 0], "model": ["2", 0], "conditioning": ["3", 0]}},+ "7": {"class_type": "H3PeopleMask", "_meta": {"title": "Main person (+ headroom)"}, "inputs": {"headroom": 0.1, "hold_frames": 2, "max_people": 1, "track_data": ["6", 0]}},+ "8": {"class_type": "H3PeopleMask", "_meta": {"title": "Main person, no headroom (for the mannequin)"}, "inputs": {"headroom": 0, "hold_frames": 1, "max_people": 1, "track_data": ["6", 0]}},+ "9": {"class_type": "GrowMaskWithBlur", "_meta": {"title": "Grow mask (~4% of the frame)"}, "inputs": {"expand": 40, "incremental_expandrate": 0, "tapered_corners": true, "flip_input": false, "blur_radius": 0, "lerp_alpha": 1, "decay_factor": 1, "fill_holes": true, "mask": ["13", 0]}},+ "10": {"class_type": "CLIPTextEncode", "_meta": {"title": "SAM: hats"}, "inputs": {"text": "hat", "clip": ["2", 1]}},+ "11": {"class_type": "SAM3_VideoTrack", "_meta": {"title": "SAM 3.1 track hats"}, "inputs": {"detection_threshold": 0.35, "max_objects": 0, "detect_interval": 1, "images": ["5", 0], "model": ["2", 0], "conditioning": ["10", 0]}},+ "12": {"class_type": "SAM3_TrackToMask", "_meta": {"title": "All hats"}, "inputs": {"object_indices": "", "track_data": ["11", 0]}},+ "13": {"class_type": "MaskComposite", "_meta": {"title": "People + hats"}, "inputs": {"x": 0, "y": 0, "operation": "add", "destination": ["7", 0], "source": ["20", 0]}},+ "14": {"class_type": "H3GreyMannequins", "_meta": {"title": "Grey mannequin (what H3 follows)"}, "inputs": {"blur": 0.01, "images": ["4", 0], "mask": ["8", 0], "size": ["8", 1]}},+ "15": {"class_type": "ImageAndMaskPreview", "_meta": {"title": "Regenerated area (cyan)"}, "inputs": {"mask_opacity": 0.45, "mask_color": "0, 200, 255", "pass_through": true, "image": ["4", 0], "mask": ["9", 0]}},+ "16": {"class_type": "ImageAndMaskPreview", "_meta": {"title": "Tracked person (orange)"}, "inputs": {"mask_opacity": 0.35, "mask_color": "255, 140, 0", "pass_through": true, "image": ["15", 0], "mask": ["8", 0]}},+ "17": {"class_type": "ImageStitch", "_meta": {"title": "Mask | mannequin"}, "inputs": {"direction": "right", "match_image_size": true, "spacing_width": 0, "spacing_color": "white", "image1": ["16", 0], "image2": ["14", 0]}},+ "18": {"class_type": "VHS_VideoCombine", "_meta": {"title": "Mask preview video"}, "inputs": {"frame_rate": 24, "loop_count": 0, "filename_prefix": "openjutsu_mask/mask", "format": "video/h264-mp4", "pix_fmt": "yuv420p", "crf": 19, "save_metadata": false, "trim_to_audio": false, "pingpong": false, "save_output": false, "images": ["17", 0]}},+ "19": {"class_type": "GrowMaskWithBlur", "_meta": {"title": "Hat search area (person + 60 px)"}, "inputs": {"expand": 60, "incremental_expandrate": 0, "tapered_corners": true, "flip_input": false, "blur_radius": 0, "lerp_alpha": 1, "decay_factor": 1, "fill_holes": true, "mask": ["7", 0]}},+ "20": {"class_type": "MaskComposite", "_meta": {"title": "Only the main person's hat"}, "inputs": {"x": 0, "y": 0, "operation": "multiply", "destination": ["12", 0], "source": ["19", 0]}}+}diff --git a/workflows/simple.api.json b/workflows/simple.api.jsonindex 28c3ba1..792c81d 100644--- a/workflows/simple.api.json+++ b/workflows/simple.api.json@@ -1,7 +1,7 @@{"2": {"inputs": {- "image": "Twilight Rest Stop Portrait.png"+ "image": "apt_vest_reference.png"},"class_type": "LoadImage","_meta": {@@ -31,7 +31,7 @@"use_default_template": true,"mtp": "auto","clip": [- "22",+ "13",0],"image": [@@ -46,142 +46,7 @@},"5": {"inputs": {- "image": "Gemini_Generated_Image_afg9p7afg9p7afg9.png"- },- "class_type": "LoadImage",- "_meta": {- "title": "Picture 2"- }- },- "6": {- "inputs": {- "upscale_method": "area",- "largest_size": 768,- "image": [- "5",- 0- ]- },- "class_type": "ImageScaleToMaxDimension",- "_meta": {- "title": "Shrink for the describer"- }- },- "7": {- "inputs": {- "prompt": "Describe the person in this picture for a casting sheet, in one sentence of about 40 words: apparent age and gender, hair, facial hair, skin tone, build, and their complete outfit including footwear. No preamble, no background.",- "max_length": 120,- "sampling_mode": "off",- "thinking": false,- "use_default_template": true,- "mtp": "auto",- "clip": [- "22",- 0- ],- "image": [- "6",- 0- ]- },- "class_type": "TextGenerate",- "_meta": {- "title": "Describe picture 2"- }- },- "8": {- "inputs": {- "image": "example.png"- },- "class_type": "LoadImage",- "_meta": {- "title": "Picture 3"- }- },- "9": {- "inputs": {- "upscale_method": "area",- "largest_size": 768,- "image": [- "8",- 0- ]- },- "class_type": "ImageScaleToMaxDimension",- "_meta": {- "title": "Shrink for the describer"- }- },- "10": {- "inputs": {- "prompt": "Describe the person in this picture for a casting sheet, in one sentence of about 40 words: apparent age and gender, hair, facial hair, skin tone, build, and their complete outfit including footwear. No preamble, no background.",- "max_length": 120,- "sampling_mode": "off",- "thinking": false,- "use_default_template": true,- "mtp": "auto",- "clip": [- "22",- 0- ],- "image": [- "9",- 0- ]- },- "class_type": "TextGenerate",- "_meta": {- "title": "Describe picture 3"- }- },- "11": {- "inputs": {- "image": "example.png"- },- "class_type": "LoadImage",- "_meta": {- "title": "Picture 4"- }- },- "12": {- "inputs": {- "upscale_method": "area",- "largest_size": 768,- "image": [- "11",- 0- ]- },- "class_type": "ImageScaleToMaxDimension",- "_meta": {- "title": "Shrink for the describer"- }- },- "13": {- "inputs": {- "prompt": "Describe the person in this picture for a casting sheet, in one sentence of about 40 words: apparent age and gender, hair, facial hair, skin tone, build, and their complete outfit including footwear. No preamble, no background.",- "max_length": 120,- "sampling_mode": "off",- "thinking": false,- "use_default_template": true,- "mtp": "auto",- "clip": [- "22",- 0- ],- "image": [- "12",- 0- ]- },- "class_type": "TextGenerate",- "_meta": {- "title": "Describe picture 4"- }- },- "14": {- "inputs": {- "video": "generation.mp4",+ "video": "spiderman_jeangrey_apt.mp4","force_rate": 24,"custom_width": 0,"custom_height": 0,@@ -195,12 +60,12 @@"title": "Source video (people get replaced)"}},- "15": {+ "6": {"inputs": {"start_index": 0,"duration": 2048,"audio": [- "14",+ "5",2]},@@ -209,12 +74,12 @@"title": "Soundtrack (whole video)"}},- "16": {+ "7": {"inputs": {"select_every_nth": 48,"skip_first_images": 24,"images": [- "14",+ "5",0]},@@ -223,12 +88,12 @@"title": "One frame every 2 s"}},- "17": {+ "8": {"inputs": {"batch_index": 0,"length": 20,"image": [- "16",+ "7",0]},@@ -237,12 +102,12 @@"title": "At most 20 frames"}},- "18": {+ "9": {"inputs": {"upscale_method": "area","largest_size": 640,"image": [- "17",+ "8",0]},@@ -251,7 +116,7 @@"title": "Shrink for the describer"}},- "19": {+ "10": {"inputs": {"prompt": "These are frames from one video, in time order. List the people who appear most, up to four, the person with the most screen time first. Write one numbered line per person: first their role in the video in two to four words, without gender, that stays true in every shot, then \" - \" and how they look, like \"1. the guitarist - tall man with a grey beard in a denim jacket\". Each person appears once. Output only the list.","max_length": 160,@@ -260,11 +125,11 @@"use_default_template": true,"mtp": "auto","clip": [- "22",+ "13",0],"image": [- "18",+ "9",0]},@@ -273,7 +138,7 @@"title": "Who is in the video"}},- "20": {+ "11": {"inputs": {"clip_seconds": 6,"overlap_frames": 39,@@ -282,43 +147,19 @@"seed": 0,"roles": "","source_frames": [- "14",+ "5",0],"picture_1": ["2",0],- "picture_2": [- "5",- 0- ],- "picture_3": [- "8",- 0- ],- "picture_4": [- "11",- 0- ],"picture_1_text": ["4",0],- "picture_2_text": [- "7",- 0- ],- "picture_3_text": [- "10",- 0- ],- "picture_4_text": [- "13",- 0- ],"video_people": [- "19",+ "10",0]},@@ -327,7 +168,7 @@"title": "Swap Plan (roles, seed, size)"}},- "22": {+ "13": {"inputs": {"clip_name": "qwen3vl_8b_int8_convrot.safetensors","type": "stable_diffusion",@@ -338,7 +179,7 @@"title": "Describer: Qwen3-VL 8B"}},- "24": {+ "15": {"inputs": {"unet_name": "minimax_h3_ref2va_pruned_int8_convrot.safetensors","weight_dtype": "default"@@ -348,12 +189,12 @@"title": "H3 Diffusion Model"}},- "25": {+ "16": {"inputs": {"lora_name": "minimax_h3_DMAD_4step_full_lora_avg_rank_39_bf16.safetensors","strength_model": 1,"model": [- "24",+ "15",0]},@@ -362,11 +203,11 @@"title": "DMAD LoRA"}},- "26": {+ "17": {"inputs": {"attention": "comfy kitchen attention","model": [- "25",+ "16",0]},@@ -375,12 +216,12 @@"title": "Comfy Kitchen Attention"}},- "27": {+ "18": {"inputs": {"shift_video": 12,"shift_audio": 2,"model": [- "26",+ "17",0]},@@ -389,7 +230,7 @@"title": "Sigma Shift"}},- "28": {+ "19": {"inputs": {"clip_name": "qwen3vl_32b_minimax_h3_int4_convrot.safetensors","type": "minimax",@@ -400,7 +241,7 @@"title": "H3 Text Encoder"}},- "29": {+ "20": {"inputs": {"vae_name": "minimax_h3_video_vae_int8_convrot.safetensors"},@@ -409,7 +250,7 @@"title": "Video VAE"}},- "30": {+ "21": {"inputs": {"vae_name": "minimax_h3_audio_vae_fp32.safetensors"},@@ -418,7 +259,7 @@"title": "Audio VAE"}},- "31": {+ "22": {"inputs": {"sampler_name": "euler"},@@ -427,7 +268,7 @@"title": "Sampler"}},- "32": {+ "23": {"inputs": {"ckpt_name": "sam3.1_multiplex_fp16.safetensors"},@@ -436,11 +277,11 @@"title": "SAM 3.1"}},- "33": {+ "24": {"inputs": {"text": "person","clip": [- "32",+ "23",1]},@@ -449,7 +290,7 @@"title": "SAM: what to replace"}},- "34": {+ "25": {"inputs": {"scene_continuity": "Hard picture + protected audio","audio_profile": "Generate audio"@@ -459,20 +300,20 @@"title": "Generation Profile"}},- "35": {+ "26": {"inputs": {"plan_json": "{\n \"shots\": [\n {\n \"id\": \"intro\",\n \"prompt\": \"Describe the opening shot.\"\n },\n {\n \"id\": \"continuation\",\n \"prompt\": \"Continue the same take.\"\n }\n ]\n}","run_name": [- "20",+ "11",3],"generation_fingerprint": "","width": [- "20",+ "11",1],"height": [- "20",+ "11",2],"encode_mode": "video",@@ -483,11 +324,11 @@"segment_crf": 16,"video_blend_frames": 0,"chain_policy": [- "34",+ "25",0],"plan_json_input": [- "20",+ "11",0]},@@ -496,14 +337,14 @@"title": "Production Plan (filled by Swap Plan)"}},- "36": {+ "27": {"inputs": {"video_path": "","audio_path": "","embedded_audio": "auto","skip_first_frames": 0,"source_audio": [- "15",+ "6",0]},@@ -512,17 +353,17 @@"title": "Source soundtrack"}},- "37": {+ "28": {"inputs": {"start_clip": 1,"scene_range": "","verify_resume_history": true,"plan": [- "35",+ "26",0],"source_timeline": [- "36",+ "27",0]},@@ -531,11 +372,11 @@"title": "Loop Start"}},- "38": {+ "29": {"inputs": {"align_audio_reference": false,"state": [- "37",+ "28",1]},@@ -544,59 +385,47 @@"title": "Current Clip"}},- "39": {+ "30": {"inputs": {"prompt": [- "51",+ "45",0],"width": [- "38",+ "29",8],"height": [- "38",+ "29",9],"length": [- "38",+ "29",6],"ref_image_size": "match","clip": [- "28",+ "19",0],"vae": [- "29",+ "20",0],"audio_vae": [- "30",+ "21",0],"ref_images.ref_image_0": ["2",0],- "ref_images.ref_image_1": [- "5",- 0- ],- "ref_images.ref_image_2": [- "8",- 0- ],- "ref_images.ref_image_3": [- "11",- 0- ],"ref_videos.ref_video_0": [- "47",+ "41",0],"ref_video_audios.ref_video_audio_0": [- "38",+ "29",12]},@@ -605,91 +434,125 @@"title": "Reference Conditioning"}},- "40": {+ "31": {"inputs": {"source_fps": 24,"crop": "center","state": [- "38",+ "29",0],"latent": [- "39",+ "30",1],"vae": [- "29",+ "20",0],"audio_vae": [- "30",+ "21",0],"source_frames": [- "14",+ "5",0],- "source_audio": [- "15",+ "source_audio": [+ "6",+ 0+ ]+ },+ "class_type": "MiniMaxH3ContexLoopSourceAVTarget",+ "_meta": {+ "title": "Source clip (frames + audio)"+ }+ },+ "32": {+ "inputs": {+ "upscale_method": "area",+ "largest_size": 512,+ "image": [+ "5",+ 0+ ]+ },+ "class_type": "ImageScaleToMaxDimension",+ "_meta": {+ "title": "Motion reference video (~512 px)"+ }+ },+ "33": {+ "inputs": {+ "expression": "round(a * 24)",+ "values.a": [+ "29",+ 10+ ]+ },+ "class_type": "ComfyMathExpression",+ "_meta": {+ "title": "Clip start frame"+ }+ },+ "34": {+ "inputs": {+ "batch_index": [+ "33",+ 1+ ],+ "length": [+ "29",+ 6+ ],+ "image": [+ "32",0]},- "class_type": "MiniMaxH3ContexLoopSourceAVTarget",+ "class_type": "ImageFromBatch","_meta": {- "title": "Source clip (frames + audio)"+ "title": "Motion reference for this clip"}},- "41": {+ "35": {"inputs": {"upscale_method": "area",- "largest_size": 512,+ "largest_size": 1008,"image": [- "14",+ "5",0]},"class_type": "ImageScaleToMaxDimension","_meta": {- "title": "Motion reference video (~512 px)"- }- },- "42": {- "inputs": {- "expression": "round(a * 24)",- "values.a": [- "38",- 10- ]- },- "class_type": "ComfyMathExpression",- "_meta": {- "title": "Clip start frame"+ "title": "SAM video (1008 px, SAM's own size)"}},- "43": {+ "36": {"inputs": {"batch_index": [- "42",+ "33",1],"length": [- "38",+ "29",6],"image": [- "41",+ "35",0]},"class_type": "ImageFromBatch","_meta": {- "title": "Motion reference for this clip"+ "title": "SAM frames for this clip"}},- "44": {+ "37": {"inputs": {"noise_seed": [- "38",+ "29",5]},@@ -698,21 +561,21 @@"title": "Clip Seed"}},- "45": {+ "38": {"inputs": {"detection_threshold": 0.35,"max_objects": 0,"detect_interval": 1,"images": [- "43",+ "36",0],"model": [- "32",+ "23",0],"conditioning": [- "33",+ "24",0]},@@ -721,44 +584,60 @@"title": "SAM 3.1 track every person"}},- "46": {+ "39": {"inputs": {- "headroom": 0.2,- "hold_frames": 4,+ "headroom": 0.1,+ "hold_frames": 2,+ "max_people": 1,"track_data": [- "45",+ "38",0]},"class_type": "H3PeopleMask","_meta": {- "title": "All tracked people (+ headroom per person)"+ "title": "Main person (+ headroom)"}},- "47": {+ "40": {+ "inputs": {+ "headroom": 0,+ "hold_frames": 1,+ "max_people": 1,+ "track_data": [+ "38",+ 0+ ]+ },+ "class_type": "H3PeopleMask",+ "_meta": {+ "title": "Main person, no headroom (for the mannequin)"+ }+ },+ "41": {"inputs": {- "blur": 0.02,+ "blur": 0.01,"images": [- "43",+ "34",0],"mask": [- "48",+ "40",0],"size": [- "46",+ "40",1]},"class_type": "H3GreyMannequins","_meta": {- "title": "Hide the original people (grey mannequins)"+ "title": "Hide the main person (grey mannequin)"}},- "48": {+ "42": {"inputs": {- "expand": 10,+ "expand": 40,"incremental_expandrate": 0,"tapered_corners": true,"flip_input": false,@@ -767,24 +646,24 @@"decay_factor": 1,"fill_holes": true,"mask": [- "56",+ "52",0]},"class_type": "GrowMaskWithBlur","_meta": {- "title": "Grow mask (~25 px at full size)"+ "title": "Grow mask (~4% of the frame)"}},- "49": {+ "43": {"inputs": {"cut_threshold": 40,"images": [- "43",+ "34",0],"shot_prompt": [- "20",+ "11",4]},@@ -793,10 +672,10 @@"title": "Find this clip's cuts"}},- "50": {+ "44": {"inputs": {"prompt": [- "49",+ "43",1],"max_length": 500,@@ -805,11 +684,11 @@"use_default_template": true,"mtp": "auto","clip": [- "22",+ "13",0],"image": [- "49",+ "43",0]},@@ -818,14 +697,14 @@"title": "Write this clip's shot list (Qwen3-VL)"}},- "51": {+ "45": {"inputs": {"prompt": [- "38",+ "29",4],"shots": [- "50",+ "44",0]},@@ -834,10 +713,10 @@"title": "Insert shot list into prompt"}},- "52": {+ "46": {"inputs": {"source": [- "51",+ "45",0]},@@ -846,11 +725,11 @@"title": "Clip prompt (what H3 gets)"}},- "53": {+ "47": {"inputs": {"text": "hat","clip": [- "32",+ "23",1]},@@ -859,21 +738,21 @@"title": "SAM: hats"}},- "54": {+ "48": {"inputs": {"detection_threshold": 0.35,"max_objects": 0,"detect_interval": 1,"images": [- "43",+ "36",0],"model": [- "32",+ "23",0],"conditioning": [- "53",+ "47",0]},@@ -882,11 +761,11 @@"title": "SAM 3.1 track hats"}},- "55": {+ "49": {"inputs": {"object_indices": "","track_data": [- "54",+ "48",0]},@@ -895,17 +774,56 @@"title": "All hats"}},- "56": {+ "50": {+ "inputs": {+ "expand": 60,+ "incremental_expandrate": 0,+ "tapered_corners": true,+ "flip_input": false,+ "blur_radius": 0,+ "lerp_alpha": 1,+ "decay_factor": 1,+ "fill_holes": true,+ "mask": [+ "39",+ 0+ ]+ },+ "class_type": "GrowMaskWithBlur",+ "_meta": {+ "title": "Hat search area (person + 60 px)"+ }+ },+ "51": {+ "inputs": {+ "x": 0,+ "y": 0,+ "operation": "multiply",+ "destination": [+ "49",+ 0+ ],+ "source": [+ "50",+ 0+ ]+ },+ "class_type": "MaskComposite",+ "_meta": {+ "title": "Only the main person's hat"+ }+ },+ "52": {"inputs": {"x": 0,"y": 0,"operation": "add","destination": [- "46",+ "39",0],"source": [- "55",+ "51",0]},@@ -914,7 +832,7 @@"title": "People + hats"}},- "57": {+ "53": {"inputs": {"cell_selection": "runtime exact (latent max)","cell_adjust": 0,@@ -924,11 +842,11 @@"show_source_outline": true,"mask_meaning": "white = generate","image": [- "47",- 0+ "31",+ 1],"mask": [- "48",+ "42",0]},@@ -937,10 +855,10 @@"title": "Mask preview"}},- "58": {+ "54": {"inputs": {"images": [- "57",+ "53",1]},@@ -949,29 +867,29 @@"title": "Mask preview (white = regenerated)"}},- "59": {+ "55": {"inputs": {"grow": 0,"keep_audio": true,"megapixels": 0,"vae": [- "29",+ "20",0],"images": [- "40",+ "31",1],"mask": [- "48",+ "42",0],"audio_vae": [- "30",+ "21",0],"audio": [- "40",+ "31",2]},@@ -980,17 +898,17 @@"title": "Edit latent (source + mask + audio)"}},- "60": {+ "56": {"inputs": {"mask_meaning": "white = generate","audio_mode": "preserve source audio","mask_conversion": "H3 exact (causal/token max)","target_latent": [- "59",+ "55",0],"mask": [- "48",+ "42",0]},@@ -999,26 +917,26 @@"title": "Masked target"}},- "61": {+ "57": {"inputs": {"state": [- "38",+ "29",0],"conditioning": [- "39",+ "30",0],"vae": [- "29",+ "20",0],"latent": [- "60",+ "56",0],"audio_vae": [- "30",+ "21",0]},@@ -1027,14 +945,14 @@"title": "Apply Clip Context"}},- "62": {+ "58": {"inputs": {"model": [- "27",+ "18",0],"conditioning": [- "61",+ "57",0]},@@ -1043,16 +961,16 @@"title": "Guider"}},- "63": {+ "59": {"inputs": {"scheduler": "simple","steps": [- "38",+ "29",7],"denoise": 1,"model": [- "27",+ "18",0]},@@ -1061,26 +979,26 @@"title": "Schedule"}},- "64": {+ "60": {"inputs": {"noise": [- "44",+ "37",0],"guider": [- "62",+ "58",0],"sampler": [- "31",+ "22",0],"sigmas": [- "63",+ "59",0],"latent_image": [- "61",+ "57",3]},@@ -1089,14 +1007,14 @@"title": "Sample Video + Audio"}},- "65": {+ "61": {"inputs": {"samples": [- "64",+ "60",0],"vae": [- "29",+ "20",0]},@@ -1105,14 +1023,14 @@"title": "Decode Video"}},- "66": {+ "62": {"inputs": {"samples": [- "64",+ "60",0],"vae": [- "30",+ "21",0]},@@ -1121,25 +1039,25 @@"title": "Decode Audio"}},- "67": {+ "63": {"inputs": {"trim_frames": [- "61",+ "57",1],"fps": 24,"match_tail": true,"audio_trim_mode": "sync_with_video","images": [- "65",+ "61",0],"audio": [- "66",+ "62",0],"state": [- "38",+ "29",0]},@@ -1148,26 +1066,26 @@"title": "Trim Overlap"}},- "68": {+ "64": {"inputs": {"state": [- "38",+ "29",0],"images": [- "67",+ "63",0],"sampled_latent": [- "64",+ "60",0],"audio": [- "67",+ "63",1],"images_with_overlap": [- "67",+ "63",2]},@@ -1176,7 +1094,7 @@"title": "Save Clip + Checkpoint"}},- "69": {+ "65": {"inputs": {"enabled": false,"play_notification_sound": false,@@ -1187,15 +1105,15 @@"candidate_count": 1,"review_each_candidate": false,"state": [- "38",+ "29",0],"segment": [- "68",+ "64",0],"audio": [- "67",+ "63",1]},@@ -1204,28 +1122,28 @@"title": "Review (off = no pause)"}},- "70": {+ "66": {"inputs": {"between_scene_cleanup": "off","execution_mode": "recursive","flow": [- "37",+ "28",0],"state": [- "38",+ "29",0],"images": [- "67",+ "63",0],"sampled_latent": [- "64",+ "60",0],"segment": [- "69",+ "65",0]},@@ -1234,7 +1152,7 @@"title": "Loop End"}},- "71": {+ "67": {"inputs": {"audio_source": "source","filename": "swap_%date:yyyy-MM-dd%",@@ -1247,7 +1165,7 @@"delete_checkpoints_after_assembly": false,"generated_audio_join": "av_overlap","manifest": [- "70",+ "66",0]},