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.

Open models: Ideogram 4 for text to image, with captions written from your words

Adarsh78ee7522719c
diff --git a/scripts/comfy/build-library.mjs b/scripts/comfy/build-library.mjs
index 2c077e4d..597ea352 100644
--- a/scripts/comfy/build-library.mjs
+++ b/scripts/comfy/build-library.mjs
@@ -131,6 +131,8 @@ export const BINDING_KEYS = new Set([
'historyVideo', 'historyStart', 'historyLength', 'keyFrame', 'spanFrames', 'tailStart', 'tailFrames', 'prevMask',
// Originals O11: Fuobe Speak's InfiniteTalk recipe on kijai's wrapper, the face mosaic
'scheduler', 'motionFrame', 'colormatch', 'audioCfg', 'threshold', 'mosaicScale',
+ // The owner's SOTA image families (2026-10-31): Ideogram 4's sampling preset
+ 'preset',
]);
const readJson = (p, fallback) => (fs.existsSync(p) ? JSON.parse(fs.readFileSync(p, 'utf8')) : fallback);
@@ -154,7 +156,11 @@ async function hfTreeSize(url) {
async function hfSize(url, cache) {
if (cache[url] !== undefined && !cache[url]?.error) return cache[url];
try {
- const res = await fetch(url, { method: 'HEAD', redirect: 'manual' });
+ let res = await fetch(url, { method: 'HEAD', redirect: 'manual' });
+ // A renamed repository answers with a redirect to its new name on huggingface.co (Comfy-Org/flux2-dev → Flux-2-Dev):
+ // follow that one. The download's own redirect, to the CDN, carries the size and isn't followed.
+ const moved = res.headers.get('location');
+ if ([301, 302, 307, 308].includes(res.status) && moved?.startsWith('/')) res = await fetch(new URL(moved, url), { method: 'HEAD', redirect: 'manual' });
const linked = res.headers.get('x-linked-size');
const len = linked || (res.status === 200 ? res.headers.get('content-length') : null);
if (res.status === 401 || res.status === 403) {
diff --git a/scripts/comfy/hand-built/ideogram4-t2i.json b/scripts/comfy/hand-built/ideogram4-t2i.json
new file mode 100644
index 00000000..4ec80cfb
--- /dev/null
+++ b/scripts/comfy/hand-built/ideogram4-t2i.json
@@ -0,0 +1,387 @@
+{
+ "158": {
+ "inputs": {
+ "filename_prefix": "fuobe/ideogram4-t2i",
+ "images": [
+ "98:13",
+ 0
+ ]
+ },
+ "class_type": "SaveImage",
+ "_meta": {
+ "title": "Save Image"
+ }
+ },
+ "98:9": {
+ "inputs": {
+ "vae_name": "flux2-vae.safetensors"
+ },
+ "class_type": "VAELoader",
+ "_meta": {
+ "title": "Load VAE"
+ }
+ },
+ "98:10": {
+ "inputs": {
+ "conditioning": [
+ "98:24",
+ 0
+ ]
+ },
+ "class_type": "ConditioningZeroOut",
+ "_meta": {
+ "title": "Conditioning Zero Out"
+ }
+ },
+ "98:11": {
+ "inputs": {
+ "width": [
+ "98:31",
+ 1
+ ],
+ "height": [
+ "98:32",
+ 1
+ ],
+ "batch_size": 1
+ },
+ "class_type": "EmptyFlux2LatentImage",
+ "_meta": {
+ "title": "Empty Flux 2 Latent"
+ }
+ },
+ "98:12": {
+ "inputs": {
+ "noise": [
+ "98:18",
+ 0
+ ],
+ "guider": [
+ "98:155",
+ 0
+ ],
+ "sampler": [
+ "98:16",
+ 0
+ ],
+ "sigmas": [
+ "98:17",
+ 0
+ ],
+ "latent_image": [
+ "98:11",
+ 0
+ ]
+ },
+ "class_type": "SamplerCustomAdvanced",
+ "_meta": {
+ "title": "SamplerCustomAdvanced"
+ }
+ },
+ "98:13": {
+ "inputs": {
+ "samples": [
+ "98:12",
+ 0
+ ],
+ "vae": [
+ "98:9",
+ 0
+ ]
+ },
+ "class_type": "VAEDecode",
+ "_meta": {
+ "title": "VAE Decode"
+ }
+ },
+ "98:16": {
+ "inputs": {
+ "sampler_name": "euler"
+ },
+ "class_type": "KSamplerSelect",
+ "_meta": {
+ "title": "KSamplerSelect"
+ }
+ },
+ "98:17": {
+ "inputs": {
+ "steps": [
+ "98:151",
+ 1
+ ],
+ "width": [
+ "98:31",
+ 1
+ ],
+ "height": [
+ "98:32",
+ 1
+ ],
+ "mu": [
+ "98:144",
+ 0
+ ],
+ "std": [
+ "98:146",
+ 0
+ ]
+ },
+ "class_type": "Ideogram4Scheduler",
+ "_meta": {
+ "title": "Ideogram 4 Scheduler"
+ }
+ },
+ "98:18": {
+ "inputs": {
+ "noise_seed": 0
+ },
+ "class_type": "RandomNoise",
+ "_meta": {
+ "title": "RandomNoise"
+ }
+ },
+ "98:23": {
+ "inputs": {
+ "unet_name": "ideogram4_int8_convrot.safetensors",
+ "weight_dtype": "default"
+ },
+ "class_type": "UNETLoader",
+ "_meta": {
+ "title": "Load Diffusion Model"
+ }
+ },
+ "98:24": {
+ "inputs": {
+ "text": "{\"high_level_description\":\"A full-length editorial fashion photograph of a woman in a floor-length ivory silk slip gown at the stone balustrade of a Mediterranean villa terrace above a calm turquoise sea, late morning.\",\"style_description\":{\"aesthetics\":\"luxurious, serene, editorial, high-end fashion campaign\",\"lighting\":\"soft late-morning sun from the left, open shade fill, neutral white balance\",\"photo\":\"85mm lens, f/2.8, eye level, smooth skin with fine pores\",\"medium\":\"photograph\",\"color_palette\":[\"#F3EEE4\",\"#D9CBB4\",\"#9DB09A\",\"#3FA7B5\",\"#1F5F7A\",\"#2B2522\"]},\"compositional_deconstruction\":{\"background\":\"A sunlit terrace of pale travertine with a carved stone balustrade, white bougainvillea on a limestone wall, and a calm turquoise sea under a clear sky.\",\"elements\":[{\"type\":\"obj\",\"bbox\":[150,520,1000,820],\"desc\":\"A fashion model in her late twenties with dark brown hair in a loose low chignon, sculpted cheekbones, wearing a floor-length ivory silk slip gown, standing in a relaxed contrapposto with one hand on the balustrade, face turned towards the camera. Her whole head is inside the frame.\"}]}}",
+ "clip": [
+ "98:14",
+ 0
+ ]
+ },
+ "class_type": "CLIPTextEncode",
+ "_meta": {
+ "title": "CLIP Text Encode (Positive Prompt)"
+ }
+ },
+ "98:14": {
+ "inputs": {
+ "clip_name": "qwen3vl_8b_fp8_scaled.safetensors",
+ "type": "ideogram4",
+ "device": "default"
+ },
+ "class_type": "CLIPLoader",
+ "_meta": {
+ "title": "Load CLIP"
+ }
+ },
+ "98:27": {
+ "inputs": {
+ "value": 1024
+ },
+ "class_type": "PrimitiveInt",
+ "_meta": {
+ "title": "Int (Width)"
+ }
+ },
+ "98:28": {
+ "inputs": {
+ "value": 1024
+ },
+ "class_type": "PrimitiveInt",
+ "_meta": {
+ "title": "Int (Height)"
+ }
+ },
+ "98:31": {
+ "inputs": {
+ "expression": "max(((a + 15) // 16) * 16, 256)",
+ "values.a": [
+ "98:27",
+ 0
+ ]
+ },
+ "class_type": "ComfyMathExpression",
+ "_meta": {
+ "title": "Math Expression"
+ }
+ },
+ "98:32": {
+ "inputs": {
+ "expression": "max(((a + 15) // 16) * 16, 256)",
+ "values.a": [
+ "98:28",
+ 0
+ ]
+ },
+ "class_type": "ComfyMathExpression",
+ "_meta": {
+ "title": "Math Expression"
+ }
+ },
+ "98:144": {
+ "inputs": {
+ "value": [
+ "98:145",
+ 0
+ ]
+ },
+ "class_type": "ComfyNumberConvert",
+ "_meta": {
+ "title": "Convert Number"
+ }
+ },
+ "98:145": {
+ "inputs": {
+ "json_string": [
+ "98:148",
+ 0
+ ],
+ "key": "mu"
+ },
+ "class_type": "JsonExtractString",
+ "_meta": {
+ "title": "Extract Text from JSON"
+ }
+ },
+ "98:146": {
+ "inputs": {
+ "value": [
+ "98:150",
+ 0
+ ]
+ },
+ "class_type": "ComfyNumberConvert",
+ "_meta": {
+ "title": "Convert Number"
+ }
+ },
+ "98:147": {
+ "inputs": {
+ "json_string": "{\n \"Quality\": {\n \"num_steps\": 48,\n \"mu\": 0.0,\n \"std\": 1.5,\n \"preset_id\": \"V4_QUALITY_48\"\n },\n \"Default\": {\n \"num_steps\": 20,\n \"mu\": 0.0,\n \"std\": 1.75,\n \"preset_id\": \"V4_DEFAULT_20\"\n },\n \"Turbo\": {\n \"num_steps\": 12,\n \"mu\": 0.5,\n \"std\": 1.75,\n \"preset_id\": \"V4_TURBO_12\"\n }\n}",
+ "key": [
+ "98:156",
+ 0
+ ]
+ },
+ "class_type": "JsonExtractString",
+ "_meta": {
+ "title": "Extract Text from JSON"
+ }
+ },
+ "98:148": {
+ "inputs": {
+ "string": [
+ "98:147",
+ 0
+ ],
+ "find": "'",
+ "replace": "\""
+ },
+ "class_type": "StringReplace",
+ "_meta": {
+ "title": "Replace Text"
+ }
+ },
+ "98:149": {
+ "inputs": {
+ "json_string": [
+ "98:148",
+ 0
+ ],
+ "key": "num_steps"
+ },
+ "class_type": "JsonExtractString",
+ "_meta": {
+ "title": "Extract Text from JSON"
+ }
+ },
+ "98:150": {
+ "inputs": {
+ "json_string": [
+ "98:148",
+ 0
+ ],
+ "key": "std"
+ },
+ "class_type": "JsonExtractString",
+ "_meta": {
+ "title": "Extract Text from JSON"
+ }
+ },
+ "98:151": {
+ "inputs": {
+ "value": [
+ "98:149",
+ 0
+ ]
+ },
+ "class_type": "ComfyNumberConvert",
+ "_meta": {
+ "title": "Convert Number"
+ }
+ },
+ "98:154": {
+ "inputs": {
+ "unet_name": "ideogram4_unconditional_int8_convrot.safetensors",
+ "weight_dtype": "default"
+ },
+ "class_type": "UNETLoader",
+ "_meta": {
+ "title": "Load Diffusion Model"
+ }
+ },
+ "98:155": {
+ "inputs": {
+ "cfg": 7,
+ "model": [
+ "98:157",
+ 0
+ ],
+ "positive": [
+ "98:24",
+ 0
+ ],
+ "model_negative": [
+ "98:154",
+ 0
+ ],
+ "negative": [
+ "98:10",
+ 0
+ ]
+ },
+ "class_type": "DualModelGuider",
+ "_meta": {
+ "title": "Dual Model CFG Guider"
+ }
+ },
+ "98:156": {
+ "inputs": {
+ "choice": "Quality",
+ "index": 0,
+ "option1": "Quality",
+ "option2": "Default",
+ "option3": "Turbo",
+ "option4": ""
+ },
+ "class_type": "CustomCombo",
+ "_meta": {
+ "title": "Custom Combo"
+ }
+ },
+ "98:157": {
+ "inputs": {
+ "cfg": 3,
+ "start_percent": 0.7,
+ "end_percent": 1,
+ "model": [
+ "98:23",
+ 0
+ ]
+ },
+ "class_type": "CFGOverride",
+ "_meta": {
+ "title": "CFG Override"
+ }
+ }
+}
diff --git a/scripts/comfy/library.spec.mjs b/scripts/comfy/library.spec.mjs
index 444f1ddb..e93852ef 100644
--- a/scripts/comfy/library.spec.mjs
+++ b/scripts/comfy/library.spec.mjs
@@ -106,6 +106,8 @@
// audioCfg (MultiTalkWav2VecEmbeds audio guidance)
// threshold, mosaicScale (face mosaic: SAM3_Detect threshold; the mosaic's scale, 0.04 = blocks of 25 px)
// prompt* (face mosaic: what SAM 3.1 pixelates, "face" when the run gives no words)
+// Keys added with the owner's SOTA image families (2026-10-31), model controls (params.extra):
+// preset (Ideogram 4's sampling preset by name: Quality | Default | Turbo, the graph's own table)
import fs from 'node:fs';
@@ -264,6 +266,12 @@ export const KNOWN_MODELS = {
// round 4 (r4/video-finish): the chunked SeedVR2 graph is hand-built, so its files are named here (same files as the template).
'seedvr2_3b_int8_convrot.safetensors': { folder: 'diffusion_models', url: 'https://huggingface.co/Comfy-Org/SeedVR2/resolve/main/diffusion_models/seedvr2_3b_int8_convrot.safetensors' },
'seedvr2_ema_vae_fp16.safetensors': { folder: 'vae', url: 'https://huggingface.co/Comfy-Org/SeedVR2/resolve/main/vae/seedvr2_ema_vae_fp16.safetensors' },
+
+ // owner's SOTA families (2026-10-31): Ideogram 4 (Comfy-Org/Ideogram-4; its flux2-vae is the flux2-dev row above). `variants`:
+ // the same weights in another precision in the same repository, which a ComfyUI may list instead of the pinned file.
+ 'ideogram4_int8_convrot.safetensors': { folder: 'diffusion_models', url: 'https://huggingface.co/Comfy-Org/Ideogram-4/resolve/main/diffusion_models/ideogram4_int8_convrot.safetensors', variants: ['ideogram4_fp8_scaled.safetensors'] },
+ 'ideogram4_unconditional_int8_convrot.safetensors': { folder: 'diffusion_models', url: 'https://huggingface.co/Comfy-Org/Ideogram-4/resolve/main/diffusion_models/ideogram4_unconditional_int8_convrot.safetensors', variants: ['ideogram4_unconditional_fp8_scaled.safetensors'] },
+ 'qwen3vl_8b_fp8_scaled.safetensors': { folder: 'text_encoders', url: 'https://huggingface.co/Comfy-Org/Ideogram-4/resolve/main/text_encoders/qwen3vl_8b_fp8_scaled.safetensors' },
};
const WAN_NEG_EN =
@@ -2111,6 +2119,30 @@ export const SPEC = [
'The look\'s LoRAs are injected after the UNETLoader (LoraLoaderModelOnly), as on z-image-turbo-t2i. The result keeps the picture\'s shape.',
},
+ // ---- Owner's SOTA image families: Ideogram 4 -------------------------------------------
+ {
+ id: 'ideogram4-t2i',
+ title: 'Ideogram 4 text to image (int8, dual-model guidance, the Quality / Default / Turbo preset table)',
+ capability: 't2i',
+ handBuilt: 'hand-built/ideogram4-t2i.json',
+ bindings: {
+ prompt: [b('98:24', 'text')], width: [b('98:27', 'value')], height: [b('98:28', 'value')], seed: [b('98:18', 'noise_seed')],
+ preset: [b('98:156', 'choice')],
+ },
+ outputs: [{ node: '158', kind: 'image' }],
+ defaults: { preset: 'Quality' },
+ limits: { maxWidth: 2048, maxHeight: 2048, dimensionMultiple: 16 },
+ vramGb: 24,
+ license: 'Ideogram Non-Commercial Model Agreement: NON-COMMERCIAL (research and personal use; commercial use needs a paid Ideogram licence)',
+ notes:
+ 'The owner\'s image_ideogram4_t2i_int8.json, exported through the ComfyUI frontend (subgraph 98 flattened, its LLM caption-template subgraph and preview pruned) and rendered as the preview pipeline\'s A1 [proven]. ' +
+ 'Kept as saved: the conditional UNET with CFGOverride (cfg 3 for the last 30% of steps) into DualModelGuider cfg 7, whose negative pass is the unconditional UNET on the zeroed prompt; ' +
+ 'qwen3vl_8b_fp8_scaled loaded as type ideogram4; flux2-vae; EmptyFlux2LatentImage; euler; SamplerCustomAdvanced; width and height rounded up to 16 (at least 256) by its math nodes. ' +
+ 'The preset table feeds Ideogram4Scheduler (Quality 48 steps / mu 0 / std 1.5, Default 20 / 0 / 1.75, Turbo 12 / 0.5 / 1.75); the graph runs Quality, the recipe of the approved preview stills with people (those without ran Default, as the saved workflow does). ' +
+ 'No negative prompt: the guidance is asymmetric with a text-free unconditional pass. The prompt is an Ideogram 4 JSON caption (the app writes one from plain words: src/lib/ideogram-caption.ts); ' +
+ 'plain sentences often come back as the grey "blocked by safety filter" card. The Realism Engine LoRA graph is not used (the approved stills are the stock graph).',
+ },
+
// ---- Fuobe DoP (Originals O4): LTX-2.3 camera moves, FPV and transitions with LoRAs ------------
{
id: 'ltx23-i2v-lora',
diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.ts
index 7ba5053a..6a7408d2 100644
--- a/src/lib/catalog/models.ts
+++ b/src/lib/catalog/models.ts
@@ -56,6 +56,35 @@ type OpenSpec = Omit<ModelDef, "engine" | "badges"> & { badges?: ModelDef["badge
const o = (m: OpenSpec): ModelDef => ({ ...m, engine: "open", badges: ["open", ...(m.badges ?? [])] });
const open: ModelDef[] = [
+ // ---- Ideogram 4 (B-I)
+ // The prompt is a JSON caption the server writes from the words (promptFormat; src/lib/ideogram-caption.ts).
+ o({
+ id: "oss-ideogram-4",
+ name: "Ideogram 4",
+ vendor: "Ideogram",
+ family: "ideogram",
+ kind: "image",
+ tagline: "Typography, posters and photographic stills from structured captions · 24 GB GPU · non-commercial weights",
+ badges: ["new", "top"],
+ routes: [comfy("t2i", "ideogram4-t2i", "lean JSON caption; Quality preset")],
+ options: {
+ aspectRatios: IMG_AR,
+ resolutions: ["1K", "1.5K", "2K"],
+ seed: true,
+ controls: [
+ {
+ param: "preset",
+ label: "Quality",
+ values: ["Quality", "Default", "Turbo"],
+ default: "Quality",
+ labels: { Quality: "Quality (48 steps)", Default: "Balanced (20 steps)", Turbo: "Turbo (12 steps)" },
+ },
+ ],
+ promptFormat: "ideogram4",
+ },
+ defaults: { aspectRatio: "1:1", resolution: "1.5K" },
+ }),
+
// ---------------- Image
o({
id: "oss-z-image-turbo",
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 593a54fa..4d95de53 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -546,6 +546,11 @@ export interface ModelOptions {
promptOptional?: boolean;
/** The words a run takes when none are given (Fuobe Try-On: its try-on LoRA's own instruction). */
defaultPrompt?: string;
+ /**
+ * The prompt the model reads, when it isn't plain words: "ideogram4" = an Ideogram 4 JSON caption. The server writes
+ * one from the words before the run (src/lib/ideogram-caption.ts) and keeps it as the run's prompt.
+ */
+ promptFormat?: "ideogram4";
/**
* LoRAs the model's recipe always loads (Fuobe Try-On's try-on LoRA): every run carries them before the user's own
* (an API's LoRA cap leaves out the user's first), their trigger words leading the prompt. A ComfyUI graph that loads
diff --git a/src/lib/ideogram-caption.ts b/src/lib/ideogram-caption.ts
new file mode 100644
index 00000000..b76edb2a
--- /dev/null
+++ b/src/lib/ideogram-caption.ts
@@ -0,0 +1,204 @@
+/**
+ * Ideogram 4's prompt: a JSON caption in the schema the model was trained on (Ideogram's caption schema, key order
+ * included: ideogram-oss/ideogram4 docs/prompting.md and its CaptionVerifier). Plain sentences often come back as the grey
+ * "Image blocked by safety filter" card, so the server writes a caption from the words before the run
+ * (src/server/enhance.ts ideogramCaption): an LLM's, checked here and asked once more when it breaks the rules, else a
+ * fixed wrapper around the words.
+ *
+ * The house style is "lean JSON", which won a blind test of 48 renders on 8 hard cards (2026-10-24): about 120–150 words.
+ * The lead names everything the picture pays off on in 25–35 words; the main element takes up to 45 words plus "Her whole
+ * head is inside the frame."; lighting up to 18 words ending "neutral white balance"; photo up to 13; background up to 35;
+ * a palette of 5–7 colours. Only what is in the picture: a thing that is named gets drawn, even when it is negated.
+ */
+
+type Box = [number, number, number, number];
+
+export interface CaptionElement {
+ type: "obj" | "text";
+ /** [top, left, bottom, right], 0–1000 from the top left. */
+ bbox?: Box;
+ /** The lettering a text element draws, exactly. */
+ text?: string;
+ desc: string;
+ color_palette?: string[];
+}
+
+export interface IdeogramCaption {
+ high_level_description?: string;
+ /** `photo` for a photograph, `art_style` (after `medium`) for anything else: never both. */
+ style_description?: { aesthetics?: string; lighting?: string; photo?: string; medium?: string; art_style?: string; color_palette?: string[] };
+ compositional_deconstruction: { background: string; elements: CaptionElement[] };
+}
+
+const HEX = /^#[0-9A-F]{6}$/;
+const str = (v: unknown) => (typeof v === "string" ? v.trim() : "");
+const words = (s: string | undefined) => (s ?? "").split(/\s+/).filter(Boolean).length;
+
+/** Uppercase #RRGGBB colours, at most `max` (the schema: 16 for the picture, 5 for an element). */
+function palette(v: unknown, max: number): string[] | undefined {
+ if (!Array.isArray(v)) return undefined;
+ const out = v.map((c) => String(c).trim().toUpperCase()).filter((c) => HEX.test(c)).slice(0, max);
+ return out.length ? out : undefined;
+}
+
+/** A box of four whole numbers in 0–1000, top before bottom and left before right; anything else is left out. */
+function box(v: unknown): Box | undefined {
+ if (!Array.isArray(v) || v.length !== 4 || !v.every((n) => typeof n === "number" && Number.isFinite(n))) return undefined;
+ const b = v.map((n: number) => Math.min(1000, Math.max(0, Math.round(n)))) as Box;
+ return b[0] <= b[2] && b[1] <= b[3] ? b : undefined;
+}
+
+/** The first JSON object in a text (an LLM's answer may wrap it in a code fence or a sentence). */
+function jsonObject(text: string): Record<string, unknown> | null {
+ const body = text.replace(/```(?:json)?/gi, "");
+ const start = body.indexOf("{");
+ const end = body.lastIndexOf("}");
+ if (start < 0 || end <= start) return null;
+ try {
+ const v = JSON.parse(body.slice(start, end + 1));
+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
+ } catch {
+ return null;
+ }
+}
+
+const isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
+
+/**
+ * A caption read from a text: JSON with a `compositional_deconstruction`, rebuilt in the schema's key order with the
+ * schema's keys only (an `aspect_ratio` key, which the model wasn't trained on, is dropped). Null when the text isn't one.
+ */
+export function readCaption(text: string): IdeogramCaption | null {
+ const c = jsonObject(text);
+ const cd = c?.compositional_deconstruction;
+ if (!c || !isObject(cd)) return null;
+ const elements = (Array.isArray(cd.elements) ? cd.elements : []).flatMap((e): CaptionElement[] => {
+ if (!isObject(e)) return [];
+ const desc = str(e.desc);
+ const text = typeof e.text === "string" && e.text.trim() ? e.text : undefined;
+ const lettering = e.type === "text" && text !== undefined;
+ if (!desc && !lettering) return [];
+ const bbox = box(e.bbox);
+ const colours = palette(e.color_palette, 5);
+ return [{ type: lettering ? "text" : "obj", ...(bbox && { bbox }), ...(lettering && { text }), desc, ...(colours && { color_palette: colours }) }];
+ });
+ const caption: IdeogramCaption = { compositional_deconstruction: { background: str(cd.background), elements } };
+ const lead = str(c.high_level_description);
+ const style = isObject(c.style_description) ? styleOf(c.style_description) : undefined;
+ return { ...(lead ? { high_level_description: lead } : {}), ...(style && { style_description: style }), ...caption };
+}
+
+/** A style block in the schema's order: aesthetics, lighting, photo, medium (or aesthetics, lighting, medium, art_style), palette. */
+function styleOf(s: Record<string, unknown>): IdeogramCaption["style_description"] {
+ const photo = str(s.photo);
+ const art = str(s.art_style);
+ const medium = str(s.medium);
+ // Exactly one of photo and art_style: the medium decides when both came.
+ const asPhoto = !!photo && (!art || !medium || medium === "photograph");
+ const out: NonNullable<IdeogramCaption["style_description"]> = {};
+ if (str(s.aesthetics)) out.aesthetics = str(s.aesthetics);
+ if (str(s.lighting)) out.lighting = str(s.lighting);
+ if (asPhoto) out.photo = photo;
+ if (medium) out.medium = medium;
+ if (!asPhoto && art) out.art_style = art;
+ const colours = palette(s.color_palette, 16);
+ if (colours) out.color_palette = colours;
+ return Object.keys(out).length ? out : undefined;
+}
+
+/** The compact caption string the model reads (the schema's encoding: no spaces, non-ASCII as it is). */
+export const captionText = (c: IdeogramCaption): string => JSON.stringify(c);
+
+/** A prompt that already is a caption (pasted, or a run reused), as the model reads it; null for plain words. */
+export function parseCaption(text: string): string | null {
+ const c = readCaption(text);
+ return c ? captionText(c) : null;
+}
+
+/**
+ * The caption when no LLM can write one: the words as the lead and as one element. No style block (a style is never
+ * invented) and one element, since a caption without elements invites the safety card.
+ */
+export function captionFromWords(text: string): string {
+ const w = text.trim().replace(/\s+/g, " ");
+ return JSON.stringify({ high_level_description: w, compositional_deconstruction: { background: "", elements: [{ type: "obj", desc: w }] } });
+}
+
+/** Words that age a face or turn a fitted garment see-through. */
+const DROP_LIST = /\b(stubble|weathered|rugged|gaunt|wrinkl\w*|crow.s feet|medium format|visible pores|sheer|translucent|see-through|mesh|illusion)\b/gi;
+/** A negated thing is still drawn: "no tourists" brings tourists. */
+const NEGATIONS = /\b(no|not|without|never|none|nothing|free of|unmarked|unbranded|logo-free|lettering-free|absent)\b/gi;
+/** Words that draw lettering. */
+const TEXT_WORDS = /\b(text|logo|label|sign|signage|letters|lettering|words|brand|typography|caption|watermark)\b/i;
+const found = (s: string, re: RegExp) => [...new Set((s.match(re) ?? []).map((x) => x.toLowerCase()))];
+
+/**
+ * What a caption does against the lean rules, in words an LLM can act on; empty when nothing. Lettering itself (a text
+ * element's `text`) is never judged.
+ */
+export function leanProblems(caption: string | IdeogramCaption): string[] {
+ const c = typeof caption === "string" ? readCaption(caption) : caption;
+ if (!c) return ["it is not a caption in the schema (JSON with compositional_deconstruction)"];
+ const p: string[] = [];
+ const s = c.style_description ?? {};
+ const cd = c.compositional_deconstruction;
+ const els = cd.elements;
+ const cap = (what: string, n: number, max: number) => {
+ if (n > max) p.push(`${what} has ${n} words (at most ${max})`);
+ };
+ cap("high_level_description", words(c.high_level_description), 35);
+ cap("background", words(cd.background), 35);
+ if (s.photo !== undefined) {
+ cap("lighting", words(s.lighting), 18);
+ cap("photo", words(s.photo), 13);
+ if (s.lighting && !/neutral(\s+daylight)?\s+white balance\.?$/i.test(s.lighting)) p.push('lighting does not end with "neutral white balance"');
+ }
+ const objects = els.filter((e) => e.type === "obj");
+ const lengths = objects.map((e) => words(e.desc));
+ const hero = Math.max(0, ...lengths);
+ // 45 words, plus the sentence that keeps the head inside the frame.
+ if (hero > 52) p.push(`the main element's desc has ${hero} words (at most 45, plus "Her whole head is inside the frame.")`);
+ lengths.forEach((n, i) => {
+ if (n !== hero && n > 22) p.push(`element "${objects[i].desc.slice(0, 30)}…" has ${n} words (at most 20 beside the main one)`);
+ });
+ if (!els.length) p.push("there are no elements (a caption without them invites the safety card)");
+ // Lettering is one text element per line, so only the things in the picture are counted.
+ if (objects.length > 5) p.push(`there are ${objects.length} object elements (at most 5)`);
+ const prose = [c.high_level_description, s.aesthetics, s.lighting, s.photo, s.art_style, cd.background, ...els.map((e) => e.desc)].filter(Boolean).join(" ");
+ const drop = found(prose, DROP_LIST);
+ if (drop.length) p.push(`it says ${drop.join(", ")}: these age faces or turn fitted garments see-through`);
+ const neg = found(prose, NEGATIONS);
+ if (neg.length) p.push(`it says ${neg.join(", ")}: describe only what is in the picture, a negated thing is still drawn`);
+ if (/\bsexy\b/i.test(prose)) p.push('it says "sexy", which trips the safety filter: describe the styling and pose instead');
+ if (/\bempty\b/i.test(prose)) p.push('it says "empty", which invites the safety card: name what is there');
+ // A picture without lettering: a word about text draws some.
+ if (!els.some((e) => e.type === "text") && TEXT_WORDS.test(prose)) p.push("it mentions text, a logo or a sign, which draws lettering: leave it out, or add the words as a text element");
+ return p;
+}
+
+/** A picture size in words for the caption writer ("1536 × 1152 px, landscape"). */
+const shapeOf = ({ width, height }: { width?: number; height?: number }) =>
+ width && height ? `${width} × ${height} px, ${width > height ? "landscape" : width < height ? "portrait" : "square"}` : "square";
+
+/** What the caption writer is asked: the idea and the picture's shape, and the second time, its caption and what to fix. */
+export function captionRequest(text: string, size: { width?: number; height?: number }, retry?: { caption: string; problems: string[] }): string {
+ const ask = `Idea: ${text.trim()}\nPicture: ${shapeOf(size)}`;
+ if (!retry) return ask;
+ return `${ask}\n\nYour caption:\n${retry.caption}\n\nIt breaks these rules:\n${retry.problems.map((x) => `- ${x}`).join("\n")}\nWrite it again within the rules.`;
+}
+
+/**
+ * The caption for some words: the LLM's (`ask` answers a request, null when no LLM answers), checked against the schema
+ * and the lean rules and asked once more with the problems listed; the first answer when the second isn't a caption; the
+ * wrapper when neither is.
+ */
+export async function writeCaption(text: string, size: { width?: number; height?: number }, ask: (request: string) => Promise<string | null>): Promise<string> {
+ const first = await ask(captionRequest(text, size)).catch(() => null);
+ if (first === null) return captionFromWords(text);
+ const caption = readCaption(first);
+ const problems = leanProblems(caption ?? first);
+ if (caption && !problems.length) return captionText(caption);
+ const again = await ask(captionRequest(text, size, { caption: caption ? captionText(caption) : first.slice(0, 4000), problems })).catch(() => null);
+ const second = again ? readCaption(again) : null;
+ return second ? captionText(second) : caption ? captionText(caption) : captionFromWords(text);
+}
diff --git a/src/lib/licences.ts b/src/lib/licences.ts
index 345468a9..ab182d79 100644
--- a/src/lib/licences.ts
+++ b/src/lib/licences.ts
@@ -256,6 +256,7 @@ const SPDX = (id: string) => `https://spdx.org/licenses/${id}.html`;
const KNOWN: { re: RegExp; name: string; class: LicenceClass; url?: string }[] = [
{ re: /FLUX\.1 \[dev\] Non-Commercial License|FLUX\.1 \[dev\] base is NON-COMMERCIAL/, name: "FLUX.1 [dev] Non-Commercial License", class: "non-commercial", url: "https://huggingface.co/black-forest-labs/FLUX.1-dev" },
{ re: /FLUX \[dev\] Non-Commercial License/, name: "FLUX [dev] Non-Commercial License", class: "non-commercial", url: "https://huggingface.co/black-forest-labs/FLUX.2-dev" },
+ { re: /Ideogram Non-Commercial Model Agreement/, name: "Ideogram Non-Commercial Model Agreement", class: "non-commercial", url: "https://huggingface.co/ideogram-ai/ideogram-4-fp8/blob/main/LICENSE.md" },
{ re: /inswapper/, name: "InsightFace inswapper (research only)", class: "research", url: "https://github.com/deepinsight/insightface" },
{ re: /CC-BY-NC-SA-4\.0/, name: "CC BY-NC-SA 4.0", class: "non-commercial", url: SPDX("CC-BY-NC-SA-4.0") },
{ re: /CC[- ]BY[- ]NC(?:[- ]4\.0)?\b/, name: "CC BY-NC 4.0", class: "non-commercial", url: SPDX("CC-BY-NC-4.0") },
diff --git a/src/server/enhance.ts b/src/server/enhance.ts
index b08c4127..e79a9459 100644
--- a/src/server/enhance.ts
+++ b/src/server/enhance.ts
@@ -1,6 +1,7 @@
import "server-only";
import Anthropic from "@anthropic-ai/sdk";
import type { MediaKind, Operation } from "@/lib/catalog/types";
+import { writeCaption } from "@/lib/ideogram-caption";
import { activeLocal, aiHelper, chatLocal, type JsonSpec } from "./llm";
import { engineMode, getSetting } from "./settings";
import { tenant } from "./tenant";
@@ -184,3 +185,31 @@ export async function enhanceSoulWords(words: string): Promise<string> {
export async function enhancePrompt(prompt: string, kind: MediaKind, op: Operation): Promise<string> {
return (await llmText(SYSTEM, instruction(prompt, kind, op))) ?? heuristicEnhance(prompt, kind, op);
}
+
+/**
+ * Ideogram 4's caption writer (src/lib/ideogram-caption.ts): the schema in its key order and the "lean JSON" house style.
+ * Written for Fuobe after Ideogram's own docs and caption verifier, and the preview pipeline's measured rules.
+ */
+const IDEOGRAM_SYSTEM = `You turn an idea into a JSON caption for the Ideogram 4 image model. Answer with one JSON object and nothing else: no code fence, no words before or after it.
+The schema, with the keys in exactly this order:
+{"high_level_description":"...","style_description":{"aesthetics":"...","lighting":"...","photo":"...","medium":"photograph","color_palette":["#RRGGBB"]},"compositional_deconstruction":{"background":"...","elements":[{"type":"obj","bbox":[top,left,bottom,right],"desc":"..."},{"type":"text","text":"...","desc":"..."}]}}
+Rules:
+- A picture that isn't a photograph has "medium" (illustration, painting, 3d_render, graphic_design…) then "art_style" in place of "photo": aesthetics, lighting, medium, art_style, color_palette.
+- high_level_description: 25 to 35 words. The shot size first, then the subject, the main clothing or materials, the place and the time of day. Name everything the picture must show.
+- The first element is the main subject, in at most 45 words, and it is the only element with a bbox: whole numbers 0 to 1000 from the top left, [top, left, bottom, right]. At most 4 more elements of up to 20 words each, without a bbox.
+- People are adults, fully clothed and styled like fashion models, in their late twenties unless the idea gives an age. Describe the hair, one or two face features, each garment's material and colour on an opaque base, the shoes when the whole body shows, the pose as physical facts and where they look. End a person's desc with "Her whole head is inside the frame." (His or Their as fits).
+- lighting: at most 18 words, one named light source and at most one fill, ending with "neutral white balance".
+- photo: at most 13 words: the lens, the camera height and the aperture; for people add "smooth skin with fine pores".
+- background: at most 35 words, only what must be visible.
+- color_palette: 5 to 7 uppercase hex colours that fit the idea.
+- Words the picture shows as lettering go in "text" elements, exactly as the idea quotes them. A picture without lettering mentions no text, logo, sign or label anywhere.
+- Describe only what is in the picture. Never write no, not, without, never, empty or free of: a thing that is named gets drawn. Never write "sexy". Leave out sheer, mesh, see-through, translucent, stubble, weathered, rugged and wrinkles.
+- Keep the idea's subject and intent. Write in English. No other keys (no aspect_ratio).`;
+
+/**
+ * An Ideogram 4 caption for some words at a picture size: an LLM's (Claude, else a local model), checked and asked once more
+ * when it breaks the rules, else the plain wrapper. An account's run has no LLM here, so it gets the wrapper.
+ */
+export function ideogramCaption(words: string, size: { width?: number; height?: number } = {}): Promise<string> {
+ return writeCaption(words, size, (request) => llmText(IDEOGRAM_SYSTEM, request, { json: "object" }));
+}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 673f6ab0..f79360f8 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -24,6 +24,8 @@ import { MIXED_ORIGINAL, originalFrameSize } from "@/lib/catalog/mixed-media";
import { imageSize } from "@/lib/image-size";
import { finishSteps, mosaicPixels, unionMasks } from "@/lib/soul-post";
import { ANGLES_ORIGINAL, MOSAIC_SCALE } from "@/lib/catalog/open-tools";
+import { computeDimensions } from "@/lib/comfy";
+import { captionFromWords, parseCaption } from "@/lib/ideogram-caption";
import {
CHAIN_LIST_SLACK,
LAST_FRAME_CHAIN,
@@ -48,7 +50,7 @@ import { listElements } from "./elements";
import { markStale } from "./gpu/snapshots";
import { pollTrainings } from "./training";
import { createExtendChain, createKeyframeFilm, createMosaicRun, createRelitClip, createShotFilm, createStillTo3d } from "./chains";
-import { enhancePrompt, enhanceSoulWords } from "./enhance";
+import { enhancePrompt, enhanceSoulWords, ideogramCaption } from "./enhance";
import { setResolver, watchGenerations, type LiveEvent } from "./live";
import { provider, PROVIDERS, RETIRED_PROVIDER_ERROR } from "./providers";
import { comfyLoraFiles, onOwnGpu, outputFetch, outsideOwnGpu, OWN_OUTPUT_LIMITS, ownGpu, probeComfy } from "./providers/comfyui";
@@ -1366,7 +1368,8 @@ async function submitNow(
});
};
let prompt = plan.prompt;
- if (req.params?.enhancePrompt && prompt) {
+ const captioned = plan.model.options.promptFormat === "ideogram4";
+ if (req.params?.enhancePrompt && prompt && !captioned) {
update(id, { message: "Enhancing prompt" });
const words = plan.soul?.words;
const at = words ? prompt.indexOf(words) : -1;
@@ -1377,6 +1380,14 @@ async function submitNow(
} else prompt = await enhancePrompt(prompt, plan.model.kind, plan.op).catch(() => prompt);
update(id, { prompt });
}
+ // Ideogram 4 reads a JSON caption (src/lib/ideogram-caption.ts): one given as the prompt (a reused run) is kept, plain
+ // words get one written. It becomes the run's prompt, as Enhance's rewrite does, so Reuse makes the same picture.
+ if (captioned && prompt) {
+ update(id, { message: "Writing the caption" });
+ const words = prompt;
+ prompt = parseCaption(words) ?? (await ideogramCaption(words, computeDimensions(plan.params.aspectRatio, plan.params.resolution, {})).catch(() => captionFromWords(words)));
+ update(id, { prompt });
+ }
const input: GenInput = {
...plan.params,
prompt,
diff --git a/tests/open-ideogram-4.test.ts b/tests/open-ideogram-4.test.ts
new file mode 100644
index 00000000..028d654f
--- /dev/null
+++ b/tests/open-ideogram-4.test.ts
@@ -0,0 +1,372 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import type { GenInput, Generation, Operation } from "@/lib/catalog/types";
+import type { ComfyWorkflow, Manifest } from "@/lib/comfy";
+import type { ChatRequest } from "@/server/llm";
+
+// Ideogram 4 on the open engine: the owner's int8 graph with its Quality / Default / Turbo preset table, and the JSON
+// caption the server writes from the words before the run (lean JSON, src/lib/ideogram-caption.ts).
+vi.setConfig({ testTimeout: 60_000 });
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-ideogram4-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here: runs fall back to the demo
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+delete process.env.ANTHROPIC_API_KEY; // a key on this machine must not reach Claude
+
+// The local LLM: each call takes the next answer (null: nothing answers) and is kept.
+const llm = vi.hoisted(() => ({ answers: [] as (string | null)[], seen: [] as { system: string; user: string; json: unknown }[] }));
+vi.mock("@/server/llm", async (orig) => ({
+ ...(await orig<typeof import("@/server/llm")>()),
+ activeLocal: async () => ({ server: { kind: "ollama", url: "http://127.0.0.1:9" }, status: { loaded: true } }),
+ chatLocal: async (_ready: unknown, req: ChatRequest) => {
+ llm.seen.push({ system: String(req.messages[0].content), user: String(req.messages[1].content), json: req.json });
+ return { text: llm.answers.shift() ?? "" };
+ },
+}));
+
+const { setSetting } = await import("@/server/settings");
+const { createGenerations, getGeneration } = await import("@/server/generations");
+const { mockProvider } = await import("@/server/providers/mock");
+const { prepareWorkflow } = await import("@/server/providers/comfyui");
+const { ideogramCaption } = await import("@/server/enhance");
+const { getModel, getPreset, MODELS } = await import("@/lib/catalog");
+const { planGeneration } = await import("@/lib/catalog/plan");
+const { computeDimensions } = await import("@/lib/comfy");
+const { licenceInfo, licenceTerms } = await import("@/lib/licences");
+const { captionFromWords, captionRequest, leanProblems, parseCaption, readCaption, writeCaption } = await import("@/lib/ideogram-caption");
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+beforeEach(() => {
+ llm.answers = [];
+ llm.seen = [];
+});
+
+const LIBRARY = path.join(process.cwd(), "workflows/comfyui");
+const manifest = JSON.parse(fs.readFileSync(path.join(LIBRARY, "manifest.json"), "utf8")) as Manifest;
+const entry = () => manifest.workflows.find((w) => w.id === "ideogram4-t2i");
+/** The graph as committed (the library's copy is the same nodes, sorted). */
+const graph = () => JSON.parse(fs.readFileSync(path.join(process.cwd(), "scripts/comfy/hand-built/ideogram4-t2i.json"), "utf8")) as ComfyWorkflow;
+
+/** A lean caption as the schema orders it (the graph's own example). */
+const GOOD = {
+ high_level_description:
+ "A full-length editorial fashion photograph of a woman in a floor-length ivory silk slip gown at the stone balustrade of a Mediterranean villa terrace above a calm turquoise sea, late morning.",
+ style_description: {
+ aesthetics: "luxurious, serene, editorial, high-end fashion campaign",
+ lighting: "soft late-morning sun from the left, open shade fill, neutral white balance",
+ photo: "85mm lens, f/2.8, eye level, smooth skin with fine pores",
+ medium: "photograph",
+ color_palette: ["#F3EEE4", "#D9CBB4", "#9DB09A", "#3FA7B5", "#1F5F7A", "#2B2522"],
+ },
+ compositional_deconstruction: {
+ background: "A sunlit terrace of pale travertine with a carved stone balustrade, white bougainvillea on a limestone wall, and a calm turquoise sea under a clear sky.",
+ elements: [
+ {
+ type: "obj",
+ bbox: [150, 520, 1000, 820],
+ desc: "A fashion model in her late twenties with dark brown hair in a loose low chignon, sculpted cheekbones, wearing a floor-length ivory silk slip gown, standing in a relaxed contrapposto with one hand on the balustrade, face turned towards the camera. Her whole head is inside the frame.",
+ },
+ ],
+ },
+};
+const good = JSON.stringify(GOOD);
+type Caption = Omit<typeof GOOD, "compositional_deconstruction"> & {
+ compositional_deconstruction: { background: string; elements: { type: string; bbox?: number[]; text?: string; desc: string }[] };
+};
+const variant = (change: (c: Caption) => void) => {
+ const c = structuredClone(GOOD) as Caption;
+ change(c);
+ return JSON.stringify(c);
+};
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+async function settled(id: string, ms = 20_000): Promise<Generation> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const g = getGeneration(id)!;
+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;
+ if (Date.now() > end) throw new Error(`${id} is still ${g.status}`);
+ await sleep(50);
+ }
+}
+async function prepare(input: GenInput, op: Operation = "t2i"): Promise<ComfyWorkflow> {
+ const { workflow } = await prepareWorkflow("ideogram4-t2i", { seed: 7, ...input }, { generationId: "g", op, upload: async (_d, _t, name) => `up_${name}`, media: () => undefined, serverRam: async () => undefined });
+ return workflow;
+}
+
+describe("Ideogram 4 captions", () => {
+ it("keeps a caption it is given, in the schema's key order, without aspect_ratio or keys the model wasn't trained on", () => {
+ const given = JSON.stringify({
+ compositional_deconstruction: {
+ elements: [{ desc: GOOD.compositional_deconstruction.elements[0].desc, bbox: [150, 520, 1000, 820], type: "obj", mood: "calm" }],
+ background: GOOD.compositional_deconstruction.background,
+ },
+ aspect_ratio: "4:3",
+ style_description: { medium: "photograph", color_palette: GOOD.style_description.color_palette.map((c) => c.toLowerCase()), photo: GOOD.style_description.photo, lighting: GOOD.style_description.lighting, aesthetics: GOOD.style_description.aesthetics },
+ high_level_description: GOOD.high_level_description,
+ negative_prompt: "blurry",
+ });
+ expect(parseCaption(given)).toBe(good);
+ // Pretty-printed or in a code fence (an LLM's answer), it is the same caption.
+ expect(parseCaption(`Here it is:\n\`\`\`json\n${JSON.stringify(GOOD, null, 2)}\n\`\`\``)).toBe(good);
+ // Already compact and in order: unchanged, byte for byte.
+ expect(parseCaption(good)).toBe(good);
+ });
+
+ it("doesn't take plain words, or other JSON, for a caption", () => {
+ expect(parseCaption("a red fox in deep snow")).toBeNull();
+ expect(parseCaption('a neon sign reading {OPEN}')).toBeNull();
+ expect(parseCaption('{"prompt":"a red fox"}')).toBeNull();
+ expect(parseCaption('{"compositional_deconstruction":"a fox"}')).toBeNull();
+ });
+
+ it("keeps one of photo and art_style, palettes as uppercase hex, boxes inside 0–1000, lettering as written", () => {
+ const c = readCaption(
+ JSON.stringify({
+ high_level_description: "A flat vector poster of a fox.",
+ style_description: { aesthetics: "bold", lighting: "flat", photo: "50mm", medium: "illustration", art_style: "flat vector, thick outlines", color_palette: ["#abc", "#e43f5a", 7] },
+ compositional_deconstruction: {
+ background: "A cream backdrop.",
+ elements: [
+ { type: "obj", bbox: [10.4, 20, 2000, 900], desc: "A red fox." },
+ { type: "obj", bbox: [600, 0, 100, 900], desc: "A pine tree." },
+ { type: "text", text: " Wild Things\n", desc: "Bold black letters across the top." },
+ { type: "text", desc: "A text element without its text is an object." },
+ { type: "obj", desc: "" },
+ ],
+ },
+ }),
+ )!;
+ expect(c.style_description).toEqual({ aesthetics: "bold", lighting: "flat", medium: "illustration", art_style: "flat vector, thick outlines", color_palette: ["#E43F5A"] });
+ expect(Object.keys(c.style_description!)).toEqual(["aesthetics", "lighting", "medium", "art_style", "color_palette"]);
+ expect(c.compositional_deconstruction.elements).toEqual([
+ { type: "obj", bbox: [10, 20, 1000, 900], desc: "A red fox." },
+ { type: "obj", desc: "A pine tree." },
+ { type: "text", text: " Wild Things\n", desc: "Bold black letters across the top." },
+ { type: "obj", desc: "A text element without its text is an object." },
+ ]);
+ expect(Object.keys(c.compositional_deconstruction.elements[2])).toEqual(["type", "text", "desc"]);
+ });
+
+ it("wraps plain words byte for byte when no LLM writes the caption", () => {
+ expect(captionFromWords(" a red fox\n in deep snow ")).toBe(
+ '{"high_level_description":"a red fox in deep snow","compositional_deconstruction":{"background":"","elements":[{"type":"obj","desc":"a red fox in deep snow"}]}}',
+ );
+ expect(captionFromWords('a sign that says "OPEN"')).toBe(
+ '{"high_level_description":"a sign that says \\"OPEN\\"","compositional_deconstruction":{"background":"","elements":[{"type":"obj","desc":"a sign that says \\"OPEN\\""}]}}',
+ );
+ // The wrapper is a caption the model reads as one (and the run keeps as it is).
+ expect(parseCaption(captionFromWords("a red fox"))).toBe(captionFromWords("a red fox"));
+ });
+
+ it("lints the lean caps, negations and the words that trip the safety filter", () => {
+ expect(leanProblems(good)).toEqual([]);
+ // The graph's own example prompt is a lean caption too.
+ const example = String(graph()["98:24"].inputs.text);
+ expect(parseCaption(example)).toBe(example);
+ expect(leanProblems(example)).toEqual([]);
+
+ const long = Array.from({ length: 40 }, (_, i) => `word${i}`).join(" ");
+ expect(leanProblems(variant((c) => (c.high_level_description = long)))).toEqual(["high_level_description has 40 words (at most 35)"]);
+ expect(leanProblems(variant((c) => (c.compositional_deconstruction.background = long)))).toEqual(["background has 40 words (at most 35)"]);
+ expect(leanProblems(variant((c) => (c.style_description.lighting = "soft window light from the left")))).toEqual(['lighting does not end with "neutral white balance"']);
+ expect(leanProblems(variant((c) => (c.style_description.photo = `${long} lens`)))).toEqual(["photo has 41 words (at most 13)"]);
+ expect(leanProblems(variant((c) => (c.compositional_deconstruction.elements[0].desc = `${long} ${long}`))).join()).toMatch(/main element's desc has 80 words/);
+ expect(leanProblems(variant((c) => (c.compositional_deconstruction.background = "A cliff path with no tourists and not a cloud")))).toEqual([
+ "it says no, not: describe only what is in the picture, a negated thing is still drawn",
+ ]);
+ expect(leanProblems(variant((c) => (c.high_level_description += " A sexy look.")))[0]).toMatch(/"sexy"/);
+ expect(leanProblems(variant((c) => (c.compositional_deconstruction.elements[0].desc += " A sheer weathered shawl.")))[0]).toMatch(/^it says sheer, weathered/);
+ expect(leanProblems(variant((c) => (c.compositional_deconstruction.background = "An empty beach.")))[0]).toMatch(/"empty"/);
+ expect(leanProblems(variant((c) => (c.compositional_deconstruction.elements = [])))).toEqual(["there are no elements (a caption without them invites the safety card)"]);
+ const objects = (n: number) => Array.from({ length: n }, (_, i) => ({ type: "obj", desc: `A pebble number ${i}.` }));
+ expect(leanProblems(variant((c) => (c.compositional_deconstruction.elements = objects(6))))).toEqual(["there are 6 object elements (at most 5)"]);
+
+ // Words about lettering draw lettering in a picture that has none; with a text element they belong, and the
+ // lettering itself is never judged.
+ const sign = variant((c) => (c.compositional_deconstruction.background = "A café wall with a hand-painted sign."));
+ expect(leanProblems(sign)[0]).toMatch(/draws lettering/);
+ const poster = variant((c) => {
+ c.compositional_deconstruction.background = "A café wall with a hand-painted sign.";
+ c.compositional_deconstruction.elements.push({ type: "text", text: "NO LIMITS, NOT EVER, SHEER", desc: "Gold serif letters on the sign." });
+ for (let i = 0; i < 6; i++) c.compositional_deconstruction.elements.push({ type: "text", text: `Line ${i}`, desc: "Small gold letters." });
+ });
+ expect(leanProblems(poster)).toEqual([]);
+ expect(leanProblems("a red fox")).toEqual(["it is not a caption in the schema (JSON with compositional_deconstruction)"]);
+ });
+
+ it("writes a caption with the LLM, and uses a good one as it is", async () => {
+ const asked: string[] = [];
+ const out = await writeCaption("a model on a villa terrace", { width: 1776, height: 1328 }, async (r) => {
+ asked.push(r);
+ return `\`\`\`json\n${JSON.stringify(GOOD, null, 2)}\n\`\`\``;
+ });
+ expect(out).toBe(good);
+ expect(asked).toEqual(["Idea: a model on a villa terrace\nPicture: 1776 × 1328 px, landscape"]);
+ });
+
+ it("asks once more with the problems listed, and falls back to the first answer, then to the wrapper", async () => {
+ const bad = variant((c) => {
+ c.compositional_deconstruction.background = "A terrace with no people.";
+ });
+ const asked: string[] = [];
+ const answers = [bad, good];
+ const ask = async (r: string) => {
+ asked.push(r);
+ return answers.shift() ?? null;
+ };
+ expect(await writeCaption("a model on a terrace", {}, ask)).toBe(good);
+ expect(asked[1]).toBe(captionRequest("a model on a terrace", {}, { caption: bad, problems: leanProblems(bad) }));
+ expect(asked[1]).toContain("It breaks these rules:\n- it says no: describe only what is in the picture");
+ expect(asked[1]).toContain("Picture: square");
+ // Neither answer is a caption: the wrapper.
+ expect(await writeCaption("a model on a terrace", {}, async () => "Sorry, I can't.")).toBe(captionFromWords("a model on a terrace"));
+ // A second answer that isn't a caption: the first one, with its problems, beats the plain wrapper.
+ const twice = [bad, "Sorry, I can't."];
+ expect(await writeCaption("a model on a terrace", {}, async () => twice.shift() ?? null)).toBe(bad);
+ // No LLM, or one that fails: the wrapper, without asking again.
+ let calls = 0;
+ const none = async () => {
+ calls++;
+ return null;
+ };
+ expect(await writeCaption("a red fox", {}, none)).toBe(captionFromWords("a red fox"));
+ expect(await writeCaption("a red fox", {}, async () => Promise.reject(new Error("down")))).toBe(captionFromWords("a red fox"));
+ expect(calls).toBe(1);
+ });
+
+ it("asks the local LLM for JSON with its own instructions, and wraps the words when none answers", async () => {
+ setSetting("enhanceProvider", "local");
+ llm.answers = [good];
+ expect(await ideogramCaption("a model on a villa terrace", { width: 1536, height: 1536 })).toBe(good);
+ expect(llm.seen).toHaveLength(1);
+ expect(llm.seen[0]).toMatchObject({ json: "object", user: "Idea: a model on a villa terrace\nPicture: 1536 × 1536 px, square" });
+ expect(llm.seen[0].system).toMatch(/Ideogram 4/);
+ expect(llm.seen[0].system).toMatch(/neutral white balance/);
+ expect(llm.seen[0].system).toMatch(/late twenties/);
+ // An empty answer is no answer.
+ llm.answers = [""];
+ expect(await ideogramCaption("a red fox")).toBe(captionFromWords("a red fox"));
+ setSetting("enhanceProvider", "none");
+ expect(await ideogramCaption("a red fox")).toBe(captionFromWords("a red fox"));
+ expect(llm.seen).toHaveLength(2);
+ });
+});
+
+describe("Ideogram 4 on the open engine", () => {
+ it("is the owner's int8 graph: dual-model guidance, the fp8 Qwen3-VL encoder, the preset table on Quality", () => {
+ const wf = entry()!;
+ expect(wf).toMatchObject({ capability: "t2i", customNodes: [], defaults: { width: 1024, height: 1024, preset: "Quality" }, limits: { maxWidth: 2048, maxHeight: 2048, dimensionMultiple: 16 } });
+ expect(Object.keys(wf.bindings).sort()).toEqual(["filenamePrefix", "height", "preset", "prompt", "seed", "width"]);
+ expect(wf.models.map((m) => `${m.folder}/${m.file}`).sort()).toEqual([
+ "diffusion_models/ideogram4_int8_convrot.safetensors",
+ "diffusion_models/ideogram4_unconditional_int8_convrot.safetensors",
+ "text_encoders/qwen3vl_8b_fp8_scaled.safetensors",
+ "vae/flux2-vae.safetensors",
+ ]);
+ // The library's flux2-vae pin, not a second build of the same name.
+ expect(wf.models.find((m) => m.file === "flux2-vae.safetensors")?.url).toContain("/Comfy-Org/flux2-dev/");
+ const g = graph();
+ const by = (cls: string) => Object.entries(g).filter(([, n]) => n.class_type === cls);
+ expect(by("UNETLoader").map(([, n]) => n.inputs.unet_name).sort()).toEqual(["ideogram4_int8_convrot.safetensors", "ideogram4_unconditional_int8_convrot.safetensors"]);
+ expect(by("CLIPLoader")[0][1].inputs).toMatchObject({ clip_name: "qwen3vl_8b_fp8_scaled.safetensors", type: "ideogram4" });
+ const [[, guider]] = by("DualModelGuider");
+ expect(guider.inputs.cfg).toBe(7);
+ expect(g[(guider.inputs.model_negative as [string, number])[0]].inputs.unet_name).toBe("ideogram4_unconditional_int8_convrot.safetensors");
+ expect(g[(guider.inputs.negative as [string, number])[0]].class_type).toBe("ConditioningZeroOut");
+ expect(g[(guider.inputs.model as [string, number])[0]].inputs).toMatchObject({ cfg: 3, start_percent: 0.7, end_percent: 1 });
+ expect(by("KSamplerSelect")[0][1].inputs.sampler_name).toBe("euler");
+ expect(g["98:156"].inputs.choice).toBe("Quality");
+ const table = JSON.parse(String(by("JsonExtractString").find(([, n]) => typeof n.inputs.json_string === "string")![1].inputs.json_string));
+ expect(table).toMatchObject({ Quality: { num_steps: 48, mu: 0, std: 1.5 }, Default: { num_steps: 20, mu: 0, std: 1.75 }, Turbo: { num_steps: 12, mu: 0.5, std: 1.75 } });
+ expect(by("ComfyMathExpression").map(([, n]) => n.inputs.expression)).toEqual(["max(((a + 15) // 16) * 16, 256)", "max(((a + 15) // 16) * 16, 256)"]);
+ // Non-commercial weights, said as information.
+ expect(licenceTerms(wf.license!).flags).toEqual(["non-commercial"]);
+ expect(licenceInfo(wf.license!)).toMatchObject({ name: "Ideogram Non-Commercial Model Agreement", class: "non-commercial" });
+ });
+
+ it("is the open engine's text-to-image model for typography, with the preset control the graph runs when left alone", () => {
+ const m = getModel("oss-ideogram-4")!;
+ expect(m).toMatchObject({ engine: "open", kind: "image", family: "ideogram", options: { promptFormat: "ideogram4", seed: true } });
+ expect(m.badges).toEqual(expect.arrayContaining(["open", "new", "top"]));
+ expect(m.routes.map((r) => [r.op, r.provider, r.endpoint])).toEqual([["t2i", "comfyui", "ideogram4-t2i"]]);
+ expect(m.tagline).toMatch(/24 GB GPU · non-commercial weights/);
+ // First among the open-source text-to-image models, after the Originals (the owner's order: Ideogram 4, Qwen-Image 2.1,
+ // Krea 2, MOSS, FIBO 2).
+ expect(MODELS.find((x) => x.id.startsWith("oss-") && x.routes.some((r) => r.op === "t2i"))?.id).toBe("oss-ideogram-4");
+ const [preset] = m.options.controls!;
+ expect(preset).toMatchObject({ param: "preset", values: ["Quality", "Default", "Turbo"], default: graph()["98:156"].inputs.choice });
+ expect(Object.keys(entry()!.bindings)).toContain(preset.param);
+ // Text to image only: a picture added doesn't make it an edit.
+ const plan = (r: Record<string, unknown>) => planGeneration({ feature: "image", modelId: "oss-ideogram-4", ...r } as Parameters<typeof planGeneration>[0], getModel, getPreset);
+ expect(plan({ prompt: "a red fox" }).op).toBe("t2i");
+ expect(plan({ prompt: "a red fox", inputs: { images: ["/a.png"] } }).op).toBe("t2i");
+ expect(() => plan({})).toThrow("Write a prompt first");
+ expect(plan({ prompt: "a red fox" }).params).toMatchObject({ aspectRatio: "1:1", resolution: "1.5K" });
+ });
+
+ it("fills the caption, the size on the 16-pixel grid, the seed and the preset", async () => {
+ const wf = await prepare({ prompt: good, aspectRatio: "4:3", resolution: "1.5K" });
+ expect(wf["98:24"].inputs.text).toBe(good);
+ const want = computeDimensions("4:3", "1.5K", {}, 16);
+ expect([wf["98:27"].inputs.value, wf["98:28"].inputs.value]).toEqual([want.width, want.height]);
+ expect(wf["98:18"].inputs.noise_seed).toBe(7);
+ expect(wf["98:156"].inputs.choice).toBe("Quality");
+ expect((await prepare({ prompt: good, extra: { preset: "Turbo" } }))["98:156"].inputs.choice).toBe("Turbo");
+ // Every shape lands on the grid within 2048 px a side.
+ for (const ar of ["1:1", "16:9", "9:16", "21:9", "4:5"]) {
+ for (const res of ["1K", "1.5K", "2K"]) {
+ const p = await prepare({ prompt: good, aspectRatio: ar, resolution: res });
+ const [w, h] = [Number(p["98:27"].inputs.value), Number(p["98:28"].inputs.value)];
+ expect([w % 16, h % 16, w <= 2048 && h <= 2048], `${ar} ${res}`).toEqual([0, 0, true]);
+ }
+ }
+ });
+});
+
+describe("Ideogram 4 runs", () => {
+ /** A demo run of Ideogram 4; what the provider was handed comes back too. */
+ async function run(prompt: string, params: Record<string, unknown> = {}) {
+ const submit = mockProvider.submit;
+ const handed: GenInput[] = [];
+ mockProvider.submit = async (ctx) => {
+ if (ctx.model.id === "oss-ideogram-4") handed.push(ctx.input);
+ return submit(ctx);
+ };
+ try {
+ const [g] = createGenerations({ feature: "image", modelId: "oss-ideogram-4", prompt, params });
+ return { g: await settled(g.id), handed };
+ } finally {
+ mockProvider.submit = submit;
+ }
+ }
+
+ it("writes the caption before the run and keeps it as the run's prompt, in place of Enhance", async () => {
+ setSetting("enhanceProvider", "local");
+ llm.answers = [JSON.stringify(GOOD, null, 2)];
+ const { g, handed } = await run("a model on a villa terrace", { enhancePrompt: true });
+ expect(g.status).toBe("succeeded");
+ expect(g.prompt).toBe(good);
+ expect(handed[0].prompt).toBe(good);
+ // One call, the caption writer's (the generic Enhance didn't run first).
+ expect(llm.seen).toHaveLength(1);
+ expect(llm.seen[0].system).toMatch(/Ideogram 4/);
+ expect(llm.seen[0].user).toBe("Idea: a model on a villa terrace\nPicture: 1536 × 1536 px, square");
+ });
+
+ it("keeps a caption it is given (a reused run) without asking the LLM", async () => {
+ setSetting("enhanceProvider", "local");
+ const { g } = await run(JSON.stringify({ aspect_ratio: "1:1", ...GOOD }));
+ expect(g.prompt).toBe(good);
+ expect(llm.seen).toEqual([]);
+ });
+
+ it("wraps the words when no LLM is set up", async () => {
+ setSetting("enhanceProvider", "none");
+ const { g, handed } = await run("a red fox in deep snow");
+ expect(g.prompt).toBe(captionFromWords("a red fox in deep snow"));
+ expect(handed[0].prompt).toBe(g.prompt);
+ });
+});
diff --git a/workflows/comfyui/model-pins.json b/workflows/comfyui/model-pins.json
index 8639fe51..45610d46 100644
--- a/workflows/comfyui/model-pins.json
+++ b/workflows/comfyui/model-pins.json
@@ -94,6 +94,21 @@
"sizeBytes": 2521292758,
"sha256": "e7c3091949c27e2d55ae6d5df917b99dadfebbf308e5a50d0ade0d16c90297ae"
},
+ "https://huggingface.co/Comfy-Org/Ideogram-4/resolve/main/diffusion_models/ideogram4_int8_convrot.safetensors": {
+ "revision": "2aa6c75ce6d5fabded0ca4d0f76abbfaf8edc87d",
+ "sizeBytes": 9583465712,
+ "sha256": "a9164002943463b4c7b2abd88c82a488c088acc35762651e4d8604d6ce4a163d"
+ },
+ "https://huggingface.co/Comfy-Org/Ideogram-4/resolve/main/diffusion_models/ideogram4_unconditional_int8_convrot.safetensors": {
+ "revision": "2aa6c75ce6d5fabded0ca4d0f76abbfaf8edc87d",
+ "sizeBytes": 9583465712,
+ "sha256": "cd03ed94f244c9cb705e7d30ca0f40b5f5b004bb20674117adff88d16416c23d"
+ },
+ "https://huggingface.co/Comfy-Org/Ideogram-4/resolve/main/text_encoders/qwen3vl_8b_fp8_scaled.safetensors": {
+ "revision": "2aa6c75ce6d5fabded0ca4d0f76abbfaf8edc87d",
+ "sizeBytes": 10588637512,
+ "sha256": "4ba424cf62e51392e4d1a39933e803706f4e823c1065f36aaf149c6453f66bcd"
+ },
"https://huggingface.co/Comfy-Org/Krea-2/resolve/main/diffusion_models/krea2_turbo_int8_convrot.safetensors": {
"revision": "1171f4dc7e325bf3734586942e737872506c73e1",
"sizeBytes": 13492686496,