Skip to content

One-click character swap for videos: an open-source, local Higgsfield Genjutsu alternative built on ComfyUI and MiniMax H3, with FLUX.3 Klein relighting.

Add Fix faces post-processing mode

D3voz53573736a61e
diff --git a/README.md b/README.md
index d824eef..ae0e5b7 100644
--- a/README.md
+++ b/README.md
@@ -9,6 +9,7 @@ The app is a small Next.js front end over a ComfyUI workflow. It uses [`@comfyor
- **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**: available. 1–4 characters, each with an optional role; every tracked person is matched to a role per shot, and people without a character stay untouched. Runs `workflows/advanced.api.json`, exported from `H3 One-Click Advanced Swap (DMAD 6 step).json`; **One pass per person** (two characters) runs `workflows/advanced_maxq.api.json`.
- **Object swap**: coming soon.
+- **Fix faces**: available. Post-processing for a finished video: H3 draws faces poorly when the person is small in the frame, so this redraws the face of the person in a photo at close-up size and pastes it back. Runs `workflows/face.api.json`, written by `user/default/openjutsu_face_build.py`.
## Requirements
@@ -26,7 +27,9 @@ Install these into `ComfyUI/custom_nodes` (ComfyUI Manager finds the first three
| [ComfyUI-Fantastic-MiniMaxH3-PromptBuilder](https://github.com/Adudeguyman/ComfyUI-Fantastic-MiniMaxH3-PromptBuilder) | masked video-edit latent |
| [ComfyUI-KJNodes](https://github.com/kijai/ComfyUI-KJNodes) | Grow Mask With Blur |
| [ComfyUI-VideoHelperSuite](https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite) | video loading |
-| `comfyui-h3-oneclick-swap` | swap plan, people and role masks, grey mannequins, track labelling, cut finder, shot list (TODO: link the published pack) |
+| `comfyui-h3-oneclick-swap` | swap plan, people and role masks, grey mannequins, track labelling, cut finder, shot list, face-fix chunks (TODO: link the published pack) |
+| [ComfyUI-H3-FaceRefine](https://github.com/Carasibana/ComfyUI-H3-FaceRefine) | Fix faces: face tracking and cropping, SAM face masks, pasting back |
+| [ComfyUI-Impact-Pack](https://github.com/ltdrdata/ComfyUI-Impact-Pack) | Fix faces: SAM loader |
Restart ComfyUI after installing them.
@@ -40,6 +43,9 @@ Restart ComfyUI after installing them.
| `text_encoders` | `qwen3vl_8b_int8_convrot.safetensors` (describer) |
| `vae` | `minimax_h3_video_vae_int8_convrot.safetensors`, `minimax_h3_audio_vae_fp32.safetensors` |
| `checkpoints` | `sam3.1_multiplex_fp16.safetensors` |
+| `ultralytics/bbox`, `ultralytics/segm` | `face_yolov8m.pt`, `person_yolov8m-seg.pt` ([Bingsu/adetailer](https://huggingface.co/Bingsu/adetailer)), for Fix faces |
+| `sams` | `sam_vit_b_01ec64.pth`, for Fix faces |
+| `insightface/models` | `buffalo_l` (InsightFace downloads it on first use), for Fix faces |
## Run it locally
@@ -78,6 +84,7 @@ A 6 s clip at 480p takes about 6–13 minutes on a 4060 Ti, most of it in H3 sam
- **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. If the character is cut off or too much background changes, set **Mask margin** (Tight, Normal, Loose) and check again; a re-check takes seconds.
- Change the **seed** (under Advanced) for a new take. Running the same inputs again resumes from the last finished clip.
- **Steps**, **Base model** and **LoRAs** (under Advanced) default to the H3 pruned INT8 model with the DMAD speed LoRA at 6 steps. LoRAs apply in order; without a speed LoRA, use 20 steps or more. Check mask ignores them.
+- **Fix faces:** drop the finished video and the photo the person was made from. **Match the photo** redraws the face from the photo: the closest likeness, but H3 makes up the expressions and mouth movements. **Follow the mouth** keeps the video's expressions and mouth movements, with a little less likeness. Only that person's face changes (matched by face identity); faces taller than a fifth of the frame are left alone, and stretches with only such faces are skipped. A 17 s video at 768p (4 chunks) took about 28 minutes on a 4060 Ti, including model loading. The video is read at 24 fps.
- **Advanced mode:** give roles as `the drummer`, optionally with how they look after ` - ` (`the drummer - man in a cap`); the look only helps match people and never reaches H3. **One pass per person** gives each of two characters their own H3 pass with only their photo (about twice the time). Check mask is Simple-only for now.
## How it works
@@ -97,6 +104,8 @@ Each clip, SAM 3.1 tracks everyone at 1008 px (its own working size), and H3 Peo
Advanced mode labels the people before it masks them. Per clip, H3 Track Crops shows each SAM track once per shot (the person alone, and the frame with them boxed) to Qwen3-VL 8B, which names the subject or "other"; H3 Track Roles reads that answer and settles a subject named twice in one shot by colour. H3 Role Mask builds the edit mask from the labelled tracks only, and the shot-list describer sees each labelled person outlined in their subject's colour, so the prompt names the same people the masks do. `lib/advanced.ts` finds nodes by title, drops unused picture branches and, without the hat fix, the hat nodes; the exports are made from `user/default/oneclick_advanced_build.js` with every optional group on.
+Fix faces works on the face, not the frame. H3 Face Track + Crop follows the face of the person in the photo over the whole video (InsightFace picks them out when there are several) and crops it to 512×512, so a face a few dozen pixels tall fills the canvas. H3 Face Fix Chunks splits the crops into independent chunks (6.5 s by default, overlapping by at least 1 s) and outputs them as lists, so ComfyUI runs the H3 nodes once per chunk. Each chunk is a masked edit: only the SAM face mask is regenerated with the photo as reference, while the hair, ears, collar and background around it stay, which keeps the new face from sliding against the head. For Follow the mouth, a blurred copy of the crop is the motion reference. H3 Face Fix Join crossfades the chunk overlaps and lowers the per-frame paste weight where the face is large, and H3 Face Stitch pastes the face back through a slightly smaller mask with the original soundtrack. The chunks are not chained through the context loop: each one starts from the swap's own frames, so colours do not drift. `lib/face.ts` removes the blurred face for Match the photo and sets the seed and chunk length.
+
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 Platform
diff --git a/app/api/jobs/route.ts b/app/api/jobs/route.ts
index a12cdc4..23370f5 100644
--- a/app/api/jobs/route.ts
+++ b/app/api/jobs/route.ts
@@ -1,5 +1,6 @@
import { NextResponse } from "next/server";
-import { listModels, submitAdvanced, submitMask, submitSimple } from "../../../lib/comfy.ts";
+import { listModels, submitAdvanced, submitFace, submitMask, submitSimple } from "../../../lib/comfy.ts";
+import { CHUNK_SECONDS, FACE_STYLES, type FaceSettings, type FaceStyle } from "../../../lib/face.ts";
import { MAX_CHARACTERS } from "../../../lib/advanced.ts";
import { MAX_LORAS, STEPS, STRENGTH, type ModelSettings } from "../../../lib/model.ts";
import { CLIP_SECONDS, DEFAULT_TARGET, MARGINS, MAX_SEED, RESOLUTIONS, type Margin, type Resolution, type SimpleSettings } from "../../../lib/simple.ts";
@@ -55,6 +56,18 @@ function parseModel(form: FormData, available: { models: string[]; loras: string
return { steps, model, loras };
}
+function parseFace(form: FormData) {
+ const picture = parsePicture(form.get("picture"));
+ const style = String(form.get("style"));
+ if (!FACE_STYLES.includes(style as FaceStyle)) throw new Error("Choose Match the photo or Follow the mouth.");
+ const seed = Number(form.get("seed"));
+ if (!Number.isInteger(seed) || seed < 0 || seed > MAX_SEED) throw new Error(`Seed must be a whole number from 0 to ${MAX_SEED}.`);
+ const chunkSeconds = Number(form.get("clip_seconds"));
+ if (!(chunkSeconds >= CHUNK_SECONDS.min && chunkSeconds <= CHUNK_SECONDS.max)) throw new Error(`Chunk length must be ${CHUNK_SECONDS.min}-${CHUNK_SECONDS.max} s.`);
+ const settings: FaceSettings = { style: style as FaceStyle, seed, chunkSeconds };
+ return { picture, settings };
+}
+
function parseSimple(form: FormData) {
const picture = parsePicture(form.get("picture"));
const settings: SimpleSettings = { role: String(form.get("role") ?? "").slice(0, 200), ...parseRun(form) };
@@ -87,6 +100,10 @@ export async function POST(request: Request) {
const { pictures, maxQuality, settings } = parseAdvanced(form);
const model = parseModel(form, await listModels());
submit = () => submitAdvanced(video, pictures, settings, maxQuality, model);
+ } else if (mode === "face") {
+ const { picture, settings } = parseFace(form);
+ const model = parseModel(form, await listModels());
+ submit = () => submitFace(video, picture, settings, model);
} else {
throw new Error("Unknown mode.");
}
diff --git a/app/globals.css b/app/globals.css
index e65e22e..5991149 100644
--- a/app/globals.css
+++ b/app/globals.css
@@ -36,7 +36,7 @@ small { color: var(--muted); font-size: 0.82em; }
h1 { margin: 0; font-size: 28px; letter-spacing: -0.02em; }
.top p { margin: 0; color: var(--muted); }
-.modes { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
+.modes { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; }
.mode {
text-align: left; padding: 14px 16px; border-radius: 14px; border: 1px solid var(--line);
background: var(--panel); display: grid; gap: 2px; align-content: start;
diff --git a/components/openjutsu.tsx b/components/openjutsu.tsx
index 0e19de1..f2e94d2 100644
--- a/components/openjutsu.tsx
+++ b/components/openjutsu.tsx
@@ -7,12 +7,14 @@ import { clipCount, clipStarts } from "../lib/clips.ts";
import { CLIP_SECONDS, DEFAULT_TARGET, MARGINS, MAX_SEED, RESOLUTIONS, type Margin, type Resolution } from "../lib/simple.ts";
import { MAX_CHARACTERS } from "../lib/advanced.ts";
import { DEFAULT_MODEL, MAX_LORAS, STEPS, STRENGTH, type Lora } from "../lib/model.ts";
+import { CHUNK_SECONDS, faceChunkCount, type FaceStyle } from "../lib/face.ts";
type Character = { file: File; url: string; role: string };
-type Mode = "simple" | "advanced";
-type Kind = "simple" | "mask" | "advanced" | "advanced_maxq";
+type Mode = "simple" | "advanced" | "face";
+type Kind = "simple" | "mask" | "advanced" | "advanced_maxq" | "face";
type Run = { id: string; kind: Kind; margin: Margin; clips: number; clipSeconds: number; startedAt: number };
-type Progress = NodeInfo & { step: number | null; steps: number | null };
+// pass counts the sampler runs started so far: Fix faces samples its chunks one after another in the same node.
+type Progress = NodeInfo & { step: number | null; steps: number | null; pass: number };
const TERMINAL = new Set(["succeeded", "failed", "canceled", "expired"]);
const RUN_KEY = "openjutsu.run";
@@ -21,8 +23,14 @@ const MODES = [
{ 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: true },
{ id: "object", title: "Object swap", text: "Replace a prop or product instead of a person.", ready: false },
+ { id: "face", title: "Fix faces", text: "Post-processing: redraw a person's face in a finished video from their photo.", ready: true },
] as const;
+const FACE_STYLE_TEXT: Record<FaceStyle, { label: string; hint: string }> = {
+ photo: { label: "Match the photo", hint: "The face is redrawn from the photo: the closest likeness, but H3 makes up its own expressions and mouth movements." },
+ mouth: { label: "Follow the mouth", hint: "The face follows the video's expressions and mouth movements; a little less like the photo." },
+};
+
function readRun(): Run | null {
try {
return JSON.parse(localStorage.getItem(RUN_KEY) ?? "null");
@@ -106,6 +114,8 @@ export function Openjutsu() {
const [hatFix, setHatFix] = useState(false);
const [margin, setMargin] = useState<Margin>("normal");
const [target, setTarget] = useState(DEFAULT_TARGET);
+ const [faceStyle, setFaceStyle] = useState<FaceStyle>("photo");
+ const [chunkSeconds, setChunkSeconds] = useState(CHUNK_SECONDS.default);
const [seed, setSeed] = useState(0);
const [clipSeconds, setClipSeconds] = useState(CLIP_SECONDS.default);
const [steps, setSteps] = useState(DEFAULT_MODEL.steps);
@@ -140,7 +150,10 @@ export function Openjutsu() {
} else if (event.type === "status") {
setJob((current) => current && { ...current, status: event.status, queuePosition: event.queuePosition });
} else if (event.type === "progress" && event.node) {
- setProgress({ ...event.node, step: event.step, steps: event.steps });
+ setProgress((last) => {
+ const again = event.node.classType === "SamplerCustomAdvanced" && (last?.classType !== "SamplerCustomAdvanced" || (event.step ?? 0) < (last.step ?? 0));
+ return { ...event.node, step: event.step, steps: event.steps, pass: (last?.pass ?? 0) + (again ? 1 : 0) };
+ });
} else if (event.type === "preview") {
setPreview(event.url);
} else if (event.type === "error") {
@@ -169,15 +182,16 @@ export function Openjutsu() {
probe.src = url;
}
- // Simple mode uses only the first character; the others are kept for switching back.
- const limit = mode === "simple" ? 1 : MAX_CHARACTERS;
+ // Simple mode and Fix faces use only the first character; the others are kept for switching back.
+ const single = mode === "simple" || mode === "face";
+ const limit = single ? 1 : MAX_CHARACTERS;
const shown = characters.slice(0, limit);
const character = characters[0] ?? null;
const onePassEach = mode === "advanced" && maxQuality && shown.length === 2;
function addCharacters(files: File[]) {
if (!files.length) return;
- if (mode === "simple" && character) {
+ if (single && character) {
URL.revokeObjectURL(character.url);
setCharacters([{ file: files[0], url: URL.createObjectURL(files[0]), role: character.role }, ...characters.slice(1)]);
return;
@@ -195,7 +209,7 @@ export function Openjutsu() {
setCharacters(characters.map((c, i) => (i === index ? { ...c, role } : c)));
}
- const clips = video?.duration ? clipCount(video.duration, clipSeconds) : 0;
+ const clips = !video?.duration ? 0 : mode === "face" ? faceChunkCount(video.duration, chunkSeconds) : clipCount(video.duration, clipSeconds);
async function submit(kind: Kind) {
if (!video || (kind !== "mask" && !character)) return;
@@ -225,6 +239,12 @@ export function Openjutsu() {
form.set("seed", String(seed));
form.set("clip_seconds", String(clipSeconds));
}
+ if (kind === "face" && character) {
+ form.set("picture", character.file);
+ form.set("style", faceStyle);
+ form.set("seed", String(seed));
+ form.set("clip_seconds", String(chunkSeconds));
+ }
if (kind !== "mask") {
form.set("steps", String(steps));
form.set("model", model);
@@ -237,7 +257,7 @@ export function Openjutsu() {
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: Run = { id: body.id, kind, margin, clips: Math.max(clips, 1), clipSeconds, startedAt: Date.now() };
+ const next: Run = { id: body.id, kind, margin, clips: Math.max(clips, 1), clipSeconds: kind === "face" ? chunkSeconds : clipSeconds, startedAt: Date.now() };
writeRun(next);
setJob(body);
setProgress(null);
@@ -319,13 +339,13 @@ export function Openjutsu() {
</div>
<div className="panel">
- <h2><span>2</span> {mode === "simple" ? "Character" : "Characters"}</h2>
+ <h2><span>2</span> {mode === "face" ? "Whose face" : mode === "simple" ? "Character" : "Characters"}</h2>
<div className="characters">
{shown.map((c, i) => (
<div className="character" key={c.url}>
<img src={c.url} alt={`Character ${i + 1}`} />
<button className="remove" onClick={() => removeCharacter(i)} aria-label={`Remove character ${i + 1}`}>×</button>
- <label>
+ {mode !== "face" && <label>
<span>Who do they replace? (optional)</span>
<input
value={c.role}
@@ -333,7 +353,7 @@ export function Openjutsu() {
placeholder={i === 0 ? "e.g. the singer" : "e.g. the drummer"}
onChange={(event) => setRole(i, event.target.value)}
/>
- </label>
+ </label>}
</div>
))}
{shown.length < limit && (
@@ -343,7 +363,17 @@ export function Openjutsu() {
</DropZone>
)}
</div>
- {mode === "simple" ? (
+ {mode === "face" ? (<>
+ <div className="segmented">
+ {(Object.keys(FACE_STYLE_TEXT) as FaceStyle[]).map((f) => (
+ <button key={f} className={f === faceStyle ? "on" : ""} onClick={() => setFaceStyle(f)}>{FACE_STYLE_TEXT[f].label}</button>
+ ))}
+ </div>
+ <p className="hint">
+ {FACE_STYLE_TEXT[faceStyle].hint} Use the photo the video was made with. Only that person&apos;s face changes; faces
+ taller than a fifth of the frame are already sharp and are left alone.
+ </p>
+ </>) : mode === "simple" ? (
<p className="hint">
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 (&ldquo;the singer&rdquo;), not clothes.
@@ -361,25 +391,25 @@ export function Openjutsu() {
<section className="panel settings">
<h2><span>3</span> Settings</h2>
- <div className="setting">
+ {mode !== "face" && <div className="setting">
<span>Resolution</span>
<div className="segmented">
{RESOLUTIONS.map((r) => (
<button key={r} className={r === resolution ? "on" : ""} onClick={() => setResolution(r)}>{r}</button>
))}
</div>
- </div>
+ </div>}
{mode === "simple" && (
<div className="setting">
<span>What to replace <small>What SAM tracks, in English: person, cat, dog, or a short description such as “black and white cat”. The biggest match is replaced.</small></span>
<input className="target-input" aria-label="What to replace" placeholder={DEFAULT_TARGET} value={target} onChange={(event) => setTarget(event.target.value)} />
</div>
)}
- <label className="setting toggle">
+ {mode !== "face" && <label className="setting toggle">
<span>Hat fix <small>Also replaces hats{mode === "advanced" ? " worn by the people being replaced" : ""} (about 45 s more per clip).</small></span>
<input type="checkbox" checked={hatFix} onChange={(event) => setHatFix(event.target.checked)} />
<i aria-hidden />
- </label>
+ </label>}
{mode === "advanced" && (
<label className="setting toggle">
<span>One pass per person <small>{shown.length === 2 ? "Each character gets their own H3 pass with only their photo. About twice the time." : "Needs exactly two characters."}</small></span>
@@ -387,10 +417,10 @@ export function Openjutsu() {
<i aria-hidden />
</label>
)}
- <div className="setting">
+ {mode !== "face" && <div className="setting">
<span>Mask margin <small>Room around the person for a differently built character.{mode === "simple" ? " Check mask shows it." : ""}</small></span>
<MarginPicker value={margin} onChange={setMargin} />
- </div>
+ </div>}
<details>
<summary>Advanced</summary>
<div className="setting">
@@ -400,10 +430,17 @@ export function Openjutsu() {
<button onClick={() => setSeed(Math.floor(Math.random() * MAX_SEED))} aria-label="Random seed">🎲</button>
</div>
</div>
- <div className="setting">
- <span>Clip length <small>{clipSeconds.toFixed(1)} s per H3 generation</small></span>
- <input type="range" min={CLIP_SECONDS.min} max={CLIP_SECONDS.max} step={0.5} value={clipSeconds} onChange={(event) => setClipSeconds(Number(event.target.value))} />
- </div>
+ {mode === "face" ? (
+ <div className="setting">
+ <span>Chunk length <small>{chunkSeconds.toFixed(1)} s of face per H3 generation; chunks overlap by 1 s and are crossfaded.</small></span>
+ <input type="range" min={CHUNK_SECONDS.min} max={CHUNK_SECONDS.max} step={0.5} value={chunkSeconds} onChange={(event) => setChunkSeconds(Number(event.target.value))} />
+ </div>
+ ) : (
+ <div className="setting">
+ <span>Clip length <small>{clipSeconds.toFixed(1)} s per H3 generation</small></span>
+ <input type="range" min={CLIP_SECONDS.min} max={CLIP_SECONDS.max} step={0.5} value={clipSeconds} onChange={(event) => setClipSeconds(Number(event.target.value))} />
+ </div>
+ )}
<div className="setting">
<span>Steps <small>6 with the DMAD speed LoRA; without a speed LoRA, 20 or more.</small></span>
<input
@@ -440,11 +477,13 @@ export function Openjutsu() {
{formError && <p className="error">{formError}</p>}
<div className="row">
{mode === "simple" && <button className="secondary" disabled={!video || submitting} onClick={() => submit("mask")}>Check mask</button>}
- <button className="primary" disabled={!video || !character || submitting} onClick={() => submit(mode === "simple" ? "simple" : onePassEach ? "advanced_maxq" : "advanced")}>
+ <button className="primary" disabled={!video || !character || submitting} onClick={() => submit(mode === "face" ? "face" : mode === "simple" ? "simple" : onePassEach ? "advanced_maxq" : "advanced")}>
{submitting ? "Uploading…" : "Generate"}
</button>
</div>
- <small>{clips ? `${clips} clip${clips > 1 ? "s" : ""} at ${resolution}` : `Add a video and ${mode === "simple" ? "a character photo" : "character photos"}.`}</small>
+ <small>{clips
+ ? mode === "face" ? `Up to ${clips} chunk${clips > 1 ? "s" : ""} of face` : `${clips} clip${clips > 1 ? "s" : ""} at ${resolution}`
+ : `Add a video and ${mode === "face" ? "the photo of the person" : mode === "simple" ? "a character photo" : "character photos"}.`}</small>
</div>
</>
)}
@@ -476,7 +515,7 @@ function RunView({ run, job, progress, preview, streamError, now, onCancel, onRe
<video src={job.video.url} controls autoPlay playsInline />
<div className="row">
<a className="primary" href={`${job.video.url}?download`} download={job.video.name}>Download MP4</a>
- <button className="secondary" onClick={onReset}>New swap</button>
+ <button className="secondary" onClick={onReset}>{run.kind === "face" ? "Fix another" : "New swap"}</button>
</div>
</section>
);
@@ -487,21 +526,27 @@ function RunView({ run, job, progress, preview, streamError, now, onCancel, onRe
<section className="panel">
<h2>{status === "canceled" ? "Canceled" : status === "succeeded" ? "Finished without a video" : status === "expired" ? "Job no longer available" : "Something went wrong"}</h2>
{job?.error && <p className="error">{job.error}</p>}
- {status === "expired" && <p className="hint">ComfyUI no longer knows this job, for example after a restart. Finished videos are in ComfyUI&apos;s output/h3_oneclick_swap folder.</p>}
+ {status === "expired" && <p className="hint">ComfyUI no longer knows this job, for example after a restart. Finished videos are in ComfyUI&apos;s output/{run.kind === "face" ? "openjutsu_face" : "h3_oneclick_swap"} folder.</p>}
<button className="secondary" onClick={onReset}>Back</button>
</section>
);
}
+ const face = run.kind === "face";
+ const sampling = progress?.classType === "SamplerCustomAdvanced";
+ const chunk = Math.min(progress?.pass ?? 0, run.clips);
let fraction = 0;
- if (mask) fraction = progress?.classType === "SAM3_VideoTrack" && progress.steps ? (progress.step ?? 0) / progress.steps : 0;
+ if (face) fraction = sampling ? 0.1 + 0.85 * (chunk - 1 + (progress!.steps ? (progress!.step ?? 0) / progress!.steps : 0)) / run.clips : chunk ? 0.97 : 0.05;
+ else 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})` : ""}` : mask ? "Checking the mask" : progress?.clip ? `Clip ${progress.clip} of ${clips}` : "Preparing"}</h2>
+ <h2>{status === "queued" ? `Queued${job?.queuePosition ? ` (#${job.queuePosition})` : ""}` : mask ? "Checking the mask"
+ : face ? (sampling ? `Chunk ${chunk} of up to ${run.clips}` : chunk ? "Pasting the face back" : "Tracking the face")
+ : 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>
@@ -511,7 +556,7 @@ 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">{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>
+ <p className="hint">{mask ? "SAM tracks the whole video once, about a minute per 3 s of video." : face ? "The face is tracked over the whole video, then each chunk is regenerated; nothing is saved until the end." : "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>
);
diff --git a/lib/comfy.ts b/lib/comfy.ts
index 00092ff..af5d464 100644
--- a/lib/comfy.ts
+++ b/lib/comfy.ts
@@ -5,6 +5,7 @@ import { ComfyLow } from "@comfyorg/sdk/low";
import { MASK_NODES, NODES, pruneMask, pruneSimple, type ApiGraph, type Margin, type SimpleSettings } from "./simple.ts";
import { VIDEO, nodeByTitle, pruneAdvanced, type AdvancedSettings } from "./advanced.ts";
import { applyModel, type ModelSettings } from "./model.ts";
+import { FACE_PICTURE, FACE_VIDEO, pruneFace, type FaceSettings } from "./face.ts";
export type PublicJob = {
id: string;
@@ -33,7 +34,7 @@ export function rawJobEvents(job: Job, signal: AbortSignal) {
return low().getJobEvents(job.urls.events || job.id, { signal });
}
-export const JOB_KINDS = ["simple", "mask", "advanced", "advanced_maxq"] as const;
+export const JOB_KINDS = ["simple", "mask", "advanced", "advanced_maxq", "face"] as const;
export type JobKind = (typeof JOB_KINDS)[number];
export async function loadGraph(kind: JobKind): Promise<ApiGraph> {
@@ -89,6 +90,16 @@ export async function submitAdvanced(video: File, pictures: File[], settings: Ad
return publicJob(await comfy.submit(workflow));
}
+export async function submitFace(video: File, picture: File, settings: FaceSettings, model: ModelSettings) {
+ const comfy = client();
+ const graph = pruneFace(await loadGraph("face"), settings);
+ applyModel(graph, model);
+ const workflow = comfy.workflows.fromJson(graph);
+ workflow.setInput(nodeByTitle(graph, FACE_VIDEO), "video", await upload(comfy, video));
+ workflow.setInput(nodeByTitle(graph, FACE_PICTURE), "image", await upload(comfy, picture));
+ return publicJob(await comfy.submit(workflow));
+}
+
export async function submitMask(video: File, hatFix: boolean, margin: Margin, target: string) {
const comfy = client();
const workflow = comfy.workflows.fromJson(pruneMask(await loadGraph("mask"), hatFix, margin, target));
diff --git a/lib/face.ts b/lib/face.ts
new file mode 100644
index 0000000..08f0fa1
--- /dev/null
+++ b/lib/face.ts
@@ -0,0 +1,39 @@
+// Fix faces: post-processing for a finished video. The face of the person in the picture is regenerated by H3 in
+// independent overlapping chunks, crossfaded and pasted back; faces that already fill the frame are left alone.
+// workflows/face.api.json is written by ComfyUI user/default/openjutsu_face_build.py with Follow the mouth on;
+// each request prunes it. Nodes are found by title.
+import { nodeByTitle } from "./advanced.ts";
+import type { ApiGraph } from "./simple.ts";
+
+export const FACE_STYLES = ["photo", "mouth"] as const;
+export type FaceStyle = (typeof FACE_STYLES)[number];
+
+export type FaceSettings = { style: FaceStyle; seed: number; chunkSeconds: number };
+
+export const FACE_VIDEO = "Video to fix";
+export const FACE_PICTURE = "Picture 1";
+export const CHUNK_SECONDS = { min: 2.5, max: 15, default: 6.5 };
+
+// Mirrors H3FaceChunks in the swap pack, before chunks with only close-ups are dropped.
+const FPS = 24;
+const OVERLAP = 24;
+export function faceChunkCount(durationSeconds: number, chunkSeconds: number) {
+ const total = Math.floor(durationSeconds * FPS);
+ const length = Math.floor((Math.floor(chunkSeconds * FPS) - 5) / 17) * 17 + 5;
+ return total <= length ? 1 : Math.ceil((total - OVERLAP) / (length - OVERLAP));
+}
+
+export function pruneFace(source: ApiGraph, settings: FaceSettings): ApiGraph {
+ const graph: ApiGraph = structuredClone(source);
+ const id = (title: string) => nodeByTitle(graph, title);
+ const chunks = graph[id("Face Fix Chunks")].inputs;
+ // Match the photo: no blurred face to follow, so H3 draws the expressions and mouth anew from the picture.
+ if (settings.style === "photo") {
+ delete graph[id("Blurred face (follow the mouth)")];
+ delete chunks.follow_mouth;
+ delete graph[id("Reference Conditioning")].inputs["ref_videos.ref_video_0"];
+ }
+ chunks.chunk_seconds = settings.chunkSeconds;
+ graph[id("Seed")].inputs.noise_seed = settings.seed;
+ return graph;
+}
diff --git a/lib/model.ts b/lib/model.ts
index 898a0e7..a99a480 100644
--- a/lib/model.ts
+++ b/lib/model.ts
@@ -15,11 +15,12 @@ export const MAX_LORAS = 4;
export const STEPS = { min: 1, max: 100 };
export const STRENGTH = { min: -4, max: 4 };
-// Mutates graph: the Swap Plan's steps, the chosen diffusion model, then the LoRAs in order into whatever read the old LoRA node.
+// Mutates graph: the steps (on the Swap Plan, or the Schedule in Fix faces, which has no plan), the chosen diffusion model,
+// then the LoRAs in order into whatever read the old LoRA node.
export function applyModel(graph: ApiGraph, settings: ModelSettings) {
const plans = Object.values(graph).filter((node) => node.class_type === "H3OneClickSwapPlan" || node.class_type === "H3AdvancedSwapPlan");
- if (plans.length !== 1) throw new Error(`Expected one Swap Plan node in the workflow, found ${plans.length}.`);
- plans[0].inputs.steps = settings.steps;
+ if (plans.length > 1) throw new Error(`Expected one Swap Plan node in the workflow, found ${plans.length}.`);
+ (plans[0] ?? graph[nodeByTitle(graph, "Schedule")]).inputs.steps = settings.steps;
const unet = nodeByTitle(graph, "H3 Diffusion Model");
const lora = nodeByTitle(graph, "DMAD LoRA");
graph[unet].inputs.unet_name = settings.model;
diff --git a/test/face.test.ts b/test/face.test.ts
new file mode 100644
index 0000000..0aac212
--- /dev/null
+++ b/test/face.test.ts
@@ -0,0 +1,52 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { nodeByTitle } from "../lib/advanced.ts";
+import { FACE_PICTURE, FACE_VIDEO, faceChunkCount, pruneFace, type FaceSettings } from "../lib/face.ts";
+import { applyModel, DEFAULT_MODEL } from "../lib/model.ts";
+import { isLink, type ApiGraph } from "../lib/simple.ts";
+
+const graph: ApiGraph = JSON.parse(readFileSync(new URL("../workflows/face.api.json", import.meta.url), "utf8"));
+const settings = (style: FaceSettings["style"]): FaceSettings => ({ style, seed: 7, chunkSeconds: 5 });
+const dangling = (g: ApiGraph) => Object.entries(g).flatMap(([id, node]) =>
+ Object.entries(node.inputs).filter(([, v]) => isLink(v) && !g[v[0]]).map(([name]) => `${id}.${name}`));
+const node = (g: ApiGraph, title: string) => g[nodeByTitle(g, title)];
+
+test("the export has the video, the picture and Follow the mouth on", () => {
+ assert.equal(node(graph, FACE_VIDEO).class_type, "VHS_LoadVideo");
+ assert.equal(node(graph, FACE_PICTURE).class_type, "LoadImage");
+ assert.ok(node(graph, "Face Fix Chunks").inputs.follow_mouth);
+ assert.ok(node(graph, "Reference Conditioning").inputs["ref_videos.ref_video_0"]);
+});
+
+test("Follow the mouth keeps the graph and sets the seed and chunk length", () => {
+ const pruned = pruneFace(graph, settings("mouth"));
+ assert.equal(Object.keys(pruned).length, Object.keys(graph).length);
+ assert.equal(node(pruned, "Seed").inputs.noise_seed, 7);
+ assert.equal(node(pruned, "Face Fix Chunks").inputs.chunk_seconds, 5);
+ assert.equal(node(graph, "Seed").inputs.noise_seed, 0, "the source graph is not modified");
+});
+
+test("Match the photo drops the blurred face and the motion reference", () => {
+ const pruned = pruneFace(graph, settings("photo"));
+ assert.deepEqual(dangling(pruned), []);
+ assert.equal(Object.keys(pruned).length, Object.keys(graph).length - 1);
+ assert.equal(node(pruned, "Face Fix Chunks").inputs.follow_mouth, undefined);
+ const ref = node(pruned, "Reference Conditioning").inputs;
+ assert.deepEqual(Object.keys(ref).filter((name) => name.startsWith("ref_")), ["ref_image_size", "ref_images.ref_image_0"]);
+});
+
+test("the steps go to the Schedule and the LoRAs into the sampler model", () => {
+ const pruned = pruneFace(graph, settings("photo"));
+ applyModel(pruned, { ...DEFAULT_MODEL, steps: 9, loras: [] });
+ assert.equal(node(pruned, "Schedule").inputs.steps, 9);
+ assert.deepEqual(node(pruned, "Comfy Kitchen Attention").inputs.model, [nodeByTitle(pruned, "H3 Diffusion Model"), 0]);
+ assert.deepEqual(dangling(pruned), []);
+});
+
+test("chunk count mirrors H3 Face Fix Chunks", () => {
+ // 413 frames, 6.5 s chunks of 141 frames overlapping by at least 24: 4 chunks; a short video is one chunk
+ assert.equal(faceChunkCount(413 / 24, 6.5), 4);
+ assert.equal(faceChunkCount(413 / 24, 6.6), 3);
+ assert.equal(faceChunkCount(4, 6.5), 1);
+});
diff --git a/workflows/face.api.json b/workflows/face.api.json
new file mode 100644
index 0000000..b592b77
--- /dev/null
+++ b/workflows/face.api.json
@@ -0,0 +1,571 @@
+{
+ "1": {
+ "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"
+ },
+ "class_type": "VHS_LoadVideo",
+ "_meta": {
+ "title": "Video to fix"
+ }
+ },
+ "2": {
+ "inputs": {
+ "image": ""
+ },
+ "class_type": "LoadImage",
+ "_meta": {
+ "title": "Picture 1"
+ }
+ },
+ "3": {
+ "inputs": {
+ "upscale_method": "area",
+ "largest_size": 768,
+ "image": [
+ "2",
+ 0
+ ]
+ },
+ "class_type": "ImageScaleToMaxDimension",
+ "_meta": {
+ "title": "Shrink for the describer"
+ }
+ },
+ "4": {
+ "inputs": {
+ "clip_name": "qwen3vl_8b_int8_convrot.safetensors",
+ "type": "stable_diffusion",
+ "device": "default"
+ },
+ "class_type": "CLIPLoader",
+ "_meta": {
+ "title": "Describer: Qwen3-VL 8B"
+ }
+ },
+ "5": {
+ "inputs": {
+ "prompt": "Describe this person's face for a casting sheet, in one sentence of about 30 words: apparent age and gender, face shape, skin tone, eyebrows, facial hair and any glasses. No preamble, no clothing, no background.",
+ "max_length": 90,
+ "sampling_mode": "off",
+ "thinking": false,
+ "use_default_template": true,
+ "mtp": "auto",
+ "clip": [
+ "4",
+ 0
+ ],
+ "image": [
+ "3",
+ 0
+ ]
+ },
+ "class_type": "TextGenerate",
+ "_meta": {
+ "title": "Describe the face in picture 1"
+ }
+ },
+ "6": {
+ "inputs": {
+ "images": [
+ "1",
+ 0
+ ],
+ "identity_reference": [
+ "2",
+ 0
+ ],
+ "fallback_detector": "segm\\person_yolov8m-seg.pt",
+ "detector": "bbox\\face_yolov8m.pt",
+ "confidence": 0.35,
+ "crop_factor": 2.5,
+ "canvas_width": 512,
+ "canvas_height": 512,
+ "canvas_mode": "manual",
+ "smooth_window": 21,
+ "size_smooth_window": 51,
+ "smooth_method": "gaussian",
+ "size_mode": "per_frame",
+ "identity_track": true,
+ "identity_threshold": 0.28,
+ "select": "largest",
+ "fallback_head_frac": 0.5
+ },
+ "class_type": "H3FaceTrackCrop",
+ "_meta": {
+ "title": "Track + crop the face"
+ }
+ },
+ "7": {
+ "inputs": {
+ "images": [
+ "2",
+ 0
+ ],
+ "fallback_detector": "none",
+ "detector": "bbox\\face_yolov8m.pt",
+ "confidence": 0.35,
+ "crop_factor": 2.5,
+ "canvas_width": 512,
+ "canvas_height": 512,
+ "canvas_mode": "manual",
+ "smooth_window": 21,
+ "size_smooth_window": 51,
+ "smooth_method": "gaussian",
+ "size_mode": "per_frame",
+ "identity_track": true,
+ "identity_threshold": 0.28,
+ "select": "largest",
+ "fallback_head_frac": 0.5
+ },
+ "class_type": "H3FaceTrackCrop",
+ "_meta": {
+ "title": "Face from picture 1"
+ }
+ },
+ "8": {
+ "inputs": {
+ "model_name": "sam_vit_b_01ec64.pth",
+ "device_mode": "AUTO"
+ },
+ "class_type": "SAMLoader",
+ "_meta": {
+ "title": "SAM (face masks)"
+ }
+ },
+ "9": {
+ "inputs": {
+ "crops": [
+ "6",
+ 0
+ ],
+ "sam_model": [
+ "8",
+ 0
+ ],
+ "transform": [
+ "6",
+ 1
+ ],
+ "threshold": 0.93,
+ "dilation": 24,
+ "temporal_smooth": 5
+ },
+ "class_type": "H3FaceMaskSAM",
+ "_meta": {
+ "title": "Face mask (regenerated)"
+ }
+ },
+ "10": {
+ "inputs": {
+ "crops": [
+ "6",
+ 0
+ ],
+ "sam_model": [
+ "8",
+ 0
+ ],
+ "transform": [
+ "6",
+ 1
+ ],
+ "threshold": 0.93,
+ "dilation": 8,
+ "temporal_smooth": 5
+ },
+ "class_type": "H3FaceMaskSAM",
+ "_meta": {
+ "title": "Face mask (pasted back)"
+ }
+ },
+ "11": {
+ "inputs": {
+ "image": [
+ "6",
+ 0
+ ],
+ "blur_radius": 9,
+ "sigma": 3.0
+ },
+ "class_type": "ImageBlur",
+ "_meta": {
+ "title": "Blurred face (follow the mouth)"
+ }
+ },
+ "12": {
+ "inputs": {
+ "crops": [
+ "6",
+ 0
+ ],
+ "masks": [
+ "9",
+ 0
+ ],
+ "audio": [
+ "1",
+ 2
+ ],
+ "transform": [
+ "6",
+ 1
+ ],
+ "chunk_seconds": 6.5,
+ "skip_faces_above": 0.2,
+ "follow_mouth": [
+ "11",
+ 0
+ ],
+ "picture_text": [
+ "5",
+ 0
+ ]
+ },
+ "class_type": "H3FaceChunks",
+ "_meta": {
+ "title": "Face Fix Chunks"
+ }
+ },
+ "13": {
+ "inputs": {
+ "unet_name": "minimax_h3_ref2va_pruned_int8_convrot.safetensors",
+ "weight_dtype": "default"
+ },
+ "class_type": "UNETLoader",
+ "_meta": {
+ "title": "H3 Diffusion Model"
+ }
+ },
+ "14": {
+ "inputs": {
+ "lora_name": "minimax_h3_DMAD_4step_full_lora_avg_rank_39_bf16.safetensors",
+ "strength_model": 1,
+ "model": [
+ "13",
+ 0
+ ]
+ },
+ "class_type": "LoraLoaderModelOnly",
+ "_meta": {
+ "title": "DMAD LoRA"
+ }
+ },
+ "15": {
+ "inputs": {
+ "attention": "comfy kitchen attention",
+ "model": [
+ "14",
+ 0
+ ]
+ },
+ "class_type": "ModelAttentionBackend",
+ "_meta": {
+ "title": "Comfy Kitchen Attention"
+ }
+ },
+ "16": {
+ "inputs": {
+ "clip_name": "qwen3vl_32b_minimax_h3_int4_convrot.safetensors",
+ "type": "minimax",
+ "device": "default"
+ },
+ "class_type": "CLIPLoader",
+ "_meta": {
+ "title": "H3 Text Encoder"
+ }
+ },
+ "17": {
+ "inputs": {
+ "vae_name": "minimax_h3_video_vae_int8_convrot.safetensors"
+ },
+ "class_type": "VAELoader",
+ "_meta": {
+ "title": "Video VAE"
+ }
+ },
+ "18": {
+ "inputs": {
+ "vae_name": "minimax_h3_audio_vae_fp32.safetensors"
+ },
+ "class_type": "VAELoader",
+ "_meta": {
+ "title": "Audio VAE"
+ }
+ },
+ "19": {
+ "inputs": {
+ "grow": 0,
+ "keep_audio": true,
+ "megapixels": 0,
+ "vae": [
+ "17",
+ 0
+ ],
+ "images": [
+ "12",
+ 0
+ ],
+ "mask": [
+ "12",
+ 1
+ ],
+ "audio_vae": [
+ "18",
+ 0
+ ],
+ "audio": [
+ "12",
+ 3
+ ]
+ },
+ "class_type": "MiniMaxH3FantasticVideoEditLatent",
+ "_meta": {
+ "title": "Edit latent (face + audio)"
+ }
+ },
+ "20": {
+ "inputs": {
+ "mask_meaning": "white = generate",
+ "audio_mode": "preserve source audio",
+ "mask_conversion": "H3 exact (causal/token max)",
+ "target_latent": [
+ "19",
+ 0
+ ],
+ "mask": [
+ "12",
+ 1
+ ]
+ },
+ "class_type": "MiniMaxH3ContexMaskedTarget",
+ "_meta": {
+ "title": "Masked target"
+ }
+ },
+ "21": {
+ "inputs": {
+ "prompt": [
+ "12",
+ 4
+ ],
+ "width": [
+ "19",
+ 1
+ ],
+ "height": [
+ "19",
+ 2
+ ],
+ "length": [
+ "19",
+ 3
+ ],
+ "ref_image_size": "match",
+ "clip": [
+ "16",
+ 0
+ ],
+ "vae": [
+ "17",
+ 0
+ ],
+ "audio_vae": [
+ "18",
+ 0
+ ],
+ "ref_images.ref_image_0": [
+ "7",
+ 0
+ ],
+ "ref_videos.ref_video_0": [
+ "12",
+ 2
+ ]
+ },
+ "class_type": "MiniMaxH3ReferenceToVideo",
+ "_meta": {
+ "title": "Reference Conditioning"
+ }
+ },
+ "22": {
+ "inputs": {
+ "model": [
+ "15",
+ 0
+ ],
+ "conditioning": [
+ "21",
+ 0
+ ]
+ },
+ "class_type": "BasicGuider",
+ "_meta": {
+ "title": "Guider"
+ }
+ },
+ "23": {
+ "inputs": {
+ "sampler_name": "euler"
+ },
+ "class_type": "KSamplerSelect",
+ "_meta": {
+ "title": "Sampler"
+ }
+ },
+ "24": {
+ "inputs": {
+ "noise_seed": 0
+ },
+ "class_type": "RandomNoise",
+ "_meta": {
+ "title": "Seed"
+ }
+ },
+ "25": {
+ "inputs": {
+ "scheduler": "simple",
+ "steps": 6,
+ "denoise": 1,
+ "model": [
+ "15",
+ 0
+ ]
+ },
+ "class_type": "BasicScheduler",
+ "_meta": {
+ "title": "Schedule"
+ }
+ },
+ "26": {
+ "inputs": {
+ "noise": [
+ "24",
+ 0
+ ],
+ "guider": [
+ "22",
+ 0
+ ],
+ "sampler": [
+ "23",
+ 0
+ ],
+ "sigmas": [
+ "25",
+ 0
+ ],
+ "latent_image": [
+ "20",
+ 0
+ ]
+ },
+ "class_type": "SamplerCustomAdvanced",
+ "_meta": {
+ "title": "Sample face"
+ }
+ },
+ "27": {
+ "inputs": {
+ "samples": [
+ "26",
+ 0
+ ],
+ "vae": [
+ "17",
+ 0
+ ]
+ },
+ "class_type": "VAEDecode",
+ "_meta": {
+ "title": "Decode face"
+ }
+ },
+ "28": {
+ "inputs": {
+ "images": [
+ "27",
+ 0
+ ],
+ "plan": [
+ "12",
+ 5
+ ],
+ "crops": [
+ "6",
+ 0
+ ],
+ "transform": [
+ "6",
+ 1
+ ]
+ },
+ "class_type": "H3FaceJoin",
+ "_meta": {
+ "title": "Face Fix Join"
+ }
+ },
+ "29": {
+ "inputs": {
+ "paste_region": "face_only",
+ "mask_dilation": 0,
+ "feather": 8,
+ "colour_match": 1.0,
+ "blend": 1.0,
+ "undetected_frames": "fade_out",
+ "feather_scales_with_crop": false,
+ "base_images": [
+ "1",
+ 0
+ ],
+ "refined_crops": [
+ "28",
+ 0
+ ],
+ "transform": [
+ "28",
+ 1
+ ],
+ "masks": [
+ "10",
+ 0
+ ]
+ },
+ "class_type": "H3FaceStitch",
+ "_meta": {
+ "title": "Paste the face back"
+ }
+ },
+ "30": {
+ "inputs": {
+ "frame_rate": 24,
+ "loop_count": 0,
+ "filename_prefix": "openjutsu_face/face",
+ "format": "video/h264-mp4",
+ "pix_fmt": "yuv420p",
+ "crf": 16,
+ "save_metadata": false,
+ "trim_to_audio": false,
+ "pingpong": false,
+ "save_output": true,
+ "images": [
+ "29",
+ 0
+ ],
+ "audio": [
+ "1",
+ 2
+ ]
+ },
+ "class_type": "VHS_VideoCombine",
+ "_meta": {
+ "title": "Fixed video"
+ }
+ }
+}