The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Apps: Tap to Recolor changes a colour and keeps the fabric
Adarsh410d4d94dab7
diff --git a/scripts/comfy/hand-built/qwen-image-21-recolor.json b/scripts/comfy/hand-built/qwen-image-21-recolor.jsonnew file mode 100644index 00000000..5fc85372--- /dev/null+++ b/scripts/comfy/hand-built/qwen-image-21-recolor.json@@ -0,0 +1,327 @@+{+ "1": {+ "inputs": {+ "unet_name": "qwen_image_2.1_int8_convrot.safetensors",+ "weight_dtype": "default"+ },+ "class_type": "UNETLoader",+ "_meta": {+ "title": "Load Diffusion Model"+ }+ },+ "2": {+ "inputs": {+ "clip_name": "qwen3vl_8b_int8_convrot.safetensors",+ "type": "qwen_image",+ "device": "default"+ },+ "class_type": "CLIPLoader",+ "_meta": {+ "title": "Load CLIP (Qwen3-VL 8B)"+ }+ },+ "3": {+ "inputs": {+ "vae_name": "qwen_image_2.1_vae_bf16.safetensors"+ },+ "class_type": "VAELoader",+ "_meta": {+ "title": "Load VAE"+ }+ },+ "4": {+ "inputs": {+ "ckpt_name": "sam3.1_multiplex_fp16.safetensors"+ },+ "class_type": "CheckpointLoaderSimple",+ "_meta": {+ "title": "SAM 3.1"+ }+ },+ "10": {+ "inputs": {+ "image": "image.png"+ },+ "class_type": "LoadImage",+ "_meta": {+ "title": "Load Image - The photo"+ }+ },+ "12": {+ "inputs": {+ "value": "[{\"x\": 512, \"y\": 512}]"+ },+ "class_type": "PrimitiveStringMultiline",+ "_meta": {+ "title": "Taps on the piece (JSON points, photo pixels)"+ }+ },+ "13": {+ "inputs": {+ "value": ""+ },+ "class_type": "PrimitiveStringMultiline",+ "_meta": {+ "title": "Taps to leave out (JSON points, or empty)"+ }+ },+ "14": {+ "inputs": {+ "threshold": 0.5,+ "refine_iterations": 2,+ "individual_masks": false,+ "model": [+ "4",+ 0+ ],+ "image": [+ "10",+ 0+ ],+ "positive_coords": [+ "12",+ 0+ ],+ "negative_coords": [+ "13",+ 0+ ]+ },+ "class_type": "SAM3_Detect",+ "_meta": {+ "title": "SAM 3.1 - The tapped piece, one mask"+ }+ },+ "15": {+ "inputs": {+ "expand": 4,+ "tapered_corners": true,+ "mask": [+ "14",+ 0+ ]+ },+ "class_type": "GrowMask",+ "_meta": {+ "title": "Grow Mask - Take in the edge"+ }+ },+ "20": {+ "inputs": {+ "context_factor": 1.4,+ "blend_pixels": 8,+ "output_multiple": 32,+ "target_width": 0,+ "target_height": 0,+ "mask_grow": 0,+ "mask_blur": 0,+ "invert_mask": false,+ "context_pixels": 0,+ "target_megapixels": 1.5,+ "rescale_algorithm": "bicubic",+ "extend_left": 0,+ "extend_right": 0,+ "extend_up": 0,+ "extend_down": 0,+ "keep_inside": true,+ "image": [+ "10",+ 0+ ],+ "mask": [+ "15",+ 0+ ]+ },+ "class_type": "AUSBOSS_NODES_CropForInpaint",+ "_meta": {+ "title": "Crop For Inpaint - Crop around the piece"+ }+ },+ "21": {+ "inputs": {+ "expand": 8,+ "tapered_corners": true,+ "mask": [+ "20",+ 1+ ]+ },+ "class_type": "GrowMask",+ "_meta": {+ "title": "Grow Mask - A little past the piece"+ }+ },+ "22": {+ "inputs": {+ "f_string": "{a} Keep everything else in the picture exactly the same.",+ "values.a": ""+ },+ "class_type": "StringFormat",+ "_meta": {+ "title": "Format Text - The new colour, and keep the rest"+ }+ },+ "23": {+ "inputs": {+ "negative_prompt": "",+ "resolution": 0,+ "clip": [+ "2",+ 0+ ],+ "vae": [+ "3",+ 0+ ],+ "prompt": [+ "22",+ 0+ ],+ "images.image_1": [+ "20",+ 0+ ]+ },+ "class_type": "TextEncodeQwenImage21",+ "_meta": {+ "title": "Text Encode Qwen Image 2.1 - The crop and the new colour"+ }+ },+ "24": {+ "inputs": {+ "pixels": [+ "20",+ 0+ ],+ "vae": [+ "3",+ 0+ ]+ },+ "class_type": "VAEEncode",+ "_meta": {+ "title": "VAE Encode - The crop as the starting point"+ }+ },+ "25": {+ "inputs": {+ "samples": [+ "24",+ 0+ ],+ "mask": [+ "21",+ 0+ ]+ },+ "class_type": "SetLatentNoiseMask",+ "_meta": {+ "title": "Set Latent Noise Mask - Only the tapped piece may change"+ }+ },+ "26": {+ "inputs": {+ "device": "auto",+ "dtype": "default",+ "model": [+ "1",+ 0+ ]+ },+ "class_type": "QwenImage21Cache",+ "_meta": {+ "title": "Reference cache"+ }+ },+ "27": {+ "inputs": {+ "seed": 0,+ "steps": 25,+ "cfg": 1,+ "sampler_name": "euler",+ "scheduler": "simple",+ "denoise": 1,+ "model": [+ "26",+ 0+ ],+ "positive": [+ "23",+ 0+ ],+ "negative": [+ "23",+ 1+ ],+ "latent_image": [+ "25",+ 0+ ]+ },+ "class_type": "KSampler",+ "_meta": {+ "title": "Sampler - CFG 1, euler"+ }+ },+ "28": {+ "inputs": {+ "samples": [+ "27",+ 0+ ],+ "vae": [+ "3",+ 0+ ]+ },+ "class_type": "VAEDecode",+ "_meta": {+ "title": "Decode"+ }+ },+ "29": {+ "inputs": {+ "image": [+ "28",+ 0+ ]+ },+ "class_type": "SplitImageWithAlpha",+ "_meta": {+ "title": "Drop the alpha"+ }+ },+ "30": {+ "inputs": {+ "fix_edge_halo": false,+ "color_match": 0,+ "seam": "classic",+ "stitcher": [+ "20",+ 2+ ],+ "inpainted": [+ "29",+ 0+ ]+ },+ "class_type": "AUSBOSS_NODES_StitchInpaint",+ "_meta": {+ "title": "Stitch Inpaint - Put the piece back (no tone match)"+ }+ },+ "90": {+ "inputs": {+ "filename_prefix": "fuobe/qwen-image-21-recolor",+ "images": [+ "30",+ 0+ ]+ },+ "class_type": "SaveImage",+ "_meta": {+ "title": "Save Image"+ }+ }+}diff --git a/scripts/comfy/library.spec.mjs b/scripts/comfy/library.spec.mjsindex a931dd9f..8bfb44a9 100644--- a/scripts/comfy/library.spec.mjs+++ b/scripts/comfy/library.spec.mjs@@ -3143,6 +3143,28 @@ export const SPEC = ['(as flux1-fill-inpaint). Removed: Mask by Touch and its SAM 3.1 model (the mask is uploaded), the speed LoRA (off in the example), the crop/pad loader (LoadImage), compare, timer and notes. ' +'Prompt: say what goes in the painted area like asking a person ("Replace the cup with a glass of orange juice").' + QWEN21_CLEAN_NOTE,},+ {+ id: 'qwen-image-21-recolor',+ title: 'Qwen-Image 2.1 Recolor (SAM 3.1 tap mask, crop, repaint, paste back)',+ capability: 'recolor',+ handBuilt: 'hand-built/qwen-image-21-recolor.json',+ bindings: {+ image: [b('10', 'image')], positiveCoords: [b('12', 'value')], negativeCoords: [b('13', 'value')], maskGrow: [b('15', 'expand')],+ prompt: [b('22', 'values.a')], seed: [b('27', 'seed')], steps: [b('27', 'steps')],+ },+ outputs: [{ node: '90', kind: 'image' }],+ vramGb: 20,+ license: 'Qwen Research License Agreement (Qwen-Image 2.1): NON-COMMERCIAL, research and evaluation only; Meta SAM License (SAM 3.1); AusBoss nodes MIT',+ modelUrls: { 'sam3.1_multiplex_fp16.safetensors': 'https://huggingface.co/Comfy-Org/sam3.1/resolve/7bb8374780a725b4353ed31f3a9395c9742b5621/checkpoints/sam3.1_multiplex_fp16.safetensors' },+ notes:+ 'Tap to Recolor: qwen-image-21-inpaint with the mask made in the graph from the taps (the AusBoss example\'s Mask by Touch, on core SAM 3.1). ' ++ 'positiveCoords / negativeCoords = JSON point lists [{"x":int,"y":int}] in the photo\'s pixels (PrimitiveStringMultiline -> SAM3_Detect point path, threshold 0.5, refine 2, one merged mask; ' ++ 'negativeCoords may be empty) -> GrowMask maskGrow (4) so the anti-aliased edge changes too -> Crop For Inpaint (context 1.4, blend 8 px, multiple 32, 1.5 MP, bicubic) -> ' ++ 'GrowMask 8 on the crop\'s mask -> StringFormat "{a} Keep everything else in the picture exactly the same." -> TextEncodeQwenImage21 with the crop as image 1 (resolution 0) -> ' ++ 'VAEEncode + SetLatentNoiseMask -> QwenImage21Cache -> KSampler 25 steps, cfg 1, euler, simple -> SplitImageWithAlpha -> Stitch Inpaint (classic, colour match 0: a tone match ' ++ 'would pull the new colour back). Only the tapped piece is sampled and pasted, so the rest of the photo stays as it was; a tap that finds nothing gives the photo back unchanged. ' ++ 'Prompt: "Change the colour of <the piece> to <colour words (#hex)>. Keep its fabric, weave, folds, seams, stitching, sheen, print and shadows exactly as they are, so only the colour is new."',+ },{id: 'qwen-image-21-outpaint',title: 'Qwen-Image 2.1 Expand (outpaint-v2 LoRA, Qwen3-VL scene description)',diff --git a/src/app/(studio)/apps/[id]/page.tsx b/src/app/(studio)/apps/[id]/page.tsxindex c9947062..8696a30d 100644--- a/src/app/(studio)/apps/[id]/page.tsx+++ b/src/app/(studio)/apps/[id]/page.tsx@@ -5,6 +5,7 @@ import { Studio } from "@/components/studio/studio";import { CleanVoiceTool } from "@/components/audio-tools/clean-voice-tool";import { AnyAngleGate } from "@/components/any-angle/any-angle-tool";import { RelightGate } from "@/components/relight/relight-gate";+import { RecolorTool } from "@/components/recolor/recolor-tool";import { APPS, getModel, getPreset } from "@/lib/catalog";import { withRecipe } from "@/lib/catalog/preset-recipes";import { appStudio } from "@/lib/studios";@@ -31,6 +32,7 @@ async function AppStudio({ params }: { params: PageProps<"/apps/[id]">["params"]// Any Angle: build a 3D view of the photo once, then pick camera angles from it. Open to everyone once its workflows// have passed their check on a GPU; the owner gets it before then.if (preset.tool === "any-angle") return <AnyAngleGate live={anyAngleToolLive()} app={{ name: preset.name }} />;+ if (preset.tool === "recolor") return <RecolorTool app={{ name: preset.name, description: preset.description }} />;// The app opens on the model its preview was made with, its own route one pick away.// Its examples sit in the app's card above the composer: one tap loads the photo and settings each was made with.const studio = <Studio config={withRecipe(appStudio(preset), (m) => !!getModel(m))} examples={exampleRow(`app:${preset.id}`)} />;diff --git a/src/components/recolor/recolor-result.tsx b/src/components/recolor/recolor-result.tsxnew file mode 100644index 00000000..105aa984--- /dev/null+++ b/src/components/recolor/recolor-result.tsx@@ -0,0 +1,104 @@+"use client";++import { Columns2, Download, Loader2, Palette } from "lucide-react";+import { useState } from "react";+import { Button } from "@/components/ui/button";+import { colourChip, CUSTOM_COLOUR } from "@/lib/catalog/recolor";+import type { Generation } from "@/lib/catalog/types";+import { downloadHref } from "@/lib/library";+import { cn } from "@/lib/utils";++/** The colour a run asked for: its swatch, or the custom code in its words. */+export function runColour(g: Pick<Generation, "request" | "prompt">): { label: string; hex: string } | null {+ const picked = g.request.presetOptions?.colour;+ if (picked && picked !== CUSTOM_COLOUR) return colourChip(picked);+ const hex = (g.request.prompt ?? g.prompt ?? "").match(/#[0-9a-f]{6}/i)?.[0];+ return hex ? colourChip(hex) : null;+}++/**+ * The new photo, and the original while it is held (a press on a phone, a mouse button on a computer). Compare does the+ * same as a tap, for anyone who can't hold.+ */+function HoldCompare({ before, after, label }: { before?: string; after: string; label: string }) {+ const [held, setHeld] = useState(false);+ const [pinned, setPinned] = useState(false);+ const showBefore = !!before && (held || pinned);+ return (+ <div className="space-y-2">+ <div+ className="relative overflow-hidden rounded-xl bg-media select-none [-webkit-touch-callout:none]"+ onPointerDown={() => before && setHeld(true)}+ onPointerUp={() => setHeld(false)}+ onPointerLeave={() => setHeld(false)}+ onPointerCancel={() => setHeld(false)}+ onContextMenu={(e) => e.preventDefault()}+ >+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={after} alt={label} className="block aspect-[4/5] w-full object-contain" draggable={false} />+ {before && (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={before} alt="The original photo" className={cn("absolute inset-0 size-full object-contain transition-opacity duration-150", showBefore ? "opacity-100" : "opacity-0")} draggable={false} />+ )}+ <span className="pointer-events-none absolute top-2 left-2 rounded-full bg-black/55 px-2 py-0.5 text-[11px] font-medium text-white backdrop-blur">{showBefore ? "Original" : "New colour"}</span>+ </div>+ {before && (+ <div className="flex items-center gap-2">+ <Button variant={pinned ? "secondary" : "outline"} size="sm" className="rounded-full" aria-pressed={pinned} onClick={() => setPinned((p) => !p)}>+ <Columns2 className="size-3.5" /> Compare+ </Button>+ <span className="text-[11px] text-muted-foreground">or hold the photo</span>+ </div>+ )}+ </div>+ );+}++/** One colour's run: running, failed or done, with its swatch. */+export function RecolorResult({ g, onMore }: { g: Generation; onMore: (url: string) => void }) {+ const colour = runColour(g);+ const before = g.request.inputs?.images?.[0];+ const out = g.status === "succeeded" ? g.outputs.find((o) => o.kind === "image") : undefined;+ const busy = g.status === "queued" || g.status === "running";+ const name = `${colour?.label ?? "Recolor"}.png`;+ return (+ <article className="space-y-2 rounded-2xl border bg-background p-2.5 shadow-soft">+ <div className="flex items-center gap-2 px-0.5">+ <span className="size-4 shrink-0 rounded-full border border-black/10" style={{ background: colour?.hex ?? "transparent" }} aria-hidden />+ <span className="min-w-0 flex-1 truncate text-[13px] font-medium">{colour?.label ?? "New colour"}</span>+ {colour && <span className="font-mono text-[11px] text-muted-foreground">{colour.hex}</span>}+ </div>+ {out ? (+ <HoldCompare before={before} after={out.url} label={`The photo in ${colour?.label.toLowerCase() ?? "its new colour"}`} />+ ) : (+ <div className="relative overflow-hidden rounded-xl bg-media">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ {before && <img src={before} alt="" className="block aspect-[4/5] w-full object-contain opacity-40" draggable={false} />}+ <div className="absolute inset-0 grid place-items-center p-4 text-center">+ {busy ? (+ <p className="inline-flex items-center gap-2 rounded-full bg-black/55 px-3 py-1.5 text-[13px] text-white backdrop-blur" role="status">+ <Loader2 className="size-3.5 animate-spin" /> Recolouring…{g.progress ? ` ${Math.round(g.progress * 100)}%` : ""}+ </p>+ ) : (+ <p className="rounded-xl bg-black/60 px-3 py-2 text-[13px] text-white backdrop-blur" role="alert">+ {g.error ?? "This colour didn't come out. Try again."}+ </p>+ )}+ </div>+ </div>+ )}+ {out && (+ <div className="flex flex-wrap gap-1.5">+ <Button variant="outline" size="sm" className="rounded-full" asChild>+ <a href={downloadHref(out.url, name)} download>+ <Download className="size-3.5" /> Download+ </a>+ </Button>+ <Button variant="outline" size="sm" className="rounded-full" onClick={() => onMore(out.url)}>+ <Palette className="size-3.5" /> Recolor more+ </Button>+ </div>+ )}+ </article>+ );+}diff --git a/src/components/recolor/recolor-tool.tsx b/src/components/recolor/recolor-tool.tsxnew file mode 100644index 00000000..2a80c857--- /dev/null+++ b/src/components/recolor/recolor-tool.tsx@@ -0,0 +1,367 @@+"use client";++import { Check, ChevronRight, ImagePlus, Library, Loader2, Palette, Upload, X } from "lucide-react";+import Link from "next/link";+import { useCallback, useEffect, useId, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Segmented } from "@/components/faceless/controls";+import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";+import { FrameStage, type Frame } from "@/components/remove-object/frame-stage";+import { fileToSlot, kindOfFile, LibraryGrid, type SlotValue } from "@/components/studio/media-slot";+import { useAskBeforeUpload, useCreateGeneration, useGenerations } from "@/lib/api";+import { colourChip, ITEMS, normaliseHex, RECOLOR, recolorRequest, SWATCHES } from "@/lib/catalog/recolor";+import type { PixelPoint } from "@/lib/catalog/types";+import { toastError } from "@/lib/refusals";+import { cn } from "@/lib/utils";+import { RecolorResult } from "./recolor-result";++const SUBTITLE = "Tap the dress, the jacket or the bag, then pick a colour. Folds, texture and shine stay exactly as they are, and nothing else in the photo changes.";+const TAP_WORDS = { positive: "recolour", negative: "leave out", ask: "Tap what to recolour", frame: "Your photo" };++/** The picture's own size, read by the browser once it loads (the taps are in its pixels). */+function useFrame(url: string | undefined): Frame | null {+ const [frame, setFrame] = useState<Frame | null>(null);+ useEffect(() => {+ if (!url) return;+ let live = true;+ const img = new Image();+ img.onload = () => live && setFrame({ url, width: img.naturalWidth, height: img.naturalHeight });+ img.src = url;+ return () => {+ live = false;+ };+ }, [url]);+ return frame && frame.url === url ? frame : null;+}++/** ?image=/api/files/… from a Library result's "Recolor", read once after hydration. */+function useHandoff(take: (s: SlotValue) => void) {+ useEffect(() => {+ const url = new URLSearchParams(window.location.search).get("image");+ if (url?.startsWith("/api/files/")) take({ ref: url, preview: url, kind: "image", name: decodeURIComponent(url.split("/").pop() ?? "") });+ // Once, on arrival.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+}++function AddPhoto({ onPick }: { onPick: (v: SlotValue | null) => void }) {+ const [over, setOver] = useState(false);+ const [picking, setPicking] = useState(false);+ const askFirst = useAskBeforeUpload();+ const inputId = useId();+ const take = (f: File | undefined) => {+ if (!f || askFirst()) return;+ if (kindOfFile(f) !== "image") return void toast("Photos only. Drop a picture here.");+ void fileToSlot(f, onPick, "image");+ };+ return (+ <div+ className={cn(+ "flex flex-col items-center justify-center gap-3 rounded-2xl border-2 border-dashed border-border-strong bg-background px-4 py-10 text-center transition-colors",+ over && "border-primary bg-brand-faint",+ )}+ onDragOver={(e) => {+ e.preventDefault();+ setOver(true);+ }}+ onDragLeave={() => setOver(false)}+ onDrop={(e) => {+ e.preventDefault();+ setOver(false);+ take(e.dataTransfer.files?.[0]);+ }}+ >+ <span className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">{over ? <Upload className="size-5" /> : <ImagePlus className="size-5" />}</span>+ <div>+ <p className="text-[15px] font-medium">Add a photo</p>+ <p className="mt-1 text-[13px] text-muted-foreground">A look, a product, a room: anything with a colour to change</p>+ </div>+ <div className="flex flex-wrap items-center justify-center gap-1.5">+ <Button size="lg" className="rounded-full" onClick={() => askFirst() || document.getElementById(inputId)?.click()}>+ <Upload className="size-4" /> Upload+ </Button>+ <Popover open={picking} onOpenChange={setPicking}>+ <PopoverTrigger asChild>+ <Button variant="ghost" size="lg" className="rounded-full">+ <Library className="size-4" /> From your Library+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-[min(92vw,360px)] p-2" collisionPadding={12}>+ <p className="px-1 pb-2 text-[13px] font-medium">From your library</p>+ {picking && (+ <LibraryGrid+ kinds={["image"]}+ onPick={(v) => {+ onPick(v);+ setPicking(false);+ }}+ />+ )}+ </PopoverContent>+ </Popover>+ </div>+ <input+ id={inputId}+ type="file"+ accept="image/png,image/jpeg,image/webp"+ hidden+ onChange={(e) => {+ take(e.target.files?.[0]);+ e.target.value = "";+ }}+ />+ </div>+ );+}++function Step({ title, hint, children }: { title: string; hint?: React.ReactNode; children: React.ReactNode }) {+ return (+ <div className="space-y-2">+ <div>+ <h3 className="text-[13px] font-semibold">{title}</h3>+ {hint && <p className="text-[12px] text-muted-foreground">{hint}</p>}+ </div>+ {children}+ </div>+ );+}++/** One round swatch (a toggle): its colour, its name under it, a check when picked. */+function SwatchButton({ hex, label, on, onClick, children }: { hex: string; label: string; on: boolean; onClick: () => void; children?: React.ReactNode }) {+ return (+ <button+ type="button"+ aria-pressed={on}+ aria-label={label}+ onClick={onClick}+ className="group flex w-14 flex-col items-center gap-1 rounded-xl py-1 text-[11px] text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <span+ className={cn("relative grid size-11 place-items-center rounded-full border border-black/10 shadow-soft transition", on ? "ring-2 ring-foreground ring-offset-2 ring-offset-background" : "group-hover:scale-105")}+ style={{ background: hex }}+ >+ {on && <Check className="size-4 text-white mix-blend-difference" aria-hidden />}+ {children}+ </span>+ <span className={cn("max-w-full truncate", on && "font-medium text-foreground")}>{label}</span>+ </button>+ );+}++function ColourPicker({ picked, onPicked, custom, onCustom }: { picked: string[]; onPicked: (v: string[]) => void; custom: string; onCustom: (hex: string) => void }) {+ const [text, setText] = useState(custom);+ const pickerId = useId();+ const customOn = picked.includes(custom);+ const toggle = (v: string) => {+ if (picked.includes(v)) return onPicked(picked.filter((x) => x !== v));+ if (picked.length >= RECOLOR.maxColours) return void toast(`Up to ${RECOLOR.maxColours} colours at a time`);+ onPicked([...picked, v]);+ };+ const setCustom = (hex: string) => {+ const h = normaliseHex(hex);+ if (!h) return;+ setText(h);+ // The custom colour stays picked as it changes.+ onPicked(picked.includes(custom) ? picked.map((x) => (x === custom ? h : x)) : picked.length < RECOLOR.maxColours ? [...picked, h] : picked);+ onCustom(h);+ };+ return (+ <div className="space-y-3">+ <div className="flex flex-wrap gap-x-1 gap-y-2" role="group" aria-label="Colours">+ {SWATCHES.map((s) => (+ <SwatchButton key={s.value} hex={s.hex} label={s.label} on={picked.includes(s.value)} onClick={() => toggle(s.value)} />+ ))}+ <SwatchButton hex={custom} label="Custom" on={customOn} onClick={() => (customOn ? toggle(custom) : document.getElementById(pickerId)?.click())}>+ {!customOn && <Palette className="size-4 text-white mix-blend-difference" aria-hidden />}+ </SwatchButton>+ </div>+ <div className="flex items-center gap-2">+ <label htmlFor={pickerId} className="text-[12px] text-muted-foreground">+ Custom+ </label>+ <input id={pickerId} type="color" value={custom.toLowerCase()} onChange={(e) => setCustom(e.target.value)} className="h-8 w-10 cursor-pointer rounded-md border bg-background p-0.5" />+ <input+ value={text}+ onChange={(e) => setText(e.target.value)}+ onBlur={() => (normaliseHex(text) ? setCustom(text) : setText(custom))}+ onKeyDown={(e) => e.key === "Enter" && (e.currentTarget as HTMLInputElement).blur()}+ aria-label="Custom colour code"+ inputMode="text"+ spellCheck={false}+ maxLength={7}+ className="h-8 w-24 rounded-md border bg-background px-2 font-mono text-[13px] uppercase outline-none focus-visible:ring-2 focus-visible:ring-ring"+ />+ {customOn && <span className="truncate text-[12px] text-muted-foreground">{colourChip(custom)?.label}</span>}+ </div>+ </div>+ );+}++/**+ * Tap to Recolor: a photo, taps on the piece to recolour (FrameStage: green adds, grey leaves out), what it is, and up+ * to four colours. Each colour is its own run on the open engine (the taps go as params.points in the photo's pixels);+ * the results stack under it with a press-and-hold before/after.+ */+export function RecolorTool({ app }: { app: { name: string; description: string } }) {+ const [photo, setPhoto] = useState<SlotValue | null>(null);+ const [points, setPoints] = useState<PixelPoint[]>([]);+ const [mark, setMark] = useState<"positive" | "negative">("positive");+ const [item, setItem] = useState("auto");+ const [colours, setColours] = useState<string[]>(["emerald"]);+ const [custom, setCustom] = useState("#C98B93");+ const [sending, setSending] = useState(false);+ const create = useCreateGeneration();+ const frame = useFrame(photo?.preview);++ const current = useRef<SlotValue | null>(null);+ const take = useCallback((v: SlotValue | null) => {+ const cur = current.current;+ // An upload settling (the same file, now on the server) keeps the taps; a new photo starts over.+ if (!(v && cur?.uploading && v.name === cur.name)) setPoints([]);+ current.current = v;+ setPhoto(v);+ }, []);+ useHandoff(take);++ const ready = photo && !photo.uploading && photo.ref ? photo : null;+ const taps = points.filter((p) => p.label !== "negative").length;+ const blocker = !ready ? "Add a photo" : !taps ? "Tap the piece you want in a new colour." : !colours.length ? "Pick a colour" : null;++ const go = async () => {+ if (blocker || !ready || !frame) return void toast(blocker ?? "Add a photo");+ setSending(true);+ try {+ for (const colour of colours) await create.mutateAsync(recolorRequest({ image: ready.ref, points, frame, colour, item }));+ toast.success(colours.length > 1 ? `Recolouring in ${colours.length} colours` : "Recolouring");+ document.getElementById("recolor-results")?.scrollIntoView({ behavior: "smooth", block: "start" });+ } catch (e) {+ toastError(e, "That didn't start. Please try again.");+ } finally {+ setSending(false);+ }+ };+ const more = (url: string) => {+ take({ ref: url, preview: url, kind: "image", name: "Recolored" });+ window.scrollTo({ top: 0, behavior: "smooth" });+ };++ return (+ <ToolShell+ title="Apps"+ engineSwitch={false}+ header={+ <nav aria-label="Breadcrumb" className="hidden items-center gap-1 text-[13px] text-muted-foreground sm:flex">+ <Link href="/apps" className="hover:text-foreground">+ Apps+ </Link>+ <ChevronRight className="size-3.5" />+ <span className="text-foreground">{app.name}</span>+ </nav>+ }+ >+ {!photo && <ToolHero title={app.name} subtitle={SUBTITLE} />}+ {!photo ? (+ <div className="mx-auto mt-6 max-w-[640px]">+ <AddPhoto onPick={take} />+ </div>+ ) : (+ <div className="mx-auto grid max-w-[1040px] gap-3 pt-4 lg:grid-cols-[minmax(0,1fr)_340px] lg:items-start">+ <Panel+ title="Tap what to recolour"+ aside={+ <Button variant="ghost" size="icon-sm" className="rounded-full" aria-label="Remove the photo" onClick={() => take(null)}>+ <X className="size-4" />+ </Button>+ }+ >+ {frame ? (+ <FrameStage frame={frame} points={points} onPoints={setPoints} pointLabel={mark} clickable maxPoints={RECOLOR.maxPoints} words={TAP_WORDS} />+ ) : (+ <div className="grid aspect-[4/5] max-h-[46vh] place-items-center rounded-xl bg-media">+ <Loader2 className="size-5 animate-spin text-white/70" />+ </div>+ )}+ <div className="mt-3 flex flex-wrap items-center gap-2">+ <Segmented+ label="What a tap does"+ value={mark}+ onChange={setMark}+ options={[+ { value: "positive", label: "Add to it" },+ { value: "negative", label: "Leave out" },+ ]}+ />+ {points.length > 0 && (+ <Button variant="ghost" size="sm" className="rounded-full" onClick={() => setPoints([])}>+ Clear+ </Button>+ )}+ <p className="w-full text-[12px] text-muted-foreground" aria-live="polite">+ {photo.uploading ? "Uploading…" : !taps ? "Tap the piece you want in a new colour." : mark === "negative" ? "Tap what should keep its colour." : "Tap again to take in more of it."}+ </p>+ </div>+ </Panel>+ <Panel className="space-y-5">+ <Step title="What is it?">+ <div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label="What is it?">+ {ITEMS.map((i) => (+ <button+ key={i.value}+ type="button"+ role="radio"+ aria-checked={item === i.value}+ onClick={() => setItem(i.value)}+ className={cn(+ "h-8 rounded-full border px-3 text-[13px] transition outline-none focus-visible:ring-2 focus-visible:ring-ring",+ item === i.value ? "border-foreground bg-foreground text-background" : "bg-background text-muted-foreground hover:text-foreground",+ )}+ >+ {i.label}+ </button>+ ))}+ </div>+ </Step>+ <Step title="Colour" hint={`Pick up to ${RECOLOR.maxColours}. Each one is its own photo.`}>+ <ColourPicker picked={colours} onPicked={setColours} custom={custom} onCustom={setCustom} />+ </Step>+ <div className="space-y-2">+ <Button size="lg" className="h-11 w-full rounded-full text-[15px]" onClick={go} disabled={sending || !ready || !frame} aria-describedby="recolor-blocker">+ {sending ? <Loader2 className="size-4 animate-spin" /> : <Palette className="size-4" />}+ {colours.length > 1 ? `Recolor in ${colours.length} colours` : "Recolor"}+ </Button>+ {blocker && ready && (+ <p id="recolor-blocker" className="text-center text-[12px] text-muted-foreground" aria-live="polite">+ {blocker}+ </p>+ )}+ </div>+ </Panel>+ </div>+ )}+ <Results onMore={more} />+ </ToolShell>+ );+}++/** The recolours so far, newest first. */+function Results({ onMore }: { onMore: (url: string) => void }) {+ const runs = useGenerations({ features: [RECOLOR.feature], limit: 24 });+ const items = runs.data ?? [];+ if (!items.length) return null;+ return (+ <section className="mx-auto mt-10 max-w-[1040px]" aria-labelledby="recolor-results">+ <h3 id="recolor-results" className="mb-3 scroll-mt-20 font-heading text-[22px]">+ Your colours+ </h3>+ <ul className="grid grid-cols-1 gap-3 min-[480px]:grid-cols-2 lg:grid-cols-3">+ {items.map((g) => (+ <li key={g.id}>+ <RecolorResult g={g} onMore={onMore} />+ </li>+ ))}+ </ul>+ </section>+ );+}diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsxindex 982d5a6b..f7cf6b7d 100644--- a/src/components/studio/result-actions.tsx+++ b/src/components/studio/result-actions.tsx@@ -28,6 +28,7 @@ import {MicOff,UserX,MoreHorizontal,+ Palette,Pin,Repeat,RotateCcw,@@ -91,6 +92,7 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {"new-angle": Rotate3d,edit: Wand2,"live-edit": Zap,+ recolor: Palette,upscale: ZoomIn,reference: ImagePlus,grade: SlidersHorizontal,diff --git a/src/lib/catalog/apps.ts b/src/lib/catalog/apps.tsindex 936242b2..fb2c7007 100644--- a/src/lib/catalog/apps.ts+++ b/src/lib/catalog/apps.ts@@ -1,5 +1,6 @@import { QMA_MODEL } from "@/lib/qma";import { ANGLES_2511_LORA } from "./open-tools";+import { CUSTOM_COLOUR, ITEMS, RECOLOR, RECOLOR_TEMPLATE, SWATCHES } from "./recolor";import { CAST_LOOK } from "./soul-cards";import type { InputSlot, Preset, PresetOption, PresetRoute } from "./types";@@ -1050,6 +1051,31 @@ export const APPS: Preset[] = ["Create a professional fashion campaign photo of a stylish model wearing all the clothing items from the images together as one outfit, reproducing each item's exact color, fabric, print and logo. {prompt}. Full-body editorial pose, natural light, high-end lookbook photography.",parity: "Makes the photoshoot as a still. Animate it with Bring to Life.",}),+ // Tap to Recolor: an app that is a tool of its own (src/components/recolor/recolor-tool.tsx): the taps (params.points)+ // pick the piece, the swatch or a custom colour (the prompt) names its new colour; only that piece is repainted.+ app({+ id: RECOLOR.appId,+ name: "Tap to Recolor",+ category: "Fashion",+ description: "Tap a piece, pick a colour; the fabric stays",+ icon: "Palette",+ hue: 330,+ badges: ["new"],+ tool: "recolor",+ options: [+ { key: "item", label: "What is it?", choices: ITEMS.map((i) => ({ value: i.value, label: i.label, prompt: i.words })) },+ {+ key: "colour",+ label: "Colour",+ choices: [...SWATCHES.map((s) => ({ value: s.value, label: s.label, prompt: `${s.words} (${s.hex})` })), { value: CUSTOM_COLOUR, label: "Custom", prompt: "" }],+ },+ ],+ userPrompt: "optional",+ prompt: RECOLOR_TEMPLATE,+ cloud: null,+ open: { modelId: RECOLOR.modelId, op: "edit" },+ parity: "Runs on your own GPU. Only the piece you tap changes.",+ }),// ---------------- Style & artapp({name: "Sketch to Real",diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.tsindex f0902254..3cc51b00 100644--- a/src/lib/catalog/models.ts+++ b/src/lib/catalog/models.ts@@ -8,6 +8,7 @@ import { H3_DECODER, H3_FAST_DECODE_OFFERED, H3_GPU_TIER } from "@/lib/gpu/h3-tiimport { loraEntry, loraRef } from "./loras";import { ANGLES_LORA, ANY_ANGLE_LORA, MOSAIC_SCALE, MOSAIC_TARGET, SPEAK_GRAPH, SPEAK_LORA, SPEAK_PROMPT } from "./open-tools";import { ANY_ANGLE } from "./any-angle";+import { RECOLOR_TAP_FIRST } from "./recolor";import { CINEMA_CROP, SOUL_ASPECTS, SOUL_TIERS } from "./soul";import { RESTORE, offlineRestorePrompt } from "./restore";import { REGEN_COPY, REGEN_DEFAULT_TIER, REGEN_MODEL, REGEN_OFFERED, REGEN_TIERS, REGEN_WORKFLOW } from "./regenerate";@@ -200,6 +201,19 @@ const open: ModelDef[] = [options: { maxImages: 4, seed: true },hidden: true,}),+ // Tap to Recolor's model (the app's own page runs it): SAM 3.1 makes the mask from the taps (params.points), and+ // Qwen-Image 2.1 repaints only that piece in the new colour. Listed for its licence and switch, never in a picker.+ o({+ id: "oss-recolor",+ name: "Tap to Recolor",+ vendor: "Alibaba Qwen + Meta SAM 3.1",+ family: "qwen-image",+ kind: "image",+ tagline: "Only the tapped piece takes the new colour; its fabric, folds and shine stay · 20 GB GPU · non-commercial weights",+ routes: [{ ...comfy("edit", "qwen-image-21-recolor", "SAM 3.1 mask from the taps, 25 steps, pasted back"), unsized: true, maxImages: 1 }],+ options: { maxImages: 1, seed: true, requires: { images: 1, points: true, msg: RECOLOR_TAP_FIRST } },+ hidden: true,+ }),// FLUX 3 Image Klein (BFL, 2026-10-13; research #10 §6.3): text to image and edits with up to 10 references, a layout of// boxes in its own table (compileFlux3), BFL's prompt helper first unless it is off. Klein Base takes your FLUX 3 Kleindiff --git a/src/lib/catalog/preset-recipe-routes.ts b/src/lib/catalog/preset-recipe-routes.tsindex a7113fd2..8718a904 100644--- a/src/lib/catalog/preset-recipe-routes.ts+++ b/src/lib/catalog/preset-recipe-routes.ts@@ -48,6 +48,7 @@ export type RecipeKind = "h3" | "orbit" | "qwen";* pixels, an SVG, a matte, a mesh) only their own model makes; their previews show the idea.* - Clean up voice: a tool of its own (RE-USE), with nothing to recast.* - Any Angle: a tool of its own (a 3D view of the photo, then each angle from it on the GPU).+ * - Tap to Recolor: a tool of its own, whose taps make the mask its graph repaints.*/export const OWN_ROUTE_APPS: ReadonlySet<string> = new Set(["app-fuobe-angles",@@ -65,6 +66,7 @@ export const OWN_ROUTE_APPS: ReadonlySet<string> = new Set(["app-image-to-3d","app-clean-up-voice","app-any-angle",+ "app-tap-to-recolor",]);/**diff --git a/src/lib/catalog/recolor.ts b/src/lib/catalog/recolor.tsnew file mode 100644index 00000000..f9118571--- /dev/null+++ b/src/lib/catalog/recolor.ts@@ -0,0 +1,207 @@+/**+ * Tap to Recolor: tap a piece of clothing (or anything) in a photo and pick a colour; only that piece changes, its+ * fabric, folds and sheen kept. On the open engine SAM 3.1 turns the taps into a mask and Qwen-Image 2.1 repaints the+ * piece inside it (workflows/comfyui/qwen-image-21-recolor.json), so the rest of the photo stays as it was.+ *+ * Pure module (the swatches, the words, the taps as SAM's point lists, the request a run sends), shared by the app's+ * page (src/components/recolor), the catalog, the ComfyUI provider and the tests.+ */+import type { GenerationRequest, PixelPoint } from "./types";++export const RECOLOR = {+ appId: "app-tap-to-recolor",+ modelId: "oss-recolor",+ feature: "app:app-tap-to-recolor",+ /** Taps on one photo (SAM 3.1 reads a few points well; more only adds noise). */+ maxPoints: 8,+ /** Colours one Recolor makes, each its own run. */+ maxColours: 4,+} as const;++export const RECOLOR_TAP_FIRST = "Tap what to recolour";++/** The words the model reads: only what the picture should show. */+export const RECOLOR_TEMPLATE =+ "Change the colour of {option:item} to {option:colour}{prompt}. Keep its fabric, weave, folds, seams, stitching, sheen, print and shadows exactly as they are, so only the colour is new.";++export interface Swatch {+ value: string;+ label: string;+ hex: string;+ /** What the model reads for it. */+ words: string;+}++export const SWATCHES: Swatch[] = [+ { value: "ivory", label: "Ivory", hex: "#F2EBDD", words: "soft ivory" },+ { value: "black", label: "Black", hex: "#141414", words: "deep jet black" },+ { value: "crimson", label: "Crimson", hex: "#A3142C", words: "rich crimson red" },+ { value: "blush", label: "Blush", hex: "#E7B7BF", words: "pale blush pink" },+ { value: "camel", label: "Camel", hex: "#B98B5E", words: "warm camel" },+ { value: "emerald", label: "Emerald", hex: "#0E6B4F", words: "deep emerald green" },+ { value: "sage", label: "Sage", hex: "#9CAF94", words: "muted sage green" },+ { value: "cobalt", label: "Cobalt", hex: "#1F48A8", words: "vivid cobalt blue" },+ { value: "navy", label: "Navy", hex: "#1B2541", words: "dark navy" },+ { value: "lilac", label: "Lilac", hex: "#B7A3D9", words: "soft lilac" },+];++/** The option value a custom colour runs under: its words come in as the run's prompt. */+export const CUSTOM_COLOUR = "custom";++export const ITEMS: { value: string; label: string; words: string }[] = [+ // The crop the graph repaints is centred on the tapped piece.+ { value: "auto", label: "Auto", words: "the piece in the middle of the picture" },+ { value: "dress", label: "Dress", words: "the dress" },+ { value: "top", label: "Top", words: "the top" },+ { value: "jacket", label: "Jacket", words: "the jacket" },+ { value: "trousers", label: "Trousers", words: "the trousers" },+ { value: "skirt", label: "Skirt", words: "the skirt" },+ { value: "bag", label: "Bag", words: "the bag" },+ { value: "shoes", label: "Shoes", words: "the shoes" },+];++/** "#abc" / "abc" / "#AABBCC" → "#AABBCC", or null. */+export function normaliseHex(s: string): string | null {+ const m = s.trim().replace(/^#/, "").match(/^([0-9a-f]{3}|[0-9a-f]{6})$/i);+ if (!m) return null;+ const h = m[1].length === 3 ? [...m[1]].map((c) => c + c).join("") : m[1];+ return `#${h.toUpperCase()}`;+}++type Lab = [number, number, number];++function hexToLab(hex: string): Lab {+ const n = parseInt(hex.slice(1), 16);+ const lin = (c: number) => {+ const v = c / 255;+ return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;+ };+ const [r, g, b] = [lin((n >> 16) & 255), lin((n >> 8) & 255), lin(n & 255)];+ // sRGB D65 → XYZ, normalised to the white point.+ const x = (0.4124 * r + 0.3576 * g + 0.1805 * b) / 0.95047;+ const y = 0.2126 * r + 0.7152 * g + 0.0722 * b;+ const z = (0.0193 * r + 0.1192 * g + 0.9505 * b) / 1.08883;+ const f = (t: number) => (t > 216 / 24389 ? Math.cbrt(t) : (24389 / 27 * t + 16) / 116);+ return [116 * f(y) - 16, 500 * (f(x) - f(y)), 200 * (f(y) - f(z))];+}++/** Names a custom colour is told by (the nearest one in Lab), with the swatches' own. */+const NAMED: [string, string][] = [+ ...SWATCHES.map((s): [string, string] => [s.words, s.hex]),+ ["pure white", "#FAFAFA"],+ ["cream", "#F3E5C8"],+ ["silver grey", "#B8B8B8"],+ ["charcoal grey", "#3C3C3C"],+ ["dove grey", "#8E8E8E"],+ ["scarlet red", "#D0201E"],+ ["burgundy", "#6B1626"],+ ["dusty rose pink", "#C98B93"],+ ["hot pink", "#E0338A"],+ ["fuchsia", "#C21E87"],+ ["coral", "#F0735A"],+ ["burnt orange", "#C2571A"],+ ["tangerine orange", "#F28A1E"],+ ["mustard yellow", "#D4A21C"],+ ["lemon yellow", "#F2E15B"],+ ["butter yellow", "#F4E3A1"],+ ["olive green", "#6B6B2A"],+ ["forest green", "#1F4A2C"],+ ["mint green", "#A8DCC0"],+ ["teal", "#13706F"],+ ["turquoise", "#2EB5B0"],+ ["sky blue", "#8EC3E8"],+ ["powder blue", "#B9CFE6"],+ ["royal blue", "#2A3FB0"],+ ["denim blue", "#3C5A82"],+ ["deep purple", "#4A2369"],+ ["violet", "#7A4FBF"],+ ["chocolate brown", "#4E2E1E"],+ ["tan", "#C9A57A"],+ ["taupe", "#8B7B6B"],+];++/** The nearest named colour to `hex` (CIE76 in Lab). */+export function nearestColourName(hex: string): string {+ const h = normaliseHex(hex);+ if (!h) return "";+ const [l, a, b] = hexToLab(h);+ let best = NAMED[0][0];+ let bestD = Infinity;+ for (const [name, at] of NAMED) {+ const [l2, a2, b2] = hexToLab(at);+ const d = (l - l2) ** 2 + (a - a2) ** 2 + (b - b2) ** 2;+ if (d < bestD) [best, bestD] = [name, d];+ }+ return best;+}++/** A swatch's words with its hex ("deep emerald green (#0E6B4F)"), or a custom colour's ("dusty rose pink (#C98B93)"). */+export function colourWords(colour: string): string {+ const swatch = SWATCHES.find((s) => s.value === colour);+ if (swatch) return `${swatch.words} (${swatch.hex})`;+ const hex = normaliseHex(colour);+ return hex ? `${nearestColourName(hex)} (${hex})` : "";+}++/** A colour the page shows: a swatch's name and hex, or a custom hex with its nearest name. */+export function colourChip(colour: string): { label: string; hex: string } | null {+ const swatch = SWATCHES.find((s) => s.value === colour);+ if (swatch) return { label: swatch.label, hex: swatch.hex };+ const hex = normaliseHex(colour);+ if (!hex) return null;+ const name = nearestColourName(hex);+ return { label: name.charAt(0).toUpperCase() + name.slice(1), hex };+}++/**+ * The taps as SAM 3.1's point lists (JSON `[{"x":int,"y":int}]`, the photo's pixels): positive and negative, "" for+ * none. `from` is the size of the picture the taps were placed on, `to` the photo's own size when known: taps on a+ * smaller copy are scaled up. Points land inside the photo.+ */+export function recolorCoords(points: PixelPoint[] | undefined, to?: { width: number; height: number }, from?: { width: number; height: number }): [string, string] {+ if (!points?.length) return ["", ""];+ const kx = to && from && from.width > 0 ? to.width / from.width : 1;+ const ky = to && from && from.height > 0 ? to.height / from.height : 1;+ const at = (p: PixelPoint) => {+ let x = Math.round(p.x * kx);+ let y = Math.round(p.y * ky);+ if (to) {+ x = Math.min(to.width - 1, Math.max(0, x));+ y = Math.min(to.height - 1, Math.max(0, y));+ }+ return { x: Math.max(0, x), y: Math.max(0, y) };+ };+ const pick = (neg: boolean) => points.filter((p) => Number.isFinite(p.x) && Number.isFinite(p.y) && (p.label === "negative") === neg).slice(0, RECOLOR.maxPoints).map(at);+ const [pos, neg] = [pick(false), pick(true)];+ return [pos.length ? JSON.stringify(pos) : "", neg.length ? JSON.stringify(neg) : ""];+}++/** The size the taps were placed on, as a run carries it (params.extra.frameWidth / frameHeight). */+export function tapFrame(extra: Record<string, unknown> | undefined): { width: number; height: number } | undefined {+ const w = Number(extra?.frameWidth);+ const h = Number(extra?.frameHeight);+ return w > 0 && h > 0 ? { width: w, height: h } : undefined;+}++/** One colour's run: the photo, the taps (in the pixels of `frame`), the piece and the colour (a swatch or a hex). */+export function recolorRequest(o: { image: string; points: PixelPoint[]; frame: { width: number; height: number }; colour: string; item?: string; seed?: number }): GenerationRequest {+ const swatch = SWATCHES.some((s) => s.value === o.colour);+ const hex = swatch ? null : normaliseHex(o.colour);+ if (!swatch && !hex) throw new Error("Pick a colour");+ const item = ITEMS.some((i) => i.value === o.item) ? o.item! : "auto";+ return {+ feature: RECOLOR.feature,+ presetId: RECOLOR.appId,+ modelId: RECOLOR.modelId,+ op: "edit",+ engine: "open",+ ...(hex ? { prompt: colourWords(hex) } : {}),+ inputs: { images: [o.image] },+ presetOptions: { item, colour: swatch ? o.colour : CUSTOM_COLOUR },+ params: {+ points: o.points.slice(0, RECOLOR.maxPoints * 2).map((p) => ({ x: Math.round(p.x), y: Math.round(p.y), label: p.label === "negative" ? "negative" : "positive" })),+ extra: { frameWidth: Math.round(o.frame.width), frameHeight: Math.round(o.frame.height) },+ ...(o.seed !== undefined ? { seed: o.seed } : {}),+ },+ };+}diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex b7774fea..f4c95648 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -1530,8 +1530,8 @@ export interface Preset {grade?: string;/** Fuobe DoP's relight effects: a step that makes the start frame first, on each engine (src/lib/catalog/dop.ts). */prestep?: PresetPrestep;- /** An app that is a tool of its own: its page renders that tool rather than the composer (Clean up voice, Relight, Any Angle). */- tool?: "clean-voice" | "relight" | "any-angle";+ /** An app that is a tool of its own: its page renders that tool rather than the composer (Clean up voice, Relight, Any Angle, Tap to Recolor). */+ tool?: "clean-voice" | "relight" | "any-angle" | "recolor";/** The recipe its preview was made with (src/lib/catalog/preset-recipe-book.json): the route it opens on follows it. */recipe?: PresetRecipeBook;}diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.tsindex f51a3220..e0f036ce 100644--- a/src/lib/output-actions.ts+++ b/src/lib/output-actions.ts@@ -24,6 +24,7 @@ export type OutputActionId =| "edit"| "live-edit"| "relight"+ | "recolor"| "upscale"| "reference"| "grade"@@ -137,6 +138,7 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =link("edit", "Edit", `/edit?image=${q(o.url)}`);link("relight", "Relight", `/apps/app-relight?image=${q(o.url)}&gen=${q(g.id)}`);link("live-edit", "Change it as you type", `/live-edit?image=${q(o.url)}&gen=${q(g.id)}&from=library`);+ link("recolor", "Recolor", `/apps/app-tap-to-recolor?image=${q(o.url)}`);link("upscale", "Upscale", `/upscale?image=${q(o.url)}`);// Any Angle: the same photo from another camera (its 3D view is built once per photo).link("new-angle", "New angle", anyAngleHref(o.url));diff --git a/src/lib/preset-featured.ts b/src/lib/preset-featured.tsindex c1d53f33..be3267a2 100644--- a/src/lib/preset-featured.ts+++ b/src/lib/preset-featured.ts@@ -34,7 +34,7 @@ const ORDER: Record<"app" | "motion" | "effect", string[]> = {app-3d-figure app-idol app-60s-cafe app-hook-frame app-kick-ad app-graffiti-ad app-volcano-ad app-simlifeapp-pixel-game app-brick-cube app-micro-beasts app-paint-app app-social-media-icon app-victory-card app-comic-bookapp-glitter-sticker app-mukbang app-roller-coaster app-banana-eating app-sticker-pack app-plushies- app-meme-generator app-cloud-surf app-game-dump app-japanese-show app-skibidi+ app-meme-generator app-cloud-surf app-game-dump app-japanese-show app-skibidi app-tap-to-recolor`,],motion: [diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex d8595e7c..5c472d24 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -68,6 +68,7 @@ import { RESTORE_EXTRA_KEYS, restoreGraph, restoreJob, type RestoreJob } from "@import { getMaker, makerPrompt, OPEN_TARGET_PROBLEM, ORIGINALS, swapTarget } from "@/lib/catalog/genjutsu";import { CLICK_OPEN_PROBLEM, HAND_OFF, REMOVE_SCENE, REVIEW_EXTRA, reuseOf, reviewOfRun, targetPhrase, type RemovalReview } from "@/lib/catalog/remove-object";import { H3_REMOVAL_WORKFLOW } from "@/lib/catalog/character-swap";+import { RECOLOR_TAP_FIRST, recolorCoords, tapFrame } from "@/lib/catalog/recolor";import type { GenInput, MediaKind, ModelRoute, Operation } from "@/lib/catalog/types";import { imageSize } from "@/lib/image-size";import { probeMedia, type MediaInfo } from "@/lib/media-probe";@@ -1597,6 +1598,16 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,if (!restore.prefix) studioLeft.push("video2");if (!restore.reference) studioLeft.push("image");}+ // Tap to Recolor: the taps (params.points, in the pixels of the picture they were placed on, params.extra.frameWidth /+ // frameHeight) become SAM 3.1's point lists in the photo's own pixels. Only the taps say what changes.+ if (manifest.capability === "recolor") {+ const photo = ctx.media?.(String(values.image ?? ""));+ const [pos, neg] = recolorCoords(input.points, photo?.width && photo.height ? { width: photo.width, height: photo.height } : undefined, tapFrame(extra));+ if (!pos) throw new ProviderError(RECOLOR_TAP_FIRST);+ values.positiveCoords = pos;+ values.negativeCoords = neg;+ for (const k of ["frameWidth", "frameHeight", "positiveCoords", "negativeCoords"]) delete extra[k];+ }// Genjutsu's Object swap: SAM 3.1 follows what goes (params.extra.maskPrompt, or the "replace … with" part of the prompt,// as Genjutsu sends it), the reference comes in, the prompt describes the result. Insert: the painted spot and the// reference, the prompt says what appears there. Neither graph takes clicked points.diff --git a/tests/comfy-library-4.test.ts b/tests/comfy-library-4.test.tsindex 452c730f..89c30a82 100644--- a/tests/comfy-library-4.test.ts+++ b/tests/comfy-library-4.test.ts@@ -120,6 +120,7 @@ describe("round-4 ComfyUI workflows", () => {"relight-scene-read","qwen-image-21-live-edit","qwen-image-21-inpaint",+ "qwen-image-21-recolor","qwen-image-21-outpaint",// Qwen-Image 2.1's speeds, its next scene and its 16 GB route: unvalidated like their base graphs until// they run on a GPU (tests/qwen21-fast.test.ts).diff --git a/tests/library-pure.test.ts b/tests/library-pure.test.tsindex 5f569fd2..1c1f8551 100644--- a/tests/library-pure.test.ts+++ b/tests/library-pure.test.ts@@ -72,6 +72,7 @@ describe("outputActions", () => {"menu:edit","menu:relight","menu:live-edit",+ "menu:recolor","menu:upscale","menu:new-angle","menu:reference",diff --git a/tests/recolor.test.ts b/tests/recolor.test.tsnew file mode 100644index 00000000..be8a8de4--- /dev/null+++ b/tests/recolor.test.ts@@ -0,0 +1,187 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, describe, expect, it } from "vitest";+import type { GenInput, Generation } from "@/lib/catalog/types";+import type { ComfyWorkflow, ManifestWorkflow } from "@/lib/comfy";++// Tap to Recolor: tap a piece, pick a colour; SAM 3.1 makes the mask from the taps and Qwen-Image 2.1 repaints only that+// piece (qwen-image-21-recolor). Everything here runs without a GPU or a ComfyUI.+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-recolor-"));+process.env.FUOBE_DATA_DIR = tmp;+process.env.COMFYUI_URL = "http://comfy.test:8188";+const { prepareWorkflow } = await import("@/server/providers/comfyui");+const { getModel, getPreset } = await import("@/lib/catalog");+const { planGeneration } = await import("@/lib/catalog/plan");+const { outputActions } = await import("@/lib/output-actions");+const R = await import("@/lib/catalog/recolor");+afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));++const LIBRARY = path.join(process.cwd(), "workflows/comfyui");+const read = (f: string) => JSON.parse(fs.readFileSync(path.join(LIBRARY, f), "utf8"));+const manifest = read("manifest.json") as { workflows: ManifestWorkflow[] };+const entry = manifest.workflows.find((w) => w.id === "qwen-image-21-recolor")!;+const plan = (r: Parameters<typeof planGeneration>[0]) => planGeneration(r, getModel, getPreset);+const taps = [+ { x: 400, y: 600, label: "positive" as const },+ { x: 420, y: 700, label: "positive" as const },+ { x: 300, y: 900, label: "negative" as const },+];+const frame = { width: 1024, height: 1280 };++async function prepare(input: GenInput, media?: { width: number; height: number }) {+ return prepareWorkflow("qwen-image-21-recolor", { seed: 7, ...input }, {+ generationId: "g",+ op: "edit",+ upload: async (_d, _t, name) => `up_${name}`,+ media: () => (media ? { container: "image", hasVideo: false, hasAudio: false, ...media } : undefined),+ serverRam: async () => undefined,+ });+}+const at = (wf: ComfyWorkflow, key: string) => (entry.bindings[key] ?? []).map((t) => wf[t.node].inputs[t.input]);++describe("Tap to Recolor in the catalog", () => {+ it("is a Fashion app with its own page, on the open engine only", () => {+ const app = getPreset(R.RECOLOR.appId)!;+ expect(app.type).toBe("app");+ expect(app.name).toBe("Tap to Recolor");+ expect(app.category).toBe("Fashion");+ expect(app.tool).toBe("recolor");+ expect(app.cloud).toBeNull();+ expect(app.open).toMatchObject({ modelId: "oss-recolor", op: "edit" });+ expect(app.options?.map((o) => o.key)).toEqual(["item", "colour"]);+ });++ it("runs on a hidden model whose one route is the recolor graph, and asks for taps", () => {+ const m = getModel("oss-recolor")!;+ expect(m.engine).toBe("open");+ expect(m.hidden).toBe(true);+ expect(m.routes.map((r) => [r.op, r.endpoint])).toEqual([["edit", "qwen-image-21-recolor"]]);+ expect(m.options.requires).toMatchObject({ images: 1, points: true, msg: R.RECOLOR_TAP_FIRST });+ });++ it("lists the graph with its bindings, its four files and its pack, unvalidated until it runs on a GPU", () => {+ expect(entry.capability).toBe("recolor");+ expect(Object.keys(entry.bindings).sort()).toEqual(["filenamePrefix", "image", "maskGrow", "negativeCoords", "positiveCoords", "prompt", "seed", "steps"]);+ expect(entry.models.map((m) => m.file).sort()).toEqual([+ "qwen3vl_8b_int8_convrot.safetensors",+ "qwen_image_2.1_int8_convrot.safetensors",+ "qwen_image_2.1_vae_bf16.safetensors",+ "sam3.1_multiplex_fp16.safetensors",+ ]);+ for (const m of entry.models) expect(m.url, m.file).toMatch(/^https:\/\/huggingface\.co\/Comfy-Org\//);+ expect(entry.customNodes.map((c) => c.name)).toEqual(["ausboss-nodes"]);+ expect(entry.validated).toBe(false);+ expect(entry.defaults).toMatchObject({ steps: 25, maskGrow: 4 });+ const req = read("requirements.json") as { workflows: Record<string, { files: string[]; packs: Record<string, string[]> }> };+ expect(req.workflows["qwen-image-21-recolor"].files).toContain("checkpoints/sam3.1_multiplex_fp16.safetensors");+ expect(Object.keys(req.workflows["qwen-image-21-recolor"].packs)).toEqual(["ausboss-nodes"]);+ });++ it("is the same graph in the library as the hand-built one", () => {+ const hand = fs.readFileSync(path.join(process.cwd(), "scripts/comfy/hand-built/qwen-image-21-recolor.json"), "utf8");+ expect(JSON.parse(hand)).toEqual(read("qwen-image-21-recolor.json"));+ });+});++describe("Tap to Recolor's graph", () => {+ const wf = read("qwen-image-21-recolor.json") as ComfyWorkflow;+ it("masks the tapped piece with SAM 3.1's point path, crops around it, repaints it and stitches it back without a tone match", () => {+ expect(wf["14"].class_type).toBe("SAM3_Detect");+ expect(wf["14"].inputs).toMatchObject({ positive_coords: ["12", 0], negative_coords: ["13", 0], model: ["4", 0], image: ["10", 0] });+ expect(wf["14"].inputs.conditioning).toBeUndefined();+ expect(wf["20"].inputs.mask).toEqual(["15", 0]);+ expect(wf["25"].class_type).toBe("SetLatentNoiseMask");+ expect(wf["27"].inputs).toMatchObject({ steps: 25, cfg: 1, sampler_name: "euler", scheduler: "simple", denoise: 1 });+ expect(wf["30"].class_type).toBe("AUSBOSS_NODES_StitchInpaint");+ expect(wf["30"].inputs.color_match).toBe(0);+ expect(wf["90"].inputs.images).toEqual(["30", 0]);+ });++ it("binds the photo, the taps as point lists, the words, the seed and the run's prefix", async () => {+ const { workflow } = await prepare({ prompt: "Change the colour of the dress to soft ivory (#F2EBDD).", images: ["photo.png"], points: taps, extra: { frameWidth: 1024, frameHeight: 1280 } } as GenInput);+ expect(at(workflow, "image")).toEqual(["photo.png"]);+ expect(JSON.parse(String(at(workflow, "positiveCoords")[0]))).toEqual([+ { x: 400, y: 600 },+ { x: 420, y: 700 },+ ]);+ expect(JSON.parse(String(at(workflow, "negativeCoords")[0]))).toEqual([{ x: 300, y: 900 }]);+ expect(at(workflow, "prompt")).toEqual(["Change the colour of the dress to soft ivory (#F2EBDD)."]);+ expect(at(workflow, "seed")).toEqual([7]);+ expect(at(workflow, "filenamePrefix")).toEqual(["fuobe/g"]);+ // The size the taps came with isn't a graph input.+ expect(JSON.stringify(workflow)).not.toContain("frameWidth");+ });++ it("moves taps placed on a smaller copy onto the photo's own pixels, inside the picture", async () => {+ const { workflow } = await prepare({ prompt: "x", images: ["photo.png"], points: [{ x: 512, y: 640 }, { x: 2000, y: -5 }], extra: { frameWidth: 1024, frameHeight: 1280 } } as GenInput, { width: 2048, height: 2560 });+ expect(JSON.parse(String(at(workflow, "positiveCoords")[0]))).toEqual([+ { x: 1024, y: 1280 },+ { x: 2047, y: 0 },+ ]);+ expect(at(workflow, "negativeCoords")).toEqual([""]);+ });++ it("refuses a run with no tap on the piece", async () => {+ await expect(prepare({ prompt: "x", images: ["photo.png"], points: [{ x: 1, y: 1, label: "negative" }] } as GenInput)).rejects.toThrow(R.RECOLOR_TAP_FIRST);+ await expect(prepare({ prompt: "x", images: ["photo.png"] } as GenInput)).rejects.toThrow(R.RECOLOR_TAP_FIRST);+ });+});++describe("Tap to Recolor's runs", () => {+ it("builds one run per colour with the taps, and the words from the swatch", () => {+ const req = R.recolorRequest({ image: "/api/files/a.png", points: taps, frame, colour: "emerald", item: "dress" });+ expect(req).toMatchObject({ feature: "app:app-tap-to-recolor", presetId: "app-tap-to-recolor", modelId: "oss-recolor", op: "edit", engine: "open", inputs: { images: ["/api/files/a.png"] } });+ expect(req.params?.extra).toEqual({ frameWidth: 1024, frameHeight: 1280 });+ const p = plan(req);+ expect(p.op).toBe("edit");+ expect(p.prompt).toBe(+ "Change the colour of the dress to deep emerald green (#0E6B4F). Keep its fabric, weave, folds, seams, stitching, sheen, print and shadows exactly as they are, so only the colour is new.",+ );+ expect(p.params.points).toHaveLength(3);+ });++ it("names a custom colour by its nearest name with its code, and the piece in the middle when the piece is Auto", () => {+ const p = plan(R.recolorRequest({ image: "/api/files/a.png", points: taps, frame, colour: "c98b93" }));+ expect(p.prompt).toMatch(/^Change the colour of the piece in the middle of the picture to dusty rose pink \(#C98B93\)\. Keep its fabric/);+ });++ it("asks for a tap before it runs, and for a real colour", () => {+ expect(() => plan(R.recolorRequest({ image: "/api/files/a.png", points: [], frame, colour: "emerald" }))).toThrow(R.RECOLOR_TAP_FIRST);+ expect(() => R.recolorRequest({ image: "/api/files/a.png", points: taps, frame, colour: "not-a-colour" })).toThrow("Pick a colour");+ });++ it("writes only what the photo should show", () => {+ const words = [R.RECOLOR_TEMPLATE, ...R.SWATCHES.map((s) => s.words), ...R.ITEMS.map((i) => i.words)].join(" ");+ expect(words).not.toMatch(/\b(no|not|never|without|free of)\b/i);+ });+});++describe("Tap to Recolor's colours", () => {+ it("reads colour codes in their short and long forms", () => {+ expect(R.normaliseHex("#abc")).toBe("#AABBCC");+ expect(R.normaliseHex("0e6b4f")).toBe("#0E6B4F");+ expect(R.normaliseHex("#12345")).toBeNull();+ });++ it("names a code by its nearest colour", () => {+ expect(R.nearestColourName("#0E6B4F")).toBe("deep emerald green");+ expect(R.nearestColourName("#FFFFFF")).toBe("pure white");+ expect(R.nearestColourName("#D0201F")).toBe("scarlet red");+ expect(R.colourChip("#4E2E1F")).toEqual({ label: "Chocolate brown", hex: "#4E2E1F" });+ expect(R.colourChip("crimson")).toEqual({ label: "Crimson", hex: "#A3142C" });+ });++ it("keeps at most eight taps of each kind", () => {+ const many = Array.from({ length: 12 }, (_, i) => ({ x: i, y: i }));+ expect(JSON.parse(R.recolorCoords(many)[0])).toHaveLength(R.RECOLOR.maxPoints);+ });+});++describe("Recolor from the Library", () => {+ it("offers Recolor on an image result, opening the app with that picture", () => {+ const g = { id: "g1", feature: "image", kind: "image", status: "succeeded", outputs: [{ url: "/api/files/x.png", kind: "image" }], request: {}, favorite: false } as unknown as Generation;+ const a = outputActions(g, 0).find((x) => x.id === "recolor");+ expect(a).toMatchObject({ label: "Recolor", placement: "menu", href: "/apps/app-tap-to-recolor?image=%2Fapi%2Ffiles%2Fx.png" });+ });+});diff --git a/workflows/comfyui/manifest.json b/workflows/comfyui/manifest.jsonindex 98c12a40..0731148b 100644--- a/workflows/comfyui/manifest.json+++ b/workflows/comfyui/manifest.json@@ -12492,6 +12492,110 @@"validated": false,"notes": "The AusBoss pack's example \"Qwen Image 2.1 Inpaint (AusBoss)\", its two subgraphs flattened: Crop For Inpaint (context 1.6, blend 8 px, multiple 32, 1.5 MP, bicubic) -> GrowMask 8 on the crop's mask -> StringFormat \"{a} Keep everything else exactly the same.\" -> TextEncodeQwenImage21 with the crop as image 1 (resolution 0) -> VAEEncode of the crop + SetLatentNoiseMask -> QwenImage21Cache -> KSampler 25 steps, cfg 1, euler, simple -> SplitImageWithAlpha -> Stitch Inpaint (classic, no colour match) back into the full picture. mask = separate uploaded PNG, same size as image, read from the RED channel: white = change (as flux1-fill-inpaint). Removed: Mask by Touch and its SAM 3.1 model (the mask is uploaded), the speed LoRA (off in the example), the crop/pad loader (LoadImage), compare, timer and notes. Prompt: say what goes in the painted area like asking a person (\"Replace the cup with a glass of orange juice\"). Options → Decoder \"Clean\" sets vae to the Texture-Fix VAE (madebyollin, a finetuned Qwen-Image 2.1 decoder, Qwen Research License; optional file, which the GPU pre-flight asks for when Clean is picked)."},+ {+ "id": "qwen-image-21-recolor",+ "title": "Qwen-Image 2.1 Recolor (SAM 3.1 tap mask, crop, repaint, paste back)",+ "capability": "recolor",+ "file": "qwen-image-21-recolor.json",+ "source": "hand-built (scripts/comfy/hand-built/qwen-image-21-recolor.json)",+ "bindings": {+ "image": [+ {+ "node": "10",+ "input": "image"+ }+ ],+ "positiveCoords": [+ {+ "node": "12",+ "input": "value"+ }+ ],+ "negativeCoords": [+ {+ "node": "13",+ "input": "value"+ }+ ],+ "maskGrow": [+ {+ "node": "15",+ "input": "expand"+ }+ ],+ "prompt": [+ {+ "node": "22",+ "input": "values.a"+ }+ ],+ "seed": [+ {+ "node": "27",+ "input": "seed"+ }+ ],+ "steps": [+ {+ "node": "27",+ "input": "steps"+ }+ ],+ "filenamePrefix": [+ {+ "node": "90",+ "input": "filename_prefix"+ }+ ]+ },+ "outputs": [+ {+ "node": "90",+ "kind": "image"+ }+ ],+ "defaults": {+ "steps": 25,+ "maskGrow": 4+ },+ "limits": {},+ "models": [+ {+ "file": "qwen_image_2.1_int8_convrot.safetensors",+ "folder": "diffusion_models",+ "url": "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/diffusion_models/qwen_image_2.1_int8_convrot.safetensors",+ "sizeGb": 7.26+ },+ {+ "file": "qwen3vl_8b_int8_convrot.safetensors",+ "folder": "text_encoders",+ "url": "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3vl_8b_int8_convrot.safetensors",+ "sizeGb": 9.35+ },+ {+ "file": "qwen_image_2.1_vae_bf16.safetensors",+ "folder": "vae",+ "url": "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors",+ "sizeGb": 0.68+ },+ {+ "file": "sam3.1_multiplex_fp16.safetensors",+ "folder": "checkpoints",+ "url": "https://huggingface.co/Comfy-Org/sam3.1/resolve/7bb8374780a725b4353ed31f3a9395c9742b5621/checkpoints/sam3.1_multiplex_fp16.safetensors",+ "sizeGb": 1.75+ }+ ],+ "customNodes": [+ {+ "name": "ausboss-nodes",+ "repo": "https://github.com/ausboss/ComfyUI-AusBoss"+ }+ ],+ "vramGb": 20,+ "license": "Qwen Research License Agreement (Qwen-Image 2.1): NON-COMMERCIAL, research and evaluation only; Meta SAM License (SAM 3.1); AusBoss nodes MIT",+ "validated": false,+ "notes": "Tap to Recolor: qwen-image-21-inpaint with the mask made in the graph from the taps (the AusBoss example's Mask by Touch, on core SAM 3.1). positiveCoords / negativeCoords = JSON point lists [{\"x\":int,\"y\":int}] in the photo's pixels (PrimitiveStringMultiline -> SAM3_Detect point path, threshold 0.5, refine 2, one merged mask; negativeCoords may be empty) -> GrowMask maskGrow (4) so the anti-aliased edge changes too -> Crop For Inpaint (context 1.4, blend 8 px, multiple 32, 1.5 MP, bicubic) -> GrowMask 8 on the crop's mask -> StringFormat \"{a} Keep everything else in the picture exactly the same.\" -> TextEncodeQwenImage21 with the crop as image 1 (resolution 0) -> VAEEncode + SetLatentNoiseMask -> QwenImage21Cache -> KSampler 25 steps, cfg 1, euler, simple -> SplitImageWithAlpha -> Stitch Inpaint (classic, colour match 0: a tone match would pull the new colour back). Only the tapped piece is sampled and pasted, so the rest of the photo stays as it was; a tap that finds nothing gives the photo back unchanged. Prompt: \"Change the colour of <the piece> to <colour words (#hex)>. Keep its fabric, weave, folds, seams, stitching, sheen, print and shadows exactly as they are, so only the colour is new.\""+ },{"id": "qwen-image-21-outpaint","title": "Qwen-Image 2.1 Expand (outpaint-v2 LoRA, Qwen3-VL scene description)",diff --git a/workflows/comfyui/qwen-image-21-recolor.json b/workflows/comfyui/qwen-image-21-recolor.jsonnew file mode 100644index 00000000..5fc85372--- /dev/null+++ b/workflows/comfyui/qwen-image-21-recolor.json@@ -0,0 +1,327 @@+{+ "1": {+ "inputs": {+ "unet_name": "qwen_image_2.1_int8_convrot.safetensors",+ "weight_dtype": "default"+ },+ "class_type": "UNETLoader",+ "_meta": {+ "title": "Load Diffusion Model"+ }+ },+ "2": {+ "inputs": {+ "clip_name": "qwen3vl_8b_int8_convrot.safetensors",+ "type": "qwen_image",+ "device": "default"+ },+ "class_type": "CLIPLoader",+ "_meta": {+ "title": "Load CLIP (Qwen3-VL 8B)"+ }+ },+ "3": {+ "inputs": {+ "vae_name": "qwen_image_2.1_vae_bf16.safetensors"+ },+ "class_type": "VAELoader",+ "_meta": {+ "title": "Load VAE"+ }+ },+ "4": {+ "inputs": {+ "ckpt_name": "sam3.1_multiplex_fp16.safetensors"+ },+ "class_type": "CheckpointLoaderSimple",+ "_meta": {+ "title": "SAM 3.1"+ }+ },+ "10": {+ "inputs": {+ "image": "image.png"+ },+ "class_type": "LoadImage",+ "_meta": {+ "title": "Load Image - The photo"+ }+ },+ "12": {+ "inputs": {+ "value": "[{\"x\": 512, \"y\": 512}]"+ },+ "class_type": "PrimitiveStringMultiline",+ "_meta": {+ "title": "Taps on the piece (JSON points, photo pixels)"+ }+ },+ "13": {+ "inputs": {+ "value": ""+ },+ "class_type": "PrimitiveStringMultiline",+ "_meta": {+ "title": "Taps to leave out (JSON points, or empty)"+ }+ },+ "14": {+ "inputs": {+ "threshold": 0.5,+ "refine_iterations": 2,+ "individual_masks": false,+ "model": [+ "4",+ 0+ ],+ "image": [+ "10",+ 0+ ],+ "positive_coords": [+ "12",+ 0+ ],+ "negative_coords": [+ "13",+ 0+ ]+ },+ "class_type": "SAM3_Detect",+ "_meta": {+ "title": "SAM 3.1 - The tapped piece, one mask"+ }+ },+ "15": {+ "inputs": {+ "expand": 4,+ "tapered_corners": true,+ "mask": [+ "14",+ 0+ ]+ },+ "class_type": "GrowMask",+ "_meta": {+ "title": "Grow Mask - Take in the edge"+ }+ },+ "20": {+ "inputs": {+ "context_factor": 1.4,+ "blend_pixels": 8,+ "output_multiple": 32,+ "target_width": 0,+ "target_height": 0,+ "mask_grow": 0,+ "mask_blur": 0,+ "invert_mask": false,+ "context_pixels": 0,+ "target_megapixels": 1.5,+ "rescale_algorithm": "bicubic",+ "extend_left": 0,+ "extend_right": 0,+ "extend_up": 0,+ "extend_down": 0,+ "keep_inside": true,+ "image": [+ "10",+ 0+ ],+ "mask": [+ "15",+ 0+ ]+ },+ "class_type": "AUSBOSS_NODES_CropForInpaint",+ "_meta": {+ "title": "Crop For Inpaint - Crop around the piece"+ }+ },+ "21": {+ "inputs": {+ "expand": 8,+ "tapered_corners": true,+ "mask": [+ "20",+ 1+ ]+ },+ "class_type": "GrowMask",+ "_meta": {+ "title": "Grow Mask - A little past the piece"+ }+ },+ "22": {+ "inputs": {+ "f_string": "{a} Keep everything else in the picture exactly the same.",+ "values.a": ""+ },+ "class_type": "StringFormat",+ "_meta": {+ "title": "Format Text - The new colour, and keep the rest"+ }+ },+ "23": {+ "inputs": {+ "negative_prompt": "",+ "resolution": 0,+ "clip": [+ "2",+ 0+ ],+ "vae": [+ "3",+ 0+ ],+ "prompt": [+ "22",+ 0+ ],+ "images.image_1": [+ "20",+ 0+ ]+ },+ "class_type": "TextEncodeQwenImage21",+ "_meta": {+ "title": "Text Encode Qwen Image 2.1 - The crop and the new colour"+ }+ },+ "24": {+ "inputs": {+ "pixels": [+ "20",+ 0+ ],+ "vae": [+ "3",+ 0+ ]+ },+ "class_type": "VAEEncode",+ "_meta": {+ "title": "VAE Encode - The crop as the starting point"+ }+ },+ "25": {+ "inputs": {+ "samples": [+ "24",+ 0+ ],+ "mask": [+ "21",+ 0+ ]+ },+ "class_type": "SetLatentNoiseMask",+ "_meta": {+ "title": "Set Latent Noise Mask - Only the tapped piece may change"+ }+ },+ "26": {+ "inputs": {+ "device": "auto",+ "dtype": "default",+ "model": [+ "1",+ 0+ ]+ },+ "class_type": "QwenImage21Cache",+ "_meta": {+ "title": "Reference cache"+ }+ },+ "27": {+ "inputs": {+ "seed": 0,+ "steps": 25,+ "cfg": 1,+ "sampler_name": "euler",+ "scheduler": "simple",+ "denoise": 1,+ "model": [+ "26",+ 0+ ],+ "positive": [+ "23",+ 0+ ],+ "negative": [+ "23",+ 1+ ],+ "latent_image": [+ "25",+ 0+ ]+ },+ "class_type": "KSampler",+ "_meta": {+ "title": "Sampler - CFG 1, euler"+ }+ },+ "28": {+ "inputs": {+ "samples": [+ "27",+ 0+ ],+ "vae": [+ "3",+ 0+ ]+ },+ "class_type": "VAEDecode",+ "_meta": {+ "title": "Decode"+ }+ },+ "29": {+ "inputs": {+ "image": [+ "28",+ 0+ ]+ },+ "class_type": "SplitImageWithAlpha",+ "_meta": {+ "title": "Drop the alpha"+ }+ },+ "30": {+ "inputs": {+ "fix_edge_halo": false,+ "color_match": 0,+ "seam": "classic",+ "stitcher": [+ "20",+ 2+ ],+ "inpainted": [+ "29",+ 0+ ]+ },+ "class_type": "AUSBOSS_NODES_StitchInpaint",+ "_meta": {+ "title": "Stitch Inpaint - Put the piece back (no tone match)"+ }+ },+ "90": {+ "inputs": {+ "filename_prefix": "fuobe/qwen-image-21-recolor",+ "images": [+ "30",+ 0+ ]+ },+ "class_type": "SaveImage",+ "_meta": {+ "title": "Save Image"+ }+ }+}diff --git a/workflows/comfyui/requirements.json b/workflows/comfyui/requirements.jsonindex f12aefe8..26e2dcd7 100644--- a/workflows/comfyui/requirements.json+++ b/workflows/comfyui/requirements.json@@ -1,6 +1,6 @@{"v": 1,- "hash": "a7256665fdb4c8673399cc1ae5160598835ce8b61c83f967d43c9b2dfff4d6d6",+ "hash": "d4019ce4a00539396524cb5025a1db8ab85c78594fe1e5358438af8bacf3121b","comfyui": {"min":"0.42.0","testedCommit":"5841c187"},"folders": ["audio_encoders","background_removal","checkpoints","clip_vision","dbs","diffusion_models","facerestore_models","foley","frame_interpolation","geometry_estimation","insightface","latent_upscale_models","loras","mmaudio","model_patches","optical_flow","reuse","text_encoders","thinksound","upscale_models","vae"],"sentinels": ["AILab_Qwen3ASRSubtitle","AILab_Qwen3TTSVoiceClone_Advanced","AILab_Qwen3TTSVoiceDesign_Advanced","AUSBOSS_NODES_CropForInpaint","AUSBOSS_NODES_ImageCropRotatePad","AUSBOSS_NODES_StitchInpaint","Add Subtitles To Frames","Apply Whisper","CFGOverride","ClothesSegment","ComfyMathExpression","CropFuobeLive","DBSLoader","DBSSeparate","DownloadAndLoadWav2VecModel","DualModelGuider","FL_ChatterboxDialogTTS","FL_ChatterboxMultilingualTTS","FL_ChatterboxVC","GetImageRangeFromBatch","GetImageSizeAndCount","GrowMaskWithBlur","H3AdaLNLoRAFix","H3AdvancedSwapPlan","H3CharacterSwapAssemble","H3CharacterSwapController","H3CharacterSwapExpandMask","H3CharacterSwapModels","H3CharacterSwapPrepareVideo","H3CharacterSwapRecoverMasks","H3CharacterSwapSelectSubject","H3CharacterSwapSettings","H3CharacterSwapShot","H3CharacterSwapWindowPlan","H3ClipShots","H3FaceChunks","H3FaceJoin","H3FaceMaskSAM","H3FaceStitch","H3FaceTrackCrop","H3FillShots","H3GreyMannequins","H3ObjectSwapPlan","H3PeopleMask","H3RelayAppendWindow","H3RelayApplyEditMask","H3RelayApplyHistory","H3RelayExpandMask","H3RelayFinishWindows","H3RelayPrepareSource","H3RelayRecoverMasks","H3RelayReviewWindows","H3RelaySamplingMemory","H3RelaySelectMask","H3RelayTextMemory","H3RelayWindowInputs","H3RelayWindowPlan","H3RoleMask","H3SLAAttention","H3SoundtrackOrSilence","H3SourceSlice","H3SubjectPrompt","H3TrackCrops","H3TrackRoles","HunyuanDependenciesLoader","HunyuanFoleySampler","HunyuanModelLoader","INTConstant","Ideogram4Scheduler","ImageBatchExtendWithOverlap","ImageDetailContrast","ImageGridtoBatch","ImageResizeKJv2","IndexTTS2Simple","Krea2EditGroundedEncode","Krea2EditModelPatch","Krea2OstrisEditModelPatch","LTXAVTextEncoderLoader","LTXAddVideoICLoRAGuide","LTXICLoRALoaderModelOnly","LTXVAddGuide","LTXVAudioVAEDecode","LTXVAudioVAELoader","LTXVConcatAVLatent","LTXVConditioning","LTXVCropGuides","LTXVDualCFGGuider","LTXVEmptyLatentAudio","LTXVImgToVideoInplace","LTXVLatentUpsampler","LTXVPreprocess","LTXVScheduler","LTXVSeparateAVLatent","LTXVTiledFusionSampler","LatentSyncNode","LoadBackgroundRemovalModel","LoadImageFuobeLive","LoadVideoDepthAnythingModel","MMAudioFeatureUtilsLoader","MMAudioModelLoader","MMAudioSampler","MelBandRoFormerModelLoader","MelBandRoFormerSampler","Metric3D-NormalMapPreprocessor","MiniMaxH3ChainAssemble","MiniMaxH3ChainContext","MiniMaxH3ChainCurrent","MiniMaxH3ChainLoopEnd","MiniMaxH3ChainLoopStart","MiniMaxH3ChainPlanModern","MiniMaxH3ChainReview","MiniMaxH3ChainSegmentSave","MiniMaxH3ContexMaskedTarget","MiniMaxH3FantasticVideoEditLatent","MiniMaxH3GenerationProfile","MiniMaxH3LoopTrim","MiniMaxH3SourceTimeline","MiniMaxH3TurboLoRA","MiniMaxH3TurboSampler","MultiTalkModelLoader","MultiTalkWav2VecEmbeds","OpenH3RegenFastVAEDecode","OpenH3RegenFinish","OpenH3RegenLora","OpenH3RegenPrepareDraft","OpenH3RegenRefineLatent","OpenH3RegenSigmas","OpenH3RegenUpscale","OpenH3SaveRefinedLatent","Orion4D_FXMax_DCTLToneMapper","PasteBackFuobeLive","Qwen21EncodeFuobeLive","Qwen21ReferenceFuobeLive","QwenImage21Cache","REUSEEnhance","REUSELoader","RIFE VFI","RMBG","ReActorFaceSwap","RemoveBackground","SAM3_Detect","SAM3_TrackToMask","SAM3_VideoTrack","SAMLoader","SaveImageFuobeLive","SeedVR2Conditioning","SeedVR2PostProcessing","SeedVR2Preprocess","SolarRendererConditioning","SolarRendererLoraLoader","SolarRendererModel","SolarRendererSigmas","TS_ImageToSVGStringColor_Vtracer","TS_SVGStringToSVGBytesIO","TextEncodeFibo2","TextEncodeKrea2OstrisEdit","TextEncodeQwenImage21","ThinkSoundFeatureUtilsLoader","ThinkSoundModelLoader","ThinkSoundSampler","Trellis2Conditioning","Trellis2ShapeStage","Trellis2TextureStage","Trellis2UpsampleStage","VHS_BatchManager","VHS_LoadAudioUpload","VHS_LoadVideo","VHS_SelectEveryNthImage","VHS_VideoCombine","VHS_VideoInfo","VHS_VideoInfoLoaded","VRAM_Debug","VideoDepthAnythingOutput","VideoDepthAnythingProcess","VideoLengthAdjuster","ViggleTurboLora","ViggleTurboSigmas","VoxCPM2_Clone","VoxCPM2_TTS","WanVideoBlockSwap","WanVideoClipVisionEncode","WanVideoDecode","WanVideoEncode","WanVideoImageToVideoMultiTalk","WanVideoLoraSelect","WanVideoModelLoader","WanVideoPassImagesFromSamples","WanVideoSampler","WanVideoTextEncodeCached","WanVideoVAELoader","ZenImage21AdapterLoader","ZenImage21TextEncode"],@@ -382,6 +382,7 @@"qwen-image-21-outpaint-draft": {"core":["CFGGuider","CLIPLoader","GetImageSize","ImageCompositeMasked","ImageScale","InvertMask","KSamplerSelect","LoraLoaderModelOnly","ManualSigmas","QwenImage21Cache","RandomNoise","RegexReplace","SamplerCustomAdvanced","SaveImage","SplitImageWithAlpha","StringConcatenate","TextEncodeQwenImage21","TextGenerate","UNETLoader","VAEDecode","VAELoader"],"packs":{"ausboss-nodes":["AUSBOSS_NODES_CropForInpaint","AUSBOSS_NODES_ImageCropRotatePad","AUSBOSS_NODES_StitchInpaint"]},"files":["diffusion_models/qwen_image_2.1_int8_convrot.safetensors","loras/Qwen-Image-2.1-DMD2-2steps-v1.5.safetensors","loras/qwen-image-2.1-outpaint-v2.safetensors","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":["vae/texture_fix_vae_for_qwen_image_2.1_bf16.safetensors"],"vramGb":20,"isolated":false,"firstRun":[]},"qwen-image-21-outpaint-fast": {"core":["CFGGuider","CLIPLoader","GetImageSize","ImageCompositeMasked","ImageScale","InvertMask","KSamplerSelect","LoraLoaderModelOnly","ManualSigmas","QwenImage21Cache","RandomNoise","RegexReplace","SamplerCustomAdvanced","SaveImage","SplitImageWithAlpha","StringConcatenate","TextEncodeQwenImage21","TextGenerate","UNETLoader","VAEDecode","VAELoader"],"packs":{"ausboss-nodes":["AUSBOSS_NODES_CropForInpaint","AUSBOSS_NODES_ImageCropRotatePad","AUSBOSS_NODES_StitchInpaint"]},"files":["diffusion_models/qwen_image_2.1_int8_convrot.safetensors","loras/Qwen-Image-2.1-Lightning-4steps.safetensors","loras/qwen-image-2.1-outpaint-v2.safetensors","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":["vae/texture_fix_vae_for_qwen_image_2.1_bf16.safetensors"],"vramGb":20,"isolated":false,"firstRun":[]},"qwen-image-21-qma": {"core":["CLIPLoader","ImageScaleToTotalPixels","KSampler","LoadImage","LoraLoaderModelOnly","QwenImage21Cache","SaveImage","SplitImageWithAlpha","TextEncodeQwenImage21","UNETLoader","VAEDecode","VAELoader"],"packs":{},"files":["diffusion_models/qwen_image_2.1_int8_convrot.safetensors","loras/qwen-image-2.1-qma-camera-angles.safetensors","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":["vae/texture_fix_vae_for_qwen_image_2.1_bf16.safetensors"],"vramGb":20,"isolated":false,"firstRun":[],"validated":true},+ "qwen-image-21-recolor": {"core":["CLIPLoader","CheckpointLoaderSimple","GrowMask","KSampler","LoadImage","PrimitiveStringMultiline","QwenImage21Cache","SAM3_Detect","SaveImage","SetLatentNoiseMask","SplitImageWithAlpha","StringFormat","TextEncodeQwenImage21","UNETLoader","VAEDecode","VAEEncode","VAELoader"],"packs":{"ausboss-nodes":["AUSBOSS_NODES_CropForInpaint","AUSBOSS_NODES_StitchInpaint"]},"files":["checkpoints/sam3.1_multiplex_fp16.safetensors","diffusion_models/qwen_image_2.1_int8_convrot.safetensors","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[]},"qwen-image-21-relight": {"core":["BasicGuider","CLIPLoader","KSamplerSelect","LoadImage","QwenImage21Cache","RandomNoise","SamplerCustomAdvanced","SaveImage","SplitImageWithAlpha","TextEncodeQwenImage21","UNETLoader","VAEDecode","VAELoader"],"packs":{"viggle_turbo":["ViggleTurboLora","ViggleTurboSigmas"]},"files":["diffusion_models/qwen_image_2.1_int8_convrot.safetensors","loras/Qwen-Image-2.1-viggle-turbo-v0.2.1-6step-lora-r256.safetensors","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":[],"vramGb":24,"isolated":false,"firstRun":[]},"qwen-image-21-t2i": {"core":["CLIPLoader","EmptyLatentImage","KSampler","SaveImage","SplitImageWithAlpha","TextEncodeQwenImage21","UNETLoader","VAEDecode","VAELoader"],"packs":{},"files":["diffusion_models/qwen_image_2.1_int8_convrot.safetensors","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":["vae/texture_fix_vae_for_qwen_image_2.1_bf16.safetensors"],"vramGb":20,"isolated":false,"firstRun":[]},"qwen-image-21-t2i-details": {"core":["CFGGuider","CLIPLoader","EmptyLatentImage","KSamplerSelect","LoraLoaderModelOnly","ManualSigmas","RandomNoise","SamplerCustomAdvanced","SaveImage","SplitImageWithAlpha","TextEncodeQwenImage21","UNETLoader","VAEDecode","VAELoader"],"packs":{},"files":["diffusion_models/qwen_image_2.1_int8_convrot.safetensors","loras/p_q_image_2.1_6_steps_upsampled_v0.2_comfyui_bf16.safetensors","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":["vae/texture_fix_vae_for_qwen_image_2.1_bf16.safetensors"],"vramGb":20,"isolated":false,"firstRun":[]},