Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Layers: text detection on both engines, Inpaint and Enhancer jobs, element drafts

Claude7b83dc9cdcf3
diff --git a/src/components/layers/apply.ts b/src/components/layers/apply.ts
index 6223a108..c2cf56cd 100644
--- a/src/components/layers/apply.ts
+++ b/src/components/layers/apply.ts
@@ -34,6 +34,8 @@ const NEW_LAYER_NAMES: Partial<Record<LayerJob["tool"], string>> = {
upscale: "Upscaled",
relight: "Relit",
angles: "New angle",
+ inpaint: "Inpainted",
+ enhance: "Enhanced",
};
/** One image of a result, measured: its pixel size and the box of its opaque pixels. */
diff --git a/src/components/layers/editor-context.tsx b/src/components/layers/editor-context.tsx
index d7b188fe..655ac98c 100644
--- a/src/components/layers/editor-context.tsx
+++ b/src/components/layers/editor-context.tsx
@@ -66,7 +66,7 @@ export interface EditorCtx {
setSplitTarget: (id: string | null) => void;
}
-export type ToolId = "decompose" | "edit-text" | "remove-bg" | "regional" | "upscale" | "relight" | "angles" | "expand" | "grade";
+export type ToolId = "decompose" | "edit-text" | "remove-bg" | "regional" | "inpaint" | "upscale" | "enhance" | "relight" | "angles" | "expand" | "grade";
/** The tool form that started each kind of job (none: the layer card or the Generate layer dialog). */
export const TOOL_FOR_JOB: Record<LayerTool, ToolId | null> = {
@@ -82,6 +82,8 @@ export const TOOL_FOR_JOB: Record<LayerTool, ToolId | null> = {
relight: "relight",
angles: "angles",
expand: "expand",
+ inpaint: "inpaint",
+ enhance: "enhance",
};
/**
diff --git a/src/lib/layers.ts b/src/lib/layers.ts
index 91485b47..cdac73ef 100644
--- a/src/lib/layers.ts
+++ b/src/lib/layers.ts
@@ -97,7 +97,9 @@ export type LayerTool =
| "upscale"
| "relight"
| "angles"
- | "expand";
+ | "expand"
+ | "inpaint"
+ | "enhance";
export interface LayerProject {
id: string;
@@ -174,6 +176,9 @@ export interface LayerJobInput {
image?: string;
/** Reference images (per-layer generate). */
refs?: string[];
+ /** Inpaint: the painted area as a PNG the size of `image` (white = change), and `image` with that area tinted red. */
+ mask?: string;
+ sketch?: string;
prompt?: string;
nodeId?: string;
frame: Box;
@@ -193,6 +198,8 @@ export interface LayerJobInput {
pads?: { left: number; top: number; right: number; bottom: number };
feather?: number;
aspect?: string;
+ /** Enhancer: one of {@link ENHANCE_LOOKS}. */
+ look?: EnhanceLook;
};
}
@@ -210,6 +217,8 @@ export const TOOL_LABELS: Record<LayerTool, string> = {
relight: "Relight",
angles: "Angles",
expand: "Expand",
+ inpaint: "Inpaint",
+ enhance: "Enhance",
};
/** Models each tool offers, per engine (the first is the default). Checked against the catalog in tests. */
@@ -218,7 +227,8 @@ export const TOOL_MODELS: Record<LayerTool, { cloud: string[]; open: string[] }>
split: { cloud: ["seedream-5-layers", "seedream-5-flash-layers", "qwen-image-layered-cloud"], open: ["oss-qwen-layered", "oss-qwen-layered-control"] },
regenerate: { cloud: ["nano-banana-pro", "seedream-5-pro", "nano-banana-2"], open: ["oss-qwen-edit", "oss-flux-kontext"] },
"generate-layer": { cloud: ["nano-banana-pro", "seedream-5-pro"], open: ["oss-z-image-turbo", "oss-qwen-image"] },
- "text-detect": { cloud: ["ideogram-3-text-layers"], open: [] },
+ // Ideogram also lifts the text off the picture; Florence-2 only reads it, for a tenth of a cent.
+ "text-detect": { cloud: ["ideogram-3-text-layers", "florence-2-ocr"], open: ["oss-ocr-lines"] },
"text-edit": { cloud: ["nano-banana-pro", "seedream-5-pro"], open: ["oss-qwen-edit"] },
"bg-remove": { cloud: ["birefnet-cloud", "ideogram-remove-bg"], open: ["oss-rmbg"] },
regional: { cloud: ["seedream-5-pro", "nano-banana-pro"], open: ["oss-qwen-edit", "oss-flux-kontext"] },
@@ -226,8 +236,59 @@ export const TOOL_MODELS: Record<LayerTool, { cloud: string[]; open: string[] }>
relight: { cloud: ["nano-banana-pro"], open: ["oss-qwen-relight"] },
angles: { cloud: ["qwen-multiple-angles", "nano-banana-pro"], open: ["oss-qwen-edit"] },
expand: { cloud: ["nano-banana-pro"], open: ["oss-flux-fill"] },
+ // Nano Banana Pro sees the painted area tinted red (Higgsfield's nano_banana_pro_inpaint); the others take the mask itself.
+ inpaint: { cloud: ["nano-banana-pro", "flux-fill-pro", "z-image-inpaint"], open: ["oss-flux-fill"] },
+ // The retouch looks; Detail runs on {@link ENHANCE_DETAIL_MODELS}.
+ enhance: { cloud: ["nano-banana-pro", "seedream-5-pro"], open: ["oss-qwen-edit"] },
};
+// ---------------------------------------------------------------------------
+// Enhancer (Higgsfield's skin-enhancer, plus the upscalers' detail pass)
+
+export type EnhanceLook = "skin" | "glow" | "sharpen" | "detail";
+
+/** The looks: what each does, and the instruction an edit model gets (Detail has none: an upscaler restores it). */
+export const ENHANCE_LOOKS: { id: EnhanceLook; label: string; hint: string; prompt?: string }[] = [
+ {
+ id: "skin",
+ label: "Skin",
+ hint: "A natural retouch: blemishes and redness even out, pores and freckles stay",
+ prompt: "Give the portrait a subtle natural retouch: even out redness and blemishes while keeping every pore, freckle and fine line.",
+ },
+ {
+ id: "glow",
+ label: "Soft glow",
+ hint: "A soft beauty retouch with a healthy, dewy glow",
+ prompt: "Give the portrait a soft beauty retouch with a healthy dewy glow, still keeping real pore texture.",
+ },
+ {
+ id: "sharpen",
+ label: "Sharpen",
+ hint: "Removes blur and noise, restores crisp edges",
+ prompt: "Sharpen the image: remove blur, noise and compression artefacts and restore crisp detail in edges, eyes, hair, fabric and text.",
+ },
+ { id: "detail", label: "Detail", hint: "An upscaler rebuilds fine detail: twice the pixels, same place on the canvas" },
+];
+
+/** The upscalers behind the Detail look (the Upscale tool's, Topaz with its face pass first). */
+export const ENHANCE_DETAIL_MODELS: { cloud: string[]; open: string[] } = { cloud: ["topaz-image", "seedvr-image"], open: ["oss-seedvr2-image", "oss-upscale-image"] };
+
+/** The models a look offers on an engine (the first is the default). */
+export function enhanceModels(look: EnhanceLook | undefined, engine: "cloud" | "open"): string[] {
+ return look === "detail" ? ENHANCE_DETAIL_MODELS[engine] : TOOL_MODELS.enhance[engine];
+}
+
+/** The edit instruction of a retouch look, with anything the user added; null for Detail. */
+export function enhancePrompt(look: EnhanceLook | undefined, extra?: string): string | null {
+ const l = ENHANCE_LOOKS.find((x) => x.id === look) ?? ENHANCE_LOOKS[0];
+ if (!l.prompt) return null;
+ const keep =
+ l.id === "sharpen"
+ ? "Keep the content, composition, colours and lighting exactly the same."
+ : "Make the skin look like a high-end editorial photograph shot on a sharp lens — real texture, no plastic smoothing, no makeup changes. Keep the face shape, identity, expression, hair, lighting and background exactly the same.";
+ return [l.prompt, keep, extra?.trim()].filter(Boolean).join(" ");
+}
+
/** Relight looks (the Relight app's), as [label, prompt]. */
export const RELIGHT_LIGHTS: [string, string][] = [
["Golden hour", "warm golden hour sunlight"],
@@ -901,26 +962,102 @@ export interface TextBlock {
box: Box | null;
}
-/** Text blocks from a text-layers result (OutputFile.meta.textBlocks), boxes normalised against the image size. */
+/**
+ * Text blocks from a detection: Ideogram's text layers (OutputFile.meta.textBlocks) or an OCR result's
+ * lines (meta.lines, from OvisOCR3 or Florence-2). Boxes in pixels are normalised against the size the
+ * result gives (meta.size), else `image` (the picture the detector read); without either they're dropped.
+ */
export function textBlocksFrom(meta: Record<string, unknown> | undefined, image?: [number, number]): TextBlock[] {
- const raw = Array.isArray(meta?.textBlocks) ? meta.textBlocks : [];
- return raw
- .map((b): TextBlock | null => {
- if (!b || typeof b !== "object") return null;
- const o = b as Record<string, unknown>;
+ const size = asSize(meta?.size) ?? image;
+ return detectedBlocks(meta)
+ .map((o): TextBlock | null => {
const text = typeof o.text === "string" ? o.text.replace(/\s+/g, " ").trim() : "";
if (!text) return null;
- let box = asBox(o.bbox);
- if (!box && o.bbox && typeof o.bbox === "object") {
- const q = o.bbox as Record<string, unknown>;
- box = asBox([q.x, q.y, q.w ?? q.width, q.h ?? q.height]);
- }
- if (box && Math.max(...box) > 1.0001) box = image ? [box[0] / image[0], box[1] / image[1], box[2] / image[0], box[3] / image[1]] : null;
+ const raw = rawBox(o);
+ let box = raw?.box ?? null;
+ if (box && raw!.px) box = size ? [box[0] / size[0], box[1] / size[1], box[2] / size[0], box[3] / size[1]] : null;
+ if (box && (box[2] <= 0 || box[3] <= 0)) box = null;
return { text, box };
})
.filter((b): b is TextBlock => !!b);
}
+/** The items of a detection: Ideogram's text blocks or an OCR result's lines. */
+function detectedBlocks(meta: Record<string, unknown> | undefined): Record<string, unknown>[] {
+ const raw = Array.isArray(meta?.textBlocks) ? meta.textBlocks : Array.isArray(meta?.lines) ? meta.lines : [];
+ return raw.filter((b): b is Record<string, unknown> => !!b && typeof b === "object");
+}
+
+/** A block's [x, y, w, h], and whether it's in pixels (`bboxPx`, or numbers past 1) rather than 0–1. */
+function rawBox(o: Record<string, unknown>): { box: Box; px: boolean } | null {
+ let box = asBox(o.bbox);
+ if (!box && o.bbox && typeof o.bbox === "object") {
+ const q = o.bbox as Record<string, unknown>;
+ box = asBox([q.x, q.y, q.w ?? q.width, q.h ?? q.height]);
+ }
+ if (box) return { box, px: Math.max(...box) > 1.0001 };
+ const px = asBox(o.bboxPx);
+ return px ? { box: px, px: true } : null;
+}
+
+const asSize = (v: unknown): [number, number] | undefined =>
+ Array.isArray(v) && v.length === 2 && v.every((n) => finite(n) && n > 0) ? (v as [number, number]) : undefined;
+
+/** A detection gives its boxes in pixels but not the size they're of: the editor measures the picture it sent. */
+export function needsDetectedSize(meta: Record<string, unknown> | undefined): boolean {
+ return !asSize(meta?.size) && detectedBlocks(meta).some((o) => !!rawBox(o)?.px);
+}
+
+/** Lay detected blocks out in the document: their 0–1 boxes inside the frame the detector read (doc px). */
+export function placeTextBlocks(blocks: TextBlock[], frame: Box): (TextRow & { box: Box | null })[] {
+ const [fx, fy, fw, fh] = frame;
+ return blocks.map((b) => ({ from: b.text, to: b.text, box: b.box ? [fx + b.box[0] * fw, fy + b.box[1] * fh, b.box[2] * fw, b.box[3] * fh] : null }));
+}
+
+// ---------------------------------------------------------------------------
+// Inpaint
+
+/** The painted area on the picture handed to edit models without a mask input (the Inpaint studio's red). */
+export const INPAINT_TINT = "rgba(255, 59, 48, 0.55)";
+
+/** The instruction an Inpaint run sends: what goes in the painted area, and that nothing else changes. */
+export function inpaintPrompt(prompt: string, keepAlpha = false): string {
+ const p = prompt.trim().replace(/[.\s]+$/, "");
+ return `${p}. Blend it into the surroundings with matching light, perspective and grain.${keepAlpha ? " Keep the subject on a plain, even background." : ""}`;
+}
+
+// ---------------------------------------------------------------------------
+// Save as Element (a layer becomes a reusable @character, prop or style)
+
+export type LayerElementKind = "character" | "prop" | "style";
+
+export const LAYER_ELEMENT_KINDS: { kind: LayerElementKind; label: string; hint: string }[] = [
+ { kind: "character", label: "Character", hint: "A person or creature to keep the same in every picture" },
+ { kind: "prop", label: "Prop", hint: "An object or product to place in new scenes" },
+ { kind: "style", label: "Style", hint: "A look, texture or background to reuse" },
+];
+
+const GENERIC_NAME = /^(background|original image|layer \d+|cut-out|edited layer|text edit|upscaled|relit|new angle|inpainted|enhanced|edited region|expanded fill|color graded|generated layer|original|new)$/i;
+const PERSON = /\b(person|people|man|men|woman|women|girl|boy|child|kid|baby|face|portrait|model|character|subject|figure|hero|lady|guy|dancer|singer|athlete|cat|dog|animal|creature|robot|avatar|mascot)\b/i;
+const STYLE = /\b(background|backdrop|texture|pattern|sky|wall|floor|style|look|gradient|scene|landscape|scenery)\b/i;
+
+/**
+ * What “Save as element” starts with for a layer: a name from the layer (generic names like
+ * “Layer 3” become “Element”), the kind its name suggests (people → character, backdrops → style,
+ * anything else → prop) and, when the layer was generated or edited with a prompt, that prompt.
+ */
+export function elementDraft(node: Pick<LayerNode, "name" | "z" | "prompt">): { name: string; kind: LayerElementKind; description?: string } {
+ const base = node.name
+ .replace(/\s*·\s*part \d+$/i, "")
+ .replace(/\s+copy$/i, "")
+ .trim();
+ const name = (base && !GENERIC_NAME.test(base) ? base : "Element").slice(0, 60);
+ const words = `${base} ${node.prompt ?? ""}`;
+ const kind: LayerElementKind = PERSON.test(words) ? "character" : STYLE.test(words) || (node.z === 0 && GENERIC_NAME.test(base)) ? "style" : "prop";
+ const description = node.prompt?.trim().slice(0, 500);
+ return { name, kind, ...(description ? { description } : {}) };
+}
+
// ---------------------------------------------------------------------------
// Decomposition states (Higgsfield's copy)
@@ -950,7 +1087,7 @@ export function jobStatusText(r: LayerJobResult | null | undefined): string {
}
/** Tools whose result changes the document when it lands (text detection only fills the Edit text list). */
-export const APPLIES_TO_DOC = new Set<LayerTool>(["decompose", "split", "regenerate", "generate-layer", "text-edit", "bg-remove", "regional", "upscale", "relight", "angles", "expand"]);
+export const APPLIES_TO_DOC = new Set<LayerTool>(["decompose", "split", "regenerate", "generate-layer", "text-edit", "bg-remove", "regional", "upscale", "relight", "angles", "expand", "inpaint", "enhance"]);
// ---------------------------------------------------------------------------
// Zip (stored): built in the browser from rendered PNGs
diff --git a/src/server/layers.ts b/src/server/layers.ts
index 7a8ac5d2..c2b71d49 100644
--- a/src/server/layers.ts
+++ b/src/server/layers.ts
@@ -9,7 +9,10 @@ import {
clampLayers,
CUTOUT_MODELS,
defaultLayers,
+ enhanceModels,
+ enhancePrompt,
initialDoc,
+ inpaintPrompt,
layersModelFor,
MAX_NODES,
RELIGHT_DIRECTIONS,
@@ -136,7 +139,7 @@ export function parseDoc(v: unknown): LayerDoc | null {
return doc;
}
-const TOOLS = ["decompose", "split", "regenerate", "generate-layer", "text-detect", "text-edit", "bg-remove", "regional", "upscale", "relight", "angles", "expand"] as const satisfies readonly LayerTool[];
+const TOOLS = ["decompose", "split", "regenerate", "generate-layer", "text-detect", "text-edit", "bg-remove", "regional", "upscale", "relight", "angles", "expand", "inpaint", "enhance"] as const satisfies readonly LayerTool[];
export const JobInputSchema = z.object({
tool: z.enum(TOOLS),
@@ -144,6 +147,8 @@ export const JobInputSchema = z.object({
modelId: z.string().max(80).optional(),
image: FileUrl.optional(),
refs: z.array(FileUrl).max(3).optional(),
+ mask: FileUrl.optional(),
+ sketch: FileUrl.optional(),
prompt: clamped(2000).optional(),
nodeId: z.string().max(40).optional(),
frame: BoxSchema,
@@ -164,6 +169,7 @@ export const JobInputSchema = z.object({
pads: z.object({ left: z.number().int().min(0).max(4096), top: z.number().int().min(0).max(4096), right: z.number().int().min(0).max(4096), bottom: z.number().int().min(0).max(4096) }).optional(),
feather: num.min(0).max(500).optional(),
aspect: z.string().regex(/^\d+(\.\d+)?:\d+(\.\d+)?$/).max(20).optional(),
+ look: z.enum(["skin", "glow", "sharpen", "detail"]).optional(),
})
.optional(),
});
@@ -172,13 +178,8 @@ export const JobInputSchema = z.object({
// Jobs → generation requests (pure: no database)
/** The tool's model on this engine: the one asked for (when the tool offers it) or its default. */
-export function toolModel(tool: LayerTool, engine: Engine, modelId?: string): ModelDef {
- const list = TOOL_MODELS[tool][engine];
- if (!list.length) {
- throw new LayersError(
- tool === "text-detect" ? "Text detection runs on the cloud engine (Ideogram). On open source, type the lines you want to change." : `${TOOL_LABELS[tool]} has no ${engine === "open" ? "open-source" : "cloud"} model yet`,
- );
- }
+export function toolModel(tool: LayerTool, engine: Engine, modelId?: string, list: string[] = TOOL_MODELS[tool][engine]): ModelDef {
+ if (!list.length) throw new LayersError(`${TOOL_LABELS[tool]} has no ${engine === "open" ? "open-source" : "cloud"} model yet`);
if (modelId && !list.includes(modelId)) throw new LayersError("That model can't run this tool", 400);
const m = getModel(modelId ?? list[0]);
if (!m) throw new LayersError("That model isn't in the catalog", 400);
@@ -274,8 +275,10 @@ export function jobSteps(input: LayerJobInput, opts: { batchTitle?: string } = {
break;
}
case "text-detect": {
+ // OCR models (OvisOCR3, Florence-2) read the lines; Ideogram's text layers also lift them off the picture.
const model = toolModel(tool, engine, input.modelId);
- add("detect", base(model, { op: "text-layers", inputs: { images: [needImage()] }, params: aspectFor(model) }));
+ const ocr = model.routes.some((r) => r.op === "ocr");
+ add("detect", base(model, { op: ocr ? "ocr" : "text-layers", inputs: { images: [needImage()] }, ...(ocr ? {} : { params: aspectFor(model) }) }));
break;
}
case "text-edit": {
@@ -330,6 +333,28 @@ export function jobSteps(input: LayerJobInput, opts: { batchTitle?: string } = {
if (s.keepAlpha) cutout("angle");
break;
}
+ case "inpaint": {
+ if (!input.mask) throw new LayersError("Paint over the area to change first", 400);
+ if (!prompt) throw new LayersError("Say what should fill the painted area", 400);
+ const model = toolModel(tool, engine, input.modelId);
+ // Mask models take the mask; edit models are shown the painted area tinted red (applySketch picks).
+ add("inpaint", base(model, { op: "inpaint", prompt: inpaintPrompt(prompt, s.keepAlpha), inputs: { images: [needImage()], mask: input.mask, ...(input.sketch ? { sketch: input.sketch } : {}) }, params: aspectFor(model) }));
+ if (s.keepAlpha) cutout("inpaint");
+ break;
+ }
+ case "enhance": {
+ const look = s.look ?? "skin";
+ const ask = enhancePrompt(look, prompt);
+ const model = toolModel(tool, engine, input.modelId, enhanceModels(look, engine));
+ if (!ask) {
+ // Detail: an upscaler rebuilds it (the layer keeps its place with more pixels, as Upscale does).
+ add("enhance", base(model, { op: "upscale-image", inputs: { images: [needImage()] }, params: aspectFor(model) }));
+ break;
+ }
+ add("enhance", base(model, { op: "edit", prompt: s.keepAlpha ? `${ask} Keep the subject on a plain, even background.` : ask, inputs: { images: [needImage()] }, params: aspectFor(model) }));
+ if (s.keepAlpha) cutout("enhance");
+ break;
+ }
case "expand": {
const model = toolModel(tool, engine, input.modelId);
const fill = "Continue the scene naturally beyond every edge with matching perspective, lighting, textures and grain. Keep the original picture untouched and add no new people or text.";
diff --git a/tests/layers-api.test.ts b/tests/layers-api.test.ts
index 36f5a2ff..76825ed7 100644
--- a/tests/layers-api.test.ts
+++ b/tests/layers-api.test.ts
@@ -3,7 +3,7 @@ import os from "node:os";
import path from "node:path";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import type { Generation } from "@/lib/catalog/types";
-import { initialDoc, nodesFromOutputs, placeOutput, type LayerDoc, type LayerJob, type LayerJobInput, type LayerProject, type LayerProjectView } from "@/lib/layers";
+import { elementDraft, initialDoc, nodesFromOutputs, placeOutput, placeTextBlocks, textBlocksFrom, type LayerDoc, type LayerJob, type LayerJobInput, type LayerProject, type LayerProjectView } from "@/lib/layers";
// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.
vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
@@ -129,7 +129,7 @@ describe("job steps", () => {
expect(r[0].request).toMatchObject({ modelId: "nano-banana-pro", op: "edit", inputs: { images: ["/api/files/mug.png"] } });
});
- it("edits text with the fixed instruction on both engines; detection is cloud only", () => {
+ it("edits text with the fixed instruction on both engines; detection reads the lines on either", () => {
const rows = [{ from: "SALE", to: "OPEN" }];
expect(steps({ tool: "text-edit", settings: { rows } })[0].request).toMatchObject({
modelId: "nano-banana-pro",
@@ -138,8 +138,51 @@ describe("job steps", () => {
});
expect(steps({ tool: "text-edit", engine: "open", settings: { rows } })[0].request.modelId).toBe("oss-qwen-edit");
expect(() => steps({ tool: "text-edit", settings: { rows: [{ from: "SALE", to: "SALE" }] } })).toThrow(/Change a line/);
- expect(steps({ tool: "text-detect" })[0].request).toMatchObject({ modelId: "ideogram-3-text-layers", op: "text-layers" });
- expect(() => steps({ tool: "text-detect", engine: "open" })).toThrow(/cloud engine/);
+ expect(steps({ tool: "text-detect", settings: { aspect: "16:9" } })[0].request).toMatchObject({ modelId: "ideogram-3-text-layers", op: "text-layers", params: { aspectRatio: "16:9" } });
+ // OCR models read the lines (no shape to send): Florence-2 on the cloud, OvisOCR3 on ComfyUI.
+ const florence = steps({ tool: "text-detect", modelId: "florence-2-ocr", settings: { aspect: "16:9" } })[0].request;
+ expect(florence).toMatchObject({ modelId: "florence-2-ocr", op: "ocr", inputs: { images: ["/api/files/a.png"] } });
+ expect(florence.params).toBeUndefined();
+ expect(steps({ tool: "text-detect", engine: "open" })[0].request).toMatchObject({ modelId: "oss-ocr-lines", op: "ocr" });
+ expect(() => steps({ tool: "text-detect", engine: "open", modelId: "ideogram-3-text-layers" })).toThrow(/can't run this tool/);
+ });
+
+ it("inpaints the painted area: the mask for mask models, the red-tinted copy for edit models", () => {
+ const paint = { tool: "inpaint" as const, prompt: "a vase of tulips", mask: "/api/files/m.png", sketch: "/api/files/s.png" };
+ const cloud = steps(paint)[0].request;
+ expect(cloud).toMatchObject({
+ modelId: "nano-banana-pro",
+ op: "inpaint",
+ prompt: "a vase of tulips. Blend it into the surroundings with matching light, perspective and grain.",
+ inputs: { images: ["/api/files/a.png"], mask: "/api/files/m.png", sketch: "/api/files/s.png" },
+ });
+ expect(steps({ ...paint, modelId: "flux-fill-pro" })[0].request).toMatchObject({ modelId: "flux-fill-pro", op: "inpaint" });
+ const open = steps({ ...paint, engine: "open", settings: { keepAlpha: true } });
+ expect(open.map((x) => [x.key, x.request.modelId, x.request.op])).toEqual([
+ ["inpaint", "oss-flux-fill", "inpaint"],
+ ["cutout", "oss-rmbg", "bg-remove"],
+ ]);
+ expect(open[0].request.prompt).toMatch(/Keep the subject on a plain, even background\.$/);
+ expect(open[1]).toMatchObject({ after: "inpaint", chain: [{ slot: "images" }] });
+ expect(() => steps({ ...paint, mask: undefined })).toThrow(/Paint over the area/);
+ expect(() => steps({ ...paint, prompt: " " })).toThrow(/fill the painted area/);
+ });
+
+ it("enhances with a retouch instruction, or restores detail with an upscaler", () => {
+ const skin = steps({ tool: "enhance", settings: { look: "skin" } })[0].request;
+ expect(skin).toMatchObject({ modelId: "nano-banana-pro", op: "edit", inputs: { images: ["/api/files/a.png"] } });
+ expect(skin.prompt).toMatch(/^Give the portrait a subtle natural retouch.*Keep the face shape, identity/);
+ expect(steps({ tool: "enhance", engine: "open", settings: { look: "sharpen" } })[0].request).toMatchObject({ modelId: "oss-qwen-edit", op: "edit" });
+ expect(steps({ tool: "enhance", engine: "open", settings: { look: "sharpen" } })[0].request.prompt).toMatch(/^Sharpen the image.*colours and lighting exactly the same\.$/);
+ expect(steps({ tool: "enhance", prompt: "keep the freckles", settings: { look: "glow" } })[0].request.prompt).toMatch(/keep the freckles$/);
+ // Detail: the Upscale tool's models (Topaz first, with its face pass), no instruction.
+ const detail = steps({ tool: "enhance", settings: { look: "detail" } })[0].request;
+ expect(detail).toMatchObject({ modelId: "topaz-image", op: "upscale-image" });
+ expect(detail.prompt).toBeUndefined();
+ expect(steps({ tool: "enhance", engine: "open", settings: { look: "detail" } })[0].request.modelId).toBe("oss-seedvr2-image");
+ expect(() => steps({ tool: "enhance", modelId: "topaz-image", settings: { look: "skin" } })).toThrow(/can't run this tool/);
+ // A transparent layer gets its cut-out back after a retouch.
+ expect(steps({ tool: "enhance", settings: { look: "skin", keepAlpha: true } }).map((x) => x.key)).toEqual(["enhance", "cutout"]);
});
it("hands layers to the existing upscale, relight, angles, background and expand models", () => {
@@ -239,6 +282,49 @@ describe("layers API", () => {
expect(((await res.json()) as { error: string }).error).toMatch(/can only be decomposed once/);
});
+ it("reads the text on the open engine and inpaints with either kind of model, in demo mode", async () => {
+ const frame = [0, 0, 1920, 1080];
+ let res = await jobs.POST(req("POST", { tool: "text-detect", engine: "open", image: source, frame, label: "Detect text" }), ctx({ id }));
+ expect(res.status).toBe(201);
+ const detect = (await res.json()) as LayerJob;
+ const g = await settle(detect.generationIds[0]);
+ expect(g).toMatchObject({ modelId: "oss-ocr-lines", op: "ocr", status: "succeeded" });
+ // What Edit text lists: the lines with their boxes, laid out in the frame the detector read.
+ const rows = placeTextBlocks(textBlocksFrom(g.outputs[0].meta), detect.frame);
+ expect(rows.length).toBeGreaterThan(1);
+ expect(rows[0].box).toEqual([expect.closeTo(153.6, 1), expect.closeTo(108, 1), expect.closeTo(998.4, 1), expect.closeTo(97.2, 1)]);
+
+ // Inpaint: Nano Banana Pro is shown the painted area tinted red; FLUX Fill [pro] takes the mask itself.
+ const mask = upload();
+ const sketch = upload();
+ const paint = { tool: "inpaint", engine: "cloud", image: source, mask, sketch, prompt: "a vase of tulips", frame, settings: { aspect: "16:9" } };
+ res = await jobs.POST(req("POST", paint), ctx({ id }));
+ expect(res.status).toBe(201);
+ const nano = gens.getGeneration(((await res.json()) as LayerJob).generationIds[0])!;
+ expect(nano).toMatchObject({ modelId: "nano-banana-pro", op: "edit" });
+ expect(nano.request.inputs).toMatchObject({ images: [source], sketch });
+ expect(nano.prompt).toMatch(/Only change the region tinted red in image 2/);
+ res = await jobs.POST(req("POST", { ...paint, modelId: "flux-fill-pro" }), ctx({ id }));
+ const fill = gens.getGeneration(((await res.json()) as LayerJob).generationIds[0])!;
+ expect(fill).toMatchObject({ modelId: "flux-fill-pro", op: "inpaint" });
+ expect(fill.request.inputs).toMatchObject({ images: [source], mask });
+ // Only stored files can be painted with.
+ res = await jobs.POST(req("POST", { ...paint, mask: "http://evil.example/m.png" }), ctx({ id }));
+ expect(res.status).toBe(400);
+ });
+
+ it("saves a layer's PNG as an element", async () => {
+ const elements = await import("@/app/api/elements/route");
+ const png = upload();
+ const draft = elementDraft({ name: "Woman in red coat · part 1", z: 2 });
+ const res = await elements.POST(new Request("http://localhost/api/elements", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...draft, references: [png] }) }));
+ expect(res.status).toBe(201);
+ const el = (await res.json()) as { id: string; handle: string; kind: string; references: string[] };
+ expect(el).toMatchObject({ handle: "Woman_in_red_coat", kind: "character", references: [png] });
+ // The element keeps its PNG: the file counts as in use.
+ expect(gens.assetInUse(png.split("/").pop()!.replace(/\.png$/, ""))).toBeTruthy();
+ });
+
it("autosaves into the head version and refuses stale or foreign documents", async () => {
const moved: LayerDoc = { ...view.doc, nodes: view.doc.nodes.map((x, i) => (i === 1 ? { ...x, x: x.x + 40, name: "Hero" } : x)) };
let res = await one.PATCH(req("PATCH", { doc: moved, versionId: view.headVersionId, name: "Summer poster v2" }), ctx({ id }));
diff --git a/tests/layers-apply.test.ts b/tests/layers-apply.test.ts
index bb0c9483..a787c5e3 100644
--- a/tests/layers-apply.test.ts
+++ b/tests/layers-apply.test.ts
@@ -166,6 +166,19 @@ describe("laying out the other tools", () => {
["Cut-out", false],
]);
});
+
+ it("lays Inpaint and Enhancer results out like the other edits", () => {
+ const d = doc([node("bg", 0, { w: 400, h: 300 }), node("face", 1, { x: 40, y: 20 })], 400, 300);
+ // On a layer: its next revision, the prompt kept with it.
+ const enh = applyMeasured(d, job("enhance", { nodeId: "face", frame: [40, 20, 100, 50], label: "Skin" }), one("/api/files/skin.png", [200, 100]), opts());
+ expect(enh.doc.nodes[1]).toMatchObject({ src: "/api/files/skin.png", revision: 1, x: 40, y: 20, w: 100, h: 50 });
+ expect(enh.message).toBe("face: skin done");
+ // On the whole picture: a new layer on top, called what it is.
+ const ip = applyMeasured(d, job("inpaint", { label: "Inpaint", settings: { prompt: "a vase" } }), one("/api/files/ip.png", [400, 300]), opts());
+ expect(ip.doc.nodes[2]).toMatchObject({ name: "Inpainted", x: 0, y: 0, w: 400, h: 300 });
+ expect(ip.doc.nodes[2].revisions[0].prompt).toBe("a vase");
+ expect(imagesToMeasure(job("inpaint"))).toEqual([{ url: "/api/files/out.png", alpha: false }]);
+ });
});
describe("a result landing on a document edited meanwhile", () => {
diff --git a/tests/layers-comfy.test.ts b/tests/layers-comfy.test.ts
index 6246db25..025146a3 100644
--- a/tests/layers-comfy.test.ts
+++ b/tests/layers-comfy.test.ts
@@ -12,7 +12,7 @@ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-layers-comfy-"));
process.env.FUOBE_DATA_DIR = dir;
process.env.COMFYUI_URL = "http://127.0.0.1:9";
-const { prepareWorkflow } = await import("@/server/providers/comfyui");
+const { collectOutputs, getWorkflow, prepareWorkflow } = await import("@/server/providers/comfyui");
const { jobSteps } = await import("@/server/layers");
const { getModel } = await import("@/lib/catalog");
@@ -23,7 +23,7 @@ async function bind(req: GenerationRequest) {
expect(route.provider).toBe("comfyui");
const res = await prepareWorkflow(
route.endpoint,
- { prompt: req.prompt, images: req.inputs?.images, ...req.params },
+ { prompt: req.prompt, images: req.inputs?.images, ...(req.inputs?.mask ? { mask: req.inputs.mask } : {}), ...req.params },
{ generationId: "gen1", op: req.op!, upload: async (_d, _t, name) => `up_${name}`, media: () => undefined, serverRam: async () => undefined },
);
const wf = res.workflow as Record<string, { inputs: Record<string, unknown> }>;
@@ -78,3 +78,67 @@ describe("Layers on the open engine", () => {
expect(text("prompt")).toEqual(["Preserve the original design and change only the requested text. Change “SALE” to “OPEN”."]);
});
});
+
+describe("Inpaint and Enhancer on the open engine", () => {
+ it("inpaint: the picture, its painted mask and the prompt reach FLUX Fill", async () => {
+ const req = step({ tool: "inpaint", prompt: "a vase of tulips", mask: "/api/files/m.png", sketch: "/api/files/s.png" });
+ const at = await bind(req);
+ expect(at("image")).toEqual(["/api/files/a.png"]);
+ expect(at("mask")).toEqual(["/api/files/m.png"]);
+ expect(String(at("prompt")[0])).toMatch(/^a vase of tulips\. Blend it into the surroundings/);
+ });
+
+ it("enhancer: a retouch reaches Qwen-Image-Edit, Detail the SeedVR2 upscaler", async () => {
+ const skin = await bind(step({ tool: "enhance", settings: { look: "skin" } }));
+ expect(String(skin("prompt")[0])).toMatch(/^Give the portrait a subtle natural retouch/);
+ const detail = await bind(step({ tool: "enhance", settings: { look: "detail" } }));
+ expect(detail("image")).toEqual(["/api/files/a.png"]);
+ });
+});
+
+describe("Text detection on the open engine (ocr-lines-qwen35)", () => {
+ const file = (filename: string) => ({ filename, subfolder: "fuobe", type: "output" });
+ const done = (outputs: Record<string, Record<string, unknown>>) => ({ status: { status_str: "success", completed: true }, outputs });
+
+ it("binds the picture to OvisOCR3 with the workflow's own instruction, checkpoint and size", async () => {
+ const req = step({ tool: "text-detect" });
+ expect(req).toMatchObject({ modelId: "oss-ocr-lines", op: "ocr", inputs: { images: ["/api/files/a.png"] } });
+ const at = await bind(req);
+ expect(at("image")).toEqual(["/api/files/a.png"]);
+ expect(at("checkpoint")).toEqual(["ovisocr3_0.8b_bf16.safetensors"]);
+ expect(at("maxSize")).toEqual([1280]);
+ expect(at("maxTokens")).toEqual([2048]);
+ expect(String(at("instruction")[0])).toMatch(/scaled to \[0, 1000\)/);
+ });
+
+ it("reads the answer into lines with 0–1 boxes, and folds the frame in as the size", () => {
+ const outs = collectOutputs(
+ done({
+ "8": { text: ['{"width": 1280, "height": 960, "coords": "relative-1000"}'] },
+ "5": { text: ['```json\n[{"bbox_2d": [62, 96, 594, 205], "text_content": "SUMMER SALE"}, {"bbox_2d": [700, 820, 940, 880], "text_content": "SAVE 30%"}]\n```'], files: [file("ocr_00001_.json")] },
+ }),
+ getWorkflow("ocr-lines-qwen35").manifest,
+ "http://comfy.test:8188",
+ );
+ expect(outs).toHaveLength(1);
+ expect(outs[0]).toMatchObject({
+ kind: "text",
+ contentType: "text/plain",
+ text: "SUMMER SALE\nSAVE 30%",
+ meta: {
+ size: [1280, 960],
+ lines: [
+ { text: "SUMMER SALE", bbox: [0.062, 0.096, 0.532, 0.109] },
+ { text: "SAVE 30%", bbox: [0.7, 0.82, 0.24, 0.06] },
+ ],
+ },
+ });
+ // The text travels as plain lines (like Florence-2's), not as the model's JSON file.
+ expect(outs[0].url.startsWith("data:text/plain;base64,")).toBe(true);
+ });
+
+ it("keeps an answer that isn't a list as its words, with no lines", () => {
+ const outs = collectOutputs(done({ "5": { text: ["Sorry, I can't read this."], files: [file("ocr_00002_.json")] } }), getWorkflow("ocr-lines-qwen35").manifest);
+ expect(outs[0]).toMatchObject({ text: "Sorry, I can't read this.", meta: { lines: [], unreadable: true } });
+ });
+});
diff --git a/tests/layers.test.ts b/tests/layers.test.ts
index a7538c52..12b369c6 100644
--- a/tests/layers.test.ts
+++ b/tests/layers.test.ts
@@ -42,6 +42,14 @@ import {
toLocal,
TOOL_MODELS,
zipPlan,
+ ENHANCE_DETAIL_MODELS,
+ ENHANCE_LOOKS,
+ elementDraft,
+ enhanceModels,
+ enhancePrompt,
+ inpaintPrompt,
+ needsDetectedSize,
+ placeTextBlocks,
coverage,
defaultLayers,
exportScale,
@@ -430,6 +438,59 @@ describe("edit text", () => {
]);
expect(textBlocksFrom(undefined)).toEqual([]);
});
+
+ it("reads OCR lines too: 0–1 boxes as they are, Florence-2's pixel boxes against the size", () => {
+ // OvisOCR3 / Florence-2 with a size: fractions already.
+ const lines = { lines: [{ text: "SUMMER SALE", bbox: [0.062, 0.096, 0.532, 0.109] }, { text: "no box" }], size: [1280, 960] };
+ expect(textBlocksFrom(lines)).toEqual([
+ { text: "SUMMER SALE", box: [0.062, 0.096, 0.532, 0.109] },
+ { text: "no box", box: null },
+ ]);
+ expect(needsDetectedSize(lines)).toBe(false);
+ // Florence-2 without the image's size: pixels in bboxPx, read against the picture the editor sent.
+ const px = { lines: [{ text: "Hi", bboxPx: [100, 50, 200, 100] }] };
+ expect(needsDetectedSize(px)).toBe(true);
+ expect(textBlocksFrom(px, [1000, 500])).toEqual([{ text: "Hi", box: [0.1, 0.1, 0.2, 0.2] }]);
+ expect(textBlocksFrom(px)).toEqual([{ text: "Hi", box: null }]);
+ expect(textBlocksFrom({ ...px, size: [2000, 1000] })).toEqual([{ text: "Hi", box: [0.05, 0.05, 0.1, 0.1] }]);
+ // Ideogram's object boxes in fractions need no size.
+ expect(needsDetectedSize({ textBlocks: [{ text: "x", bbox: { x: 0.1, y: 0.2, width: 0.3, height: 0.1 } }] })).toBe(false);
+ });
+
+ it("lays detected lines out in the frame the detector read, like the cloud route's blocks", () => {
+ const rows = placeTextBlocks(
+ [
+ { text: "SUMMER SALE", box: [0.1, 0.2, 0.5, 0.1] },
+ { text: "fine print", box: null },
+ ],
+ [100, 50, 800, 400],
+ );
+ expect(rows).toEqual([
+ { from: "SUMMER SALE", to: "SUMMER SALE", box: [180, 130, 400, 40] },
+ { from: "fine print", to: "fine print", box: null },
+ ]);
+ // Nothing changed yet: Generate has nothing to send.
+ expect(textEditPrompt(rows)).toBe("Preserve the original design and change only the requested text.");
+ });
+});
+
+describe("inpaint and Save as element", () => {
+ it("asks for the painted area only", () => {
+ expect(inpaintPrompt(" a red scarf. ")).toBe("a red scarf. Blend it into the surroundings with matching light, perspective and grain.");
+ expect(inpaintPrompt("a hat", true)).toMatch(/grain\. Keep the subject on a plain, even background\.$/);
+ });
+
+ it("names a layer's element and guesses its kind", () => {
+ expect(elementDraft({ name: "Woman in red coat", z: 2 })).toEqual({ name: "Woman in red coat", kind: "character" });
+ expect(elementDraft({ name: "Guitar · part 2", z: 3 })).toEqual({ name: "Guitar", kind: "prop" });
+ expect(elementDraft({ name: "Sky gradient copy", z: 1 })).toEqual({ name: "Sky gradient", kind: "style" });
+ // Generic names: the bottom layer reads as a backdrop, anything else as a prop; prompts say more.
+ expect(elementDraft({ name: "Background", z: 0 })).toEqual({ name: "Element", kind: "style" });
+ expect(elementDraft({ name: "Layer 4", z: 4 })).toEqual({ name: "Element", kind: "prop" });
+ expect(elementDraft({ name: "Generated layer", z: 5, prompt: "a golden retriever puppy" })).toEqual({ name: "Element", kind: "prop", description: "a golden retriever puppy" });
+ expect(elementDraft({ name: "Generated layer", z: 5, prompt: "a smiling dog" })).toMatchObject({ kind: "character" });
+ expect(elementDraft({ name: "x".repeat(90), z: 1 }).name).toHaveLength(60);
+ });
});
describe("Open in Layers", () => {
@@ -450,7 +511,7 @@ describe("tools and prices", () => {
split: ["layers"],
regenerate: ["edit"],
"generate-layer": ["t2i", "edit"],
- "text-detect": ["text-layers"],
+ "text-detect": ["text-layers", "ocr"],
"text-edit": ["edit"],
"bg-remove": ["bg-remove"],
regional: ["edit"],
@@ -458,6 +519,8 @@ describe("tools and prices", () => {
relight: ["edit"],
angles: ["edit"],
expand: ["edit", "outpaint"],
+ inpaint: ["inpaint", "edit"],
+ enhance: ["edit"],
};
it("offers catalog models of the right engine and operation for every tool", () => {
@@ -473,6 +536,24 @@ describe("tools and prices", () => {
}
});
+ it("runs the Enhancer's Detail look on catalog upscalers", () => {
+ for (const engine of ["cloud", "open"] as const) {
+ for (const id of ENHANCE_DETAIL_MODELS[engine]) {
+ const m = getModel(id);
+ expect(m?.engine, id).toBe(engine);
+ expect(supportsOp(m!, "upscale-image"), id).toBe(true);
+ }
+ expect(enhanceModels("detail", engine)).toBe(ENHANCE_DETAIL_MODELS[engine]);
+ expect(enhanceModels("skin", engine)).toBe(TOOL_MODELS.enhance[engine]);
+ }
+ expect(enhancePrompt("detail")).toBeNull();
+ expect(enhancePrompt("glow", " ")).toBe(
+ "Give the portrait a soft beauty retouch with a healthy dewy glow, still keeping real pore texture. Make the skin look like a high-end editorial photograph shot on a sharp lens — real texture, no plastic smoothing, no makeup changes. Keep the face shape, identity, expression, hair, lighting and background exactly the same.",
+ );
+ // Every look but Detail has an instruction.
+ expect(ENHANCE_LOOKS.filter((l) => !l.prompt).map((l) => l.id)).toEqual(["detail"]);
+ });
+
it("prices a decomposition per layer", () => {
expect(decomposeCost("seedream-5-layers", 8)).toBeCloseTo(0.27);
expect(decomposeCost("seedream-5-layers", 8, "2K")).toBeCloseTo(0.54);