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 custom resolution an exact width x height
D3vozd049d1b0398a
diff --git a/README.md b/README.mdindex 5942ec5..b686447 100644--- a/README.md+++ b/README.md@@ -75,7 +75,7 @@ On Windows, double-click `start_openjutsu.bat` (ComfyUI must be running, or star`.env.local` sets `COMFY_BASE_URL=http://127.0.0.1:8189`. Leave `COMFY_API_KEY` empty for a local proxy. The base model and LoRA pickers read ComfyUI's model lists from `COMFYUI_URL` (default `http://127.0.0.1:8188`); without it they become text fields.-A 6 s clip at 480p takes about 6–13 minutes on a 4060 Ti, most of it in H3 sampling. 736p is the default; 1080p is about 2.5× slower than 736p and needs much more memory. Custom sets any short edge from 256 to 2048 px (rounded to 32); the other side follows the video's shape. It needs the `short_edge` input of the H3 Swap Plan nodes in comfyui-h3-oneclick-swap.+A 6 s clip at 480p takes about 6–13 minutes on a 4060 Ti, most of it in H3 sampling. 736p is the default; 1080p is about 2.5× slower than 736p and needs much more memory. Custom sets an exact width × height from 256 to 2048 px a side (rounded to 32); the video is scaled and centre-cropped to that shape first. It needs the `short_edge` input of the H3 Swap Plan nodes in comfyui-h3-oneclick-swap.## Tipsdiff --git a/app/api/jobs/route.ts b/app/api/jobs/route.tsindex 90d6dc6..dbb295c 100644--- a/app/api/jobs/route.ts+++ b/app/api/jobs/route.ts@@ -5,7 +5,7 @@ import { CHUNK_SECONDS, FACE_STYLES, type FaceSettings, type FaceStyle } from ".import { MAX_CHARACTERS } from "../../../lib/advanced.ts";import { MAX_LORAS, STEPS, STRENGTH, type ModelSettings } from "../../../lib/model.ts";import { EDIT_MODES, OBJECT_MARGINS, type EditMode, type ObjectMargin, type ObjectSettings } from "../../../lib/object.ts";-import { CLIP_SECONDS, DEFAULT_TARGET, MARGINS, MAX_SEED, MIN_SECTION_SECONDS, MOTION_SIZES, RESOLUTIONS, SHORT_EDGE, type Margin, type MotionSize, type Resolution, type Section, type SimpleSettings } from "../../../lib/simple.ts";+import { CLIP_SECONDS, DEFAULT_TARGET, MARGINS, MAX_SEED, MIN_SECTION_SECONDS, MOTION_SIZES, RESOLUTIONS, CUSTOM_SIZE, type Margin, type MotionSize, type Preset, type Resolution, type Section, type SimpleSettings } from "../../../lib/simple.ts";export const runtime = "nodejs";@@ -40,11 +40,12 @@ function parsePicture(picture: FormDataEntryValue | null) {function parseRun(form: FormData) {const entry = String(form.get("resolution"));- const edge = Number(entry);- const resolution: Resolution = RESOLUTIONS.includes(entry as (typeof RESOLUTIONS)[number]) ? entry as Resolution : edge;- if (typeof resolution === "number" && !(Number.isInteger(edge) && edge >= SHORT_EDGE.min && edge <= SHORT_EDGE.max)) {- throw new Error(`Choose a resolution, or a custom short edge of ${SHORT_EDGE.min}-${SHORT_EDGE.max} px.`);+ const custom = entry.match(/^(\d+)x(\d+)$/);+ const [width, height] = custom ? [custom[1], custom[2]].map((side) => Math.round(Number(side) / CUSTOM_SIZE.step) * CUSTOM_SIZE.step) : [0, 0];+ if (custom ? !(Math.min(width, height) >= CUSTOM_SIZE.min && Math.max(width, height) <= CUSTOM_SIZE.max) : !RESOLUTIONS.includes(entry as Preset)) {+ throw new Error(`Choose a resolution, or a custom size of ${CUSTOM_SIZE.min}-${CUSTOM_SIZE.max} px a side.`);}+ const resolution: Resolution = custom ? { width, height } : entry as Preset;const motion = Number(form.get("motion"));if (!MOTION_SIZES.includes(motion as MotionSize)) throw new Error("Choose a supported motion reference size.");const seed = Number(form.get("seed"));diff --git a/app/globals.css b/app/globals.cssindex 58ac6d8..0a9deaf 100644--- a/app/globals.css+++ b/app/globals.css@@ -153,6 +153,7 @@ input[type="range"] { accent-color: var(--accent); width: 220px; max-width: 100%.file-name { min-width: 0; width: min(100%, 420px); }.steps-input { width: 6rem; }+.custom-size, .custom-size label { display: flex; align-items: center; gap: 8px; }.target-input { width: 12rem; }.setting.loras { align-items: flex-start; }.lora-list { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; flex: 1 1 100%; }diff --git a/components/openjutsu.tsx b/components/openjutsu.tsxindex 6123f40..97ede29 100644--- a/components/openjutsu.tsx+++ b/components/openjutsu.tsx@@ -4,7 +4,7 @@ import { useEffect, useRef, useState, type DragEvent, type ReactNode } from "reaimport type { PublicJob } from "../lib/comfy.ts";import type { NodeInfo } from "../lib/progress.ts";import { clipCount, clipStarts } from "../lib/clips.ts";-import { CLIP_SECONDS, DEFAULT_TARGET, MARGINS, MAX_SEED, MIN_SECTION_SECONDS, MOTION_SIZES, RESOLUTIONS, SHORT_EDGE, canvasSize, type Margin, type MotionSize, type Resolution, type Section } from "../lib/simple.ts";+import { CLIP_SECONDS, DEFAULT_TARGET, MARGINS, MAX_SEED, MIN_SECTION_SECONDS, MOTION_SIZES, RESOLUTIONS, CUSTOM_SIZE, canvasSize, type Margin, type MotionSize, type Resolution, type Section, type Size } 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 type { EditMode } from "../lib/object.ts";@@ -142,7 +142,7 @@ export function Openjutsu() {const [characters, setCharacters] = useState<Character[]>([]);const [maxQuality, setMaxQuality] = useState(false);const [resolution, setResolution] = useState<Resolution>("736p");- const [customEdge, setCustomEdge] = useState(SHORT_EDGE.default);+ const [customSize, setCustomSize] = useState<Size>({ width: 1248, height: 736 });const [hatFix, setHatFix] = useState(false);const [noLipSync, setNoLipSync] = useState(false);const [margin, setMargin] = useState<Margin>("normal");@@ -289,13 +289,15 @@ export function Openjutsu() {setCharacters(characters.map((c, i) => (i === index ? { ...c, role } : c)));}- const canvas = video?.width ? canvasSize(video.width, video.height, resolution) : null;+ const canvas = typeof resolution === "object" ? [resolution.width, resolution.height] : video?.width ? canvasSize(video.width, video.height, resolution) : null;+ const resolutionField = typeof resolution === "object" ? `${resolution.width}x${resolution.height}` : resolution;- function chooseEdge(value: number) {- const edge = Math.min(SHORT_EDGE.max, Math.max(SHORT_EDGE.min, Math.round(value / SHORT_EDGE.step) * SHORT_EDGE.step || SHORT_EDGE.default));- setCustomEdge(edge);- setResolution(edge);- return edge;+ function chooseSize(side: keyof Size, value: number) {+ const snapped = Math.min(CUSTOM_SIZE.max, Math.max(CUSTOM_SIZE.min, Math.round(value / CUSTOM_SIZE.step) * CUSTOM_SIZE.step || customSize[side]));+ const size = { ...customSize, [side]: snapped };+ setCustomSize(size);+ setResolution(size);+ return snapped;}const clips = !video?.duration ? 0 : faceFix ? faceChunkCount(part.length || video.duration, chunkSeconds) : clipCount(part.length || video.duration, clipSeconds);@@ -334,7 +336,7 @@ export function Openjutsu() {form.set("role", character.role);}if (kind === "simple") {- form.set("resolution", String(resolution));+ form.set("resolution", resolutionField);form.set("seed", String(seed));form.set("clip_seconds", String(clipSeconds));}@@ -345,7 +347,7 @@ export function Openjutsu() {form.append("role", c.role);}form.set("max_quality", String(kind === "advanced_maxq"));- form.set("resolution", String(resolution));+ form.set("resolution", resolutionField);form.set("seed", String(seed));form.set("clip_seconds", String(clipSeconds));}@@ -369,7 +371,7 @@ export function Openjutsu() {if (look && editMode !== "remove") form.set("picture", look.file);form.set("biggest_only", String(biggestOnly));form.set("keep_outline", String(keepOutline));- form.set("resolution", String(resolution));+ form.set("resolution", resolutionField);form.set("seed", String(seed));form.set("clip_seconds", String(clipSeconds));}@@ -638,19 +640,26 @@ export function Openjutsu() {<section className="panel settings"><h2><span>3</span> Settings</h2>{mode !== "post" && <div className="setting">- <span>Resolution <small>{canvas ? `${canvas[0]} × ${canvas[1]} for this video.` : "Short edge of the video."} The shape follows the source.</small></span>+ <span>Resolution <small>{typeof resolution === "object" ? "Width × height. The video is scaled and centre-cropped to this shape." : `${canvas ? `${canvas[0]} × ${canvas[1]} for this video` : "Short edge of the video"}. The shape follows the source.`}</small></span><div className="segmented">{RESOLUTIONS.map((r) => (<button key={r} className={r === resolution ? "on" : ""} onClick={() => setResolution(r)}>{r}</button>))}- <button className={typeof resolution === "number" ? "on" : ""} onClick={() => setResolution(customEdge)}>Custom</button>+ <button className={typeof resolution === "object" ? "on" : ""} onClick={() => setResolution(customSize)}>Custom</button></div>- {typeof resolution === "number" && (- <input- className="steps-input" type="number" aria-label="Custom short edge in pixels" min={SHORT_EDGE.min} max={SHORT_EDGE.max} step={SHORT_EDGE.step}- defaultValue={resolution} onBlur={(event) => { event.target.value = String(chooseEdge(Number(event.target.value))); }}- onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); }}- />+ {typeof resolution === "object" && (+ <div className="custom-size">+ {(["width", "height"] as const).map((side) => (+ <label key={side}>+ {side === "height" && "×"}+ <input+ className="steps-input" type="number" aria-label={`Custom ${side} in pixels`} min={CUSTOM_SIZE.min} max={CUSTOM_SIZE.max} step={CUSTOM_SIZE.step}+ defaultValue={resolution[side]} onBlur={(event) => { event.target.value = String(chooseSize(side, Number(event.target.value))); }}+ onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); }}+ />+ </label>+ ))}+ </div>)}</div>}{mode === "object" && editMode !== "background" && !fromPicture && (diff --git a/lib/advanced.ts b/lib/advanced.tsindex 469efa0..f5533e9 100644--- a/lib/advanced.ts+++ b/lib/advanced.ts@@ -75,7 +75,7 @@ export function pruneAdvanced(source: ApiGraph, pictures: number, settings: Adva}const plan = graph[nodeByTitle(graph, PLAN)].inputs;const roles = settings.roles.slice(0, pictures).map((role) => role.replace(/\s+/g, " ").trim());- setResolution(plan, settings.resolution);+ setResolution(graph, nodeByTitle(graph, PLAN), nodeByTitle(graph, VIDEO), settings.resolution);plan.seed = settings.seed;plan.clip_seconds = settings.clipSeconds;plan.roles = roles.some(Boolean) ? roles.map((role, i) => role || ordinal(i, pictures)).join("\n") : "";diff --git a/lib/object.ts b/lib/object.tsindex 7747ef7..10f447e 100644--- a/lib/object.ts+++ b/lib/object.ts@@ -85,6 +85,6 @@ export function pruneObject(source: ApiGraph, picture: boolean, settings: Objectseed: settings.seed,clip_seconds: settings.clipSeconds,});- setResolution(plan, settings.resolution);+ setResolution(graph, id("Object Swap Plan (what to change)"), id(OBJECT_VIDEO), settings.resolution);return graph;}diff --git a/lib/simple.ts b/lib/simple.tsindex 89d42c4..f4f8885 100644--- a/lib/simple.ts+++ b/lib/simple.ts@@ -6,19 +6,30 @@ export type ApiNode = { class_type: string; inputs: Record<string, unknown>; _meexport type ApiGraph = Record<string, ApiNode>;export const RESOLUTIONS = ["480p", "576p", "736p", "768p", "1080p"] as const;-// A number is a custom short edge in pixels; the Swap Plan rounds the canvas to 32 and keeps the source shape either way.-export type Resolution = (typeof RESOLUTIONS)[number] | number;-export const SHORT_EDGE = { min: 256, max: 2048, step: 32, default: 960 };+export type Preset = (typeof RESOLUTIONS)[number];+export type Size = { width: number; height: number };+// A preset is the short edge and keeps the source shape; a custom size is the exact canvas.+export type Resolution = Preset | Size;+export const CUSTOM_SIZE = { min: 256, max: 2048, step: 32 };// Canvas the Swap Plan makes for a source of this size, as its plan_clips does.-export function canvasSize(width: number, height: number, resolution: Resolution) {- const scale = (typeof resolution === "number" ? resolution : parseInt(resolution)) / Math.min(width, height);+export function canvasSize(width: number, height: number, preset: Preset) {+ const scale = parseInt(preset) / Math.min(width, height);return [width, height].map((side) => Math.max(32, Math.round((side * scale) / 32) * 32));}-export function setResolution(plan: Record<string, unknown>, resolution: Resolution) {- if (typeof resolution === "number") plan.short_edge = resolution;- else plan.resolution = resolution;+// A custom size scales and centre-crops the source frames before anything reads them, so SAM, the masks,+// the motion reference and the generation share that shape; the Production Plan alone would crop the frames but stretch the mask.+export function setResolution(graph: ApiGraph, plan: string, video: string, resolution: Resolution) {+ if (typeof resolution === "string") {+ graph[plan].inputs.resolution = resolution;+ return;+ }+ for (const node of Object.values(graph)) {+ for (const [name, value] of Object.entries(node.inputs)) if (isLink(value) && value[0] === video && value[1] === 0) node.inputs[name] = ["custom_size", 0];+ }+ graph.custom_size = { class_type: "ImageScale", inputs: { image: [video, 0], upscale_method: "bilinear", width: resolution.width, height: resolution.height, crop: "center" }, _meta: { title: "Custom size (centre crop)" } };+ graph[plan].inputs.short_edge = Math.min(resolution.width, resolution.height);}export const CLIP_SECONDS = { min: 2.5, max: 15, default: 6 };@@ -142,7 +153,7 @@ export function pruneSimple(source: ApiGraph, settings: SimpleSettings): ApiGrapif (!settings.noLipSync) dropNoLipSync(graph);setMotionSize(graph, settings.motion);const plan = graph[NODES.plan].inputs;- setResolution(plan, settings.resolution);+ setResolution(graph, NODES.plan, NODES.video, settings.resolution);plan.seed = settings.seed;plan.clip_seconds = settings.clipSeconds;plan.roles = settings.role.replace(/\s+/g, " ").trim();diff --git a/test/object.test.ts b/test/object.test.tsindex c643260..2c1e7be 100644--- a/test/object.test.ts+++ b/test/object.test.ts@@ -31,7 +31,8 @@ test("change with a picture keeps the graph and sets the plan", () => {assert.equal(node(pruned, "Grow mask").inputs.expand, 40);assert.equal(node(pruned, "Tracked area").inputs.max_people, 1);assert.ok(node(graph, OBJECT_PICTURE), "the source graph is not modified");- assert.equal(node(pruneObject(graph, true, { ...settings("change"), resolution: 640 }), "Object Swap Plan (what to change)").inputs.short_edge, 640);+ const custom = pruneObject(graph, true, { ...settings("change"), resolution: { width: 640, height: 960 } });+ assert.deepEqual([node(custom, "Object Swap Plan (what to change)").inputs.short_edge, custom.custom_size.inputs.image], [640, [nodeByTitle(custom, OBJECT_VIDEO), 0]]);});test("several things are tracked together, one of each when only the biggest is kept", () => {diff --git a/test/simple.test.ts b/test/simple.test.tsindex 283ef34..06440b9 100644--- a/test/simple.test.ts+++ b/test/simple.test.ts@@ -3,7 +3,7 @@ import { readFileSync } from "node:fs";import test from "node:test";import { clipCount, clipStarts } from "../lib/clips.ts";import { nodeDescriber } from "../lib/progress.ts";-import { MASK_NODES, NODES, canvasSize, pruneMask, pruneSimple, setSection, type ApiGraph, type SimpleSettings } from "../lib/simple.ts";+import { MASK_NODES, NODES, canvasSize, isLink, pruneMask, pruneSimple, setSection, type ApiGraph, type SimpleSettings } from "../lib/simple.ts";const isLinkTo = (g: ApiGraph, value: unknown, type: string) => Array.isArray(value) && g[value[0] as string]?.class_type === type;const load = (name: string): ApiGraph => JSON.parse(readFileSync(new URL(`../workflows/${name}.api.json`, import.meta.url), "utf8"));@@ -34,13 +34,16 @@ test("without hat fix the hat nodes go and the grow mask reads the people mask",assert.ok(graph[NODES.hat[0]], "the source graph is not modified");});-test("a custom resolution is the Swap Plan's short edge; the canvas keeps the source shape", () => {- const plan = pruneSimple(graph, { ...settings(true), resolution: 1000 })[NODES.plan].inputs;- assert.deepEqual([plan.short_edge, plan.resolution], [1000, graph[NODES.plan].inputs.resolution]);- assert.equal(pruneSimple(graph, settings(true))[NODES.plan].inputs.short_edge, undefined);+test("a custom size crops the source frames to that canvas before anything reads them", () => {+ const frameReaders = (g: ApiGraph, id: string) => Object.values(g).flatMap((node) => Object.values(node.inputs)).filter((v) => isLink(v) && v[0] === id && v[1] === 0).length;+ const pruned = pruneSimple(graph, { ...settings(true), resolution: { width: 1248, height: 736 } });+ assert.deepEqual(pruned.custom_size.inputs, { image: [NODES.video, 0], upscale_method: "bilinear", width: 1248, height: 736, crop: "center" });+ assert.equal(frameReaders(pruned, NODES.video), 1);+ assert.equal(frameReaders(pruned, "custom_size"), frameReaders(graph, NODES.video));+ assert.deepEqual([pruned[NODES.plan].inputs.short_edge, pruned[NODES.video].inputs.audio], [736, graph[NODES.video].inputs.audio]);+ assert.equal(pruneSimple(graph, settings(true)).custom_size, undefined);assert.deepEqual(canvasSize(640, 360, "736p"), [1312, 736]);- assert.deepEqual(canvasSize(640, 360, 1000), [1792, 992]);- assert.deepEqual(canvasSize(1080, 1920, 1000), [992, 1792]);+ assert.deepEqual(canvasSize(1080, 1920, "480p"), [480, 864]);});test("a part of the video becomes VHS's skip and frame cap; the whole video keeps 0", () => {