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.

Image studios: Soul presets fallback, colour signatures and moodboards

Claudee8745c22074f
diff --git a/scripts/gen-cloud-models.py b/scripts/gen-cloud-models.py
index d8f81a87..eb51fb0b 100644
--- a/scripts/gen-cloud-models.py
+++ b/scripts/gen-cloud-models.py
@@ -153,6 +153,12 @@ model("recraft-4-style-pro", "Recraft V4 Styles Pro", "Recraft", "recraft", "ima
[("edit", "recraft/v4/style/pro/text-to-image")],
badges=["pro"], pricing=("image", 0.1, "+$0.005 when a new style is made from references"), defaults={"aspectRatio": "1:1"},
controls=[("style_match", "Style match")])
+# A moodboard's saved Recraft style (meta.styleId from a Recraft V4 Styles run) on its own: style_id, no references.
+# Hidden: only the Image studio's Moodboard chip routes here, and it always sends the style id.
+model("recraft-4-style-saved", "Recraft V4 Styles · saved style", "Recraft", "recraft", "image",
+ "A new picture in a style saved from your moodboard",
+ [("t2i", "recraft/v4/style/text-to-image", "fal", {"drop": ["images", "styleImages"]})],
+ pricing=("image", 0.035), defaults={"aspectRatio": "1:1"}, controls=[("style_match", "Style match")], hidden=True)
model("ideogram-3", "Ideogram 3.0", "Ideogram", "ideogram", "image",
"Posters and type in your exact brand colours, with 60+ style presets and style references",
[("t2i", "fal-ai/ideogram/v3"),
diff --git a/scripts/gen-higgsfield-presets.py b/scripts/gen-higgsfield-presets.py
new file mode 100644
index 00000000..c149fc70
--- /dev/null
+++ b/scripts/gen-higgsfield-presets.py
@@ -0,0 +1,130 @@
+#!/usr/bin/env python3
+"""
+Generate src/lib/catalog/higgsfield-presets.generated.ts from docs/research/higgsfield-image-studios.json.
+
+Outputs (all static, used when there is no Higgsfield key or the live list fails):
+ SOUL_PRESETS — the 106 Soul (v1) presets and the 33 Soul 2.0 presets / curated moodboards:
+ id (the API's style_id), name, categories, description, whether the description
+ is ours (inferred) and, for Soul 2.0, whether it's one of the curated moodboards.
+ SOUL_CATEGORIES — the picker's category tabs per model, in Higgsfield's order.
+ PHOTODUMP_PACKS — Soul 2.0 Photodump packs and Instadump packs: name, photo count, description.
+ FASHION_TEMPLATES — Fashion Factory templates: name, preview shot count, description.
+
+No preview URLs are copied: Fuobe draws its own previews, so nothing is hot-linked from Higgsfield's CDN.
+
+Run: python3 scripts/gen-higgsfield-presets.py
+"""
+import json
+import re
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+RESEARCH = json.loads((ROOT / "docs/research/higgsfield-image-studios.json").read_text())
+OUT = ROOT / "src/lib/catalog/higgsfield-presets.generated.ts"
+
+V1_TABS = ["New", "TikTok Core", "Instagram Aesthetics", "Camera Presets", "Beauty", "Mood", "Surreal", "Graphic Art"]
+V2_TABS = ["Mood", "Styles", "Camera"]
+
+
+def warn(msg):
+ print(f"warning: {msg}")
+
+
+def slug(s):
+ return re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-")
+
+
+def clean(s):
+ return re.sub(r"\s+", " ", s or "").strip()
+
+
+presets = []
+for p in RESEARCH["soulPresets"]:
+ model = p["model"]
+ if model not in ("soul-v1", "soul-v2"):
+ warn(f"unknown preset model {model}")
+ continue
+ cats = list(p.get("categories") or [])
+ if model == "soul-v2" and p.get("category") and p["category"] != "All presets":
+ cats = [p["category"]]
+ tabs = V1_TABS if model == "soul-v1" else V2_TABS
+ for c in cats:
+ if c not in tabs:
+ warn(f"{p['name']}: category {c} not in the {model} tabs")
+ entry = {
+ "id": p["id"],
+ "name": clean(p["name"]),
+ "model": model,
+ "categories": cats,
+ "description": clean(p["description"]),
+ "inferred": p.get("descriptionSource") == "inferred",
+ }
+ if model == "soul-v2":
+ entry["curated"] = bool(p.get("curatedMoodboard"))
+ presets.append(entry)
+
+ids = [p["id"] for p in presets]
+if len(ids) != len(set(ids)):
+ warn("duplicate preset ids")
+counts = RESEARCH["counts"]
+v1 = [p for p in presets if p["model"] == "soul-v1"]
+v2 = [p for p in presets if p["model"] == "soul-v2"]
+if len(v1) != counts["soulV1Presets"] or len(v2) != counts["soulV2Presets"]:
+ warn(f"preset counts {len(v1)}/{len(v2)} differ from research counts {counts['soulV1Presets']}/{counts['soulV2Presets']}")
+
+packs = []
+for t in RESEARCH["photodump"]["templates"]:
+ version = t.get("version", "")
+ if version.startswith("legacy"):
+ continue # the fixed 26-shot Soul v1 set; superseded by the packs below
+ product = "instadump" if version.startswith("Instadump") else "photodump"
+ packs.append({
+ "id": slug(t["name"]),
+ "higgsfieldId": t.get("id"),
+ "name": t["name"],
+ "count": t["count"],
+ "description": clean(t["description"]),
+ "inferred": t.get("descriptionSource") == "inferred",
+ "product": product,
+ **({"author": t["author"]} if t.get("author") else {}),
+ })
+
+templates = []
+for t in sorted(RESEARCH["fashionFactory"]["templates"], key=lambda x: x.get("priority", 99)):
+ templates.append({
+ "id": slug(t["name"]),
+ "higgsfieldId": t.get("id"),
+ "name": t["name"],
+ "shots": t["previewCount"],
+ "description": clean(t["description"]),
+ "inferred": t.get("descriptionSource") == "inferred",
+ })
+if len(templates) != counts["fashionFactoryTemplates"]:
+ warn("fashion template count differs from research")
+
+defaults = {"soul-v1": next((p["id"] for p in v1 if p["name"] == "General"), None), "soul-v2": next((p["id"] for p in v2 if p["name"] == "General"), None)}
+
+
+def ts(v):
+ return json.dumps(v, ensure_ascii=False, indent=2)
+
+
+OUT.write_text(
+ "// GENERATED by scripts/gen-higgsfield-presets.py from docs/research/higgsfield-image-studios.json — do not edit.\n"
+ "// Higgsfield's own preset ids (the API's style_id), names and categories; descriptions marked `inferred` are ours.\n\n"
+ "export type SoulPresetModel = \"soul-v1\" | \"soul-v2\";\n\n"
+ "export interface SoulPreset {\n"
+ " id: string;\n name: string;\n model: SoulPresetModel;\n categories: string[];\n description: string;\n"
+ " /** The description is Fuobe's (Higgsfield publishes none for this preset). */\n inferred: boolean;\n"
+ " /** Soul 2.0: one of the curated moodboards in the Moodboard panel. */\n curated?: boolean;\n}\n\n"
+ "export interface PackMeta {\n id: string;\n higgsfieldId?: string;\n name: string;\n count: number;\n description: string;\n inferred: boolean;\n"
+ " product: \"photodump\" | \"instadump\";\n author?: string;\n}\n\n"
+ "export interface FashionTemplateMeta {\n id: string;\n higgsfieldId?: string;\n name: string;\n /** Shots in Higgsfield's preview carousel (Fuobe's photoset makes one photo per shot). */\n shots: number;\n"
+ " description: string;\n inferred: boolean;\n}\n\n"
+ f"export const SOUL_CATEGORIES: Record<SoulPresetModel, string[]> = {ts({'soul-v1': V1_TABS, 'soul-v2': V2_TABS})};\n\n"
+ f"/** The default (\"General\") preset of each model. */\nexport const SOUL_DEFAULT: Record<SoulPresetModel, string> = {ts(defaults)};\n\n"
+ f"export const SOUL_PRESETS: SoulPreset[] = {ts(presets)};\n\n"
+ f"export const PHOTODUMP_PACKS: PackMeta[] = {ts(packs)};\n\n"
+ f"export const FASHION_TEMPLATES: FashionTemplateMeta[] = {ts(templates)};\n"
+)
+print(f"wrote {OUT.relative_to(ROOT)}: {len(v1)} Soul + {len(v2)} Soul 2.0 presets, {len(packs)} packs, {len(templates)} fashion templates")
diff --git a/src/app/(studio)/moodboards/page.tsx b/src/app/(studio)/moodboards/page.tsx
new file mode 100644
index 00000000..f89a7f26
--- /dev/null
+++ b/src/app/(studio)/moodboards/page.tsx
@@ -0,0 +1,8 @@
+import type { Metadata } from "next";
+import { MoodboardsView } from "@/components/moodboards/moodboards-view";
+
+export const metadata: Metadata = { title: "Moodboards" };
+
+export default function Page() {
+ return <MoodboardsView />;
+}
diff --git a/src/app/api/moodboards/[id]/retry/route.ts b/src/app/api/moodboards/[id]/retry/route.ts
new file mode 100644
index 00000000..414670be
--- /dev/null
+++ b/src/app/api/moodboards/[id]/retry/route.ts
@@ -0,0 +1,15 @@
+import { z } from "zod";
+import { retryMoodboard } from "@/server/moodboards";
+
+const Body = z.object({ engine: z.enum(["cloud", "open"]).optional() });
+
+/** Run a board's cover job again (after a failure, or on the other engine). */
+export async function POST(request: Request, ctx: RouteContext<"/api/moodboards/[id]/retry">) {
+ const { id } = await ctx.params;
+ const parsed = Body.safeParse(await request.json().catch(() => ({})));
+ try {
+ return Response.json(retryMoodboard(id, parsed.success ? parsed.data.engine : undefined));
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: /not found/i.test((e as Error).message) ? 404 : 409 });
+ }
+}
diff --git a/src/app/api/moodboards/[id]/route.ts b/src/app/api/moodboards/[id]/route.ts
new file mode 100644
index 00000000..a20a8950
--- /dev/null
+++ b/src/app/api/moodboards/[id]/route.ts
@@ -0,0 +1,28 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { deleteMoodboard, getMoodboard, renameMoodboard } from "@/server/moodboards";
+
+const Patch = z.object({ name: z.string().max(200) });
+
+export async function GET(_req: Request, ctx: RouteContext<"/api/moodboards/[id]">) {
+ await connection();
+ const { id } = await ctx.params;
+ const m = getMoodboard(id);
+ return m ? Response.json(m) : Response.json({ error: "Not found" }, { status: 404 });
+}
+
+export async function PATCH(request: Request, ctx: RouteContext<"/api/moodboards/[id]">) {
+ const { id } = await ctx.params;
+ const parsed = Patch.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Please enter a moodboard name" }, { status: 400 });
+ try {
+ return Response.json(renameMoodboard(id, parsed.data.name));
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: /not found/i.test((e as Error).message) ? 404 : 400 });
+ }
+}
+
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/moodboards/[id]">) {
+ const { id } = await ctx.params;
+ return deleteMoodboard(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });
+}
diff --git a/src/app/api/moodboards/[id]/train/route.ts b/src/app/api/moodboards/[id]/train/route.ts
new file mode 100644
index 00000000..a4d069e6
--- /dev/null
+++ b/src/app/api/moodboards/[id]/train/route.ts
@@ -0,0 +1,11 @@
+import { trainMoodboard } from "@/server/moodboards";
+
+/** Train the board as a Z-Image Turbo style LoRA (a style element, AI-Toolkit on your own GPU). */
+export async function POST(_req: Request, ctx: RouteContext<"/api/moodboards/[id]/train">) {
+ const { id } = await ctx.params;
+ try {
+ return Response.json(trainMoodboard(id), { status: 202 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: /not found/i.test((e as Error).message) ? 404 : 409 });
+ }
+}
diff --git a/src/app/api/moodboards/route.ts b/src/app/api/moodboards/route.ts
new file mode 100644
index 00000000..f9d03769
--- /dev/null
+++ b/src/app/api/moodboards/route.ts
@@ -0,0 +1,26 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { createMoodboard, curatedMoodboards, listMoodboards } from "@/server/moodboards";
+
+const Body = z.object({
+ name: z.string().max(200),
+ images: z.array(z.string().startsWith("/api/files/")).max(200),
+ collages: z.array(z.string().startsWith("/api/files/")).max(2).optional(),
+ engine: z.enum(["cloud", "open"]).default("cloud"),
+});
+
+/** Your moodboards (each one's status follows its cover job) and Soul 2.0's curated looks. */
+export async function GET() {
+ await connection();
+ return Response.json({ items: listMoodboards(), curated: curatedMoodboards() });
+}
+
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Upload at least 5 photos to continue." }, { status: 400 });
+ try {
+ return Response.json(createMoodboard(parsed.data), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 400 });
+ }
+}
diff --git a/src/app/api/palettes/[id]/route.ts b/src/app/api/palettes/[id]/route.ts
new file mode 100644
index 00000000..141b1b03
--- /dev/null
+++ b/src/app/api/palettes/[id]/route.ts
@@ -0,0 +1,24 @@
+import { z } from "zod";
+import { deletePalette, renamePalette } from "@/server/palettes";
+
+const Patch = z.object({ name: z.string().trim().min(1).max(60) });
+
+export async function PATCH(request: Request, ctx: RouteContext<"/api/palettes/[id]">) {
+ const { id } = await ctx.params;
+ const parsed = Patch.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Give the palette a name" }, { status: 400 });
+ try {
+ return Response.json(renamePalette(id, parsed.data.name));
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: /not found/i.test((e as Error).message) ? 404 : 400 });
+ }
+}
+
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/palettes/[id]">) {
+ const { id } = await ctx.params;
+ try {
+ return deletePalette(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 400 });
+ }
+}
diff --git a/src/app/api/palettes/lock/route.ts b/src/app/api/palettes/lock/route.ts
new file mode 100644
index 00000000..4f6a31b4
--- /dev/null
+++ b/src/app/api/palettes/lock/route.ts
@@ -0,0 +1,41 @@
+import { z } from "zod";
+import { createLockedRun } from "@/server/palettes";
+
+const Hex = z.string().regex(/^#?[0-9a-fA-F]{6}$/);
+
+/** The image request as the composer builds it (the fields an image studio sends). */
+const RequestSchema = z.object({
+ feature: z.string().min(1).max(80),
+ presetId: z.string().max(120).optional(),
+ modelId: z.string().min(1).max(120),
+ op: z.string().max(40).optional(),
+ prompt: z.string().max(10_000).optional(),
+ negativePrompt: z.string().max(4_000).optional(),
+ inputs: z.object({ images: z.array(z.string()).max(14).optional() }).optional(),
+ params: z
+ .object({
+ aspectRatio: z.string().max(20).optional(),
+ resolution: z.string().max(20).optional(),
+ numOutputs: z.number().int().min(1).max(8).optional(),
+ seed: z.number().int().optional(),
+ enhancePrompt: z.boolean().optional(),
+ palette: z.array(Hex).max(16).optional(),
+ styleId: z.string().max(200).optional(),
+ extra: z.record(z.string(), z.unknown()).optional(),
+ })
+ .optional(),
+});
+
+const Body = z.object({ request: RequestSchema, colors: z.array(Hex).min(1).max(16), strength: z.number().min(0).max(1).optional() });
+
+/** Make the images, then recolour each one to the palette (open engine: a chained palette-transfer step). */
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") }, { status: 400 });
+ try {
+ const { items } = createLockedRun(parsed.data.request as Parameters<typeof createLockedRun>[0], parsed.data.colors, parsed.data.strength);
+ return Response.json({ items }, { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 422 });
+ }
+}
diff --git a/src/app/api/palettes/route.ts b/src/app/api/palettes/route.ts
new file mode 100644
index 00000000..d647574e
--- /dev/null
+++ b/src/app/api/palettes/route.ts
@@ -0,0 +1,27 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { createPalette, listPalettes, signatureCaps } from "@/server/palettes";
+
+const Body = z.object({
+ name: z.string().trim().min(1).max(60),
+ colors: z.array(z.string().max(9)).min(1).max(12),
+ background: z.string().max(9).nullable().optional(),
+ source: z.enum(["manual", "images"]).default("manual"),
+ thumb: z.string().startsWith("/api/files/").nullable().optional(),
+});
+
+/** Your colour signatures and the 50 built-in palettes, plus which models take a palette natively. */
+export async function GET() {
+ await connection();
+ return Response.json({ items: listPalettes(), caps: signatureCaps() });
+}
+
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Give the palette a name and 1–12 colours" }, { status: 400 });
+ try {
+ return Response.json(createPalette(parsed.data), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 400 });
+ }
+}
diff --git a/src/app/api/photodump/character/route.ts b/src/app/api/photodump/character/route.ts
new file mode 100644
index 00000000..544fcafb
--- /dev/null
+++ b/src/app/api/photodump/character/route.ts
@@ -0,0 +1,34 @@
+import { z } from "zod";
+import { createSheet, previewSheet, type SheetRun } from "@/server/photodump";
+
+const Engine = z.enum(["cloud", "open"]);
+
+const Body = z.discriminatedUnion("mode", [
+ z.object({ mode: z.literal("reference"), engine: Engine, images: z.array(z.string().startsWith("/api/files/")).max(5), details: z.string().max(300).optional() }),
+ z.object({
+ mode: z.literal("cast"),
+ engine: Engine,
+ cast: z.record(z.string().max(40), z.union([z.string().max(300), z.number(), z.array(z.string().max(60)).max(8)])),
+ details: z.string().max(300).optional(),
+ }),
+ z.object({ mode: z.literal("describe"), engine: Engine, prompt: z.string().max(2000) }),
+]);
+
+/**
+ * Character Sheet: a turnaround sheet from 1–5 reference photos, from a Soul Cast build, or from a
+ * description (the AI Influencer app). `?preview=1` prices it instead.
+ */
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) {
+ const images = (parsed.error.issues.find((i) => i.path[0] === "images") && "Maximum 5 images") || "Upload at least 1 image";
+ return Response.json({ error: images }, { status: 400 });
+ }
+ const input = parsed.data as SheetRun;
+ if (new URL(request.url).searchParams.get("preview")) return Response.json(previewSheet(input));
+ try {
+ return Response.json(createSheet(input), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 422 });
+ }
+}
diff --git a/src/app/api/photodump/fashion/route.ts b/src/app/api/photodump/fashion/route.ts
new file mode 100644
index 00000000..75ab5748
--- /dev/null
+++ b/src/app/api/photodump/fashion/route.ts
@@ -0,0 +1,27 @@
+import { z } from "zod";
+import { createFashion, previewFashion, type FashionRun } from "@/server/photodump";
+
+const File = z.string().startsWith("/api/files/");
+const Engine = z.enum(["cloud", "open"]);
+
+const Body = z.discriminatedUnion("step", [
+ z.object({ step: z.literal("base"), templateId: z.string().max(80), elementId: z.string().max(40), engine: Engine }),
+ z.object({ step: z.literal("outfit"), templateId: z.string().max(80), base: File, garment: File, engine: Engine, modelId: z.string().max(80).optional() }),
+ z.object({ step: z.literal("photoset"), templateId: z.string().max(80), dressed: File, engine: Engine }),
+]);
+
+/**
+ * Fashion Factory steps: 4 base shots of the character in the template's set, the outfit (try-on),
+ * and the photoset (one photo per template shot). `?preview=1` prices a step instead.
+ */
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Template required" }, { status: 400 });
+ const input = parsed.data as FashionRun;
+ if (new URL(request.url).searchParams.get("preview")) return Response.json(previewFashion(input));
+ try {
+ return Response.json(createFashion(input), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 422 });
+ }
+}
diff --git a/src/app/api/photodump/packs/[id]/route.ts b/src/app/api/photodump/packs/[id]/route.ts
new file mode 100644
index 00000000..3df0c708
--- /dev/null
+++ b/src/app/api/photodump/packs/[id]/route.ts
@@ -0,0 +1,6 @@
+import { deleteUserPack } from "@/server/photodump";
+
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/photodump/packs/[id]">) {
+ const { id } = await ctx.params;
+ return deleteUserPack(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });
+}
diff --git a/src/app/api/photodump/packs/route.ts b/src/app/api/photodump/packs/route.ts
new file mode 100644
index 00000000..b37fcde7
--- /dev/null
+++ b/src/app/api/photodump/packs/route.ts
@@ -0,0 +1,21 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { createUserPack, listUserPacks } from "@/server/photodump";
+
+const Body = z.object({ name: z.string().max(200), refs: z.array(z.string().startsWith("/api/files/")).max(40) });
+
+export async function GET() {
+ await connection();
+ return Response.json({ packs: listUserPacks() });
+}
+
+/** Create a pack from up to 15 reference photos: each becomes one photo of the dump. */
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Upload your reference set up to 15 photos" }, { status: 400 });
+ try {
+ return Response.json(createUserPack(parsed.data), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 400 });
+ }
+}
diff --git a/src/app/api/photodump/route.ts b/src/app/api/photodump/route.ts
new file mode 100644
index 00000000..5ca3d5a9
--- /dev/null
+++ b/src/app/api/photodump/route.ts
@@ -0,0 +1,35 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { createPhotodump, listUserPacks, previewPhotodump } from "@/server/photodump";
+
+const Body = z
+ .object({
+ packId: z.string().min(1).max(80),
+ engine: z.enum(["cloud", "open"]),
+ elementId: z.string().max(40).optional(),
+ selfie: z.string().startsWith("/api/files/").optional(),
+ aspectRatio: z.string().max(10).optional(),
+ modelId: z.string().max(80).optional(),
+ })
+ .refine((b) => !!b.elementId || !!b.selfie, { message: "Pick a character or add a selfie" });
+
+/** Your own packs (the built-in ones ship with the page). */
+export async function GET() {
+ await connection();
+ return Response.json({ packs: listUserPacks() });
+}
+
+/**
+ * Generate a photodump: one photo per pack shot, as one batch. `?preview=1` prices it instead
+ * (model, photo count, cost, demo, notes, or the error that would stop it).
+ */
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: parsed.error.issues[0]?.message ?? "Pick a pack" }, { status: 400 });
+ if (new URL(request.url).searchParams.get("preview")) return Response.json(previewPhotodump(parsed.data));
+ try {
+ return Response.json(createPhotodump(parsed.data), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 422 });
+ }
+}
diff --git a/src/app/api/providers/higgsfield/presets/route.ts b/src/app/api/providers/higgsfield/presets/route.ts
index bbf053d7..d66bf76e 100644
--- a/src/app/api/providers/higgsfield/presets/route.ts
+++ b/src/app/api/providers/higgsfield/presets/route.ts
@@ -1,14 +1,31 @@
import { connection } from "next/server";
+import { presetFallback } from "@/lib/catalog/packs";
import { higgsfieldKey, higgsfieldPresets } from "@/server/providers/higgsfield";
-/** Soul styles, Genjutsu looks and Marketing Studio templates, straight from Higgsfield. */
+/**
+ * Soul styles, Genjutsu looks and Marketing Studio templates, straight from Higgsfield. Soul and
+ * Soul 2.0 fall back to the researched list (same ids, with categories) when there's no key or the
+ * live list fails, so the picker always works and the id is right once a key is added.
+ */
export async function GET(request: Request) {
await connection();
const source = new URL(request.url).searchParams.get("source") ?? "";
- if (!higgsfieldKey()) return Response.json({ items: [], error: "Add a Higgsfield API key in Settings to load these" });
+ const fallback = presetFallback(source);
+ if (!higgsfieldKey()) {
+ if (fallback) return Response.json({ ...fallback, fallback: true, note: "Built-in list · add a Higgsfield key in Settings for previews" });
+ return Response.json({ items: [], error: "Add a Higgsfield API key in Settings to load these" });
+ }
try {
- return Response.json({ items: await higgsfieldPresets(source) });
+ const items = await higgsfieldPresets(source);
+ if (!items.length && fallback) return Response.json({ ...fallback, fallback: true, note: "Higgsfield returned no styles — showing the built-in list" });
+ // Live items get the researched categories and descriptions where the ids match.
+ const known = new Map(fallback?.items.map((p) => [p.id, p]));
+ return Response.json({
+ items: items.map((p) => ({ ...p, categories: known.get(p.id)?.categories ?? (p.group ? [p.group] : []), description: known.get(p.id)?.description })),
+ ...(fallback && { categories: fallback.categories }),
+ });
} catch (e) {
+ if (fallback) return Response.json({ ...fallback, fallback: true, note: `Higgsfield's list didn't load (${(e as Error).message}) — showing the built-in list` });
return Response.json({ items: [], error: (e as Error).message }, { status: 502 });
}
}
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index 8ea7fba1..ef3ac3cb 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -38,6 +38,10 @@ import {
Library,
PersonStanding,
Scissors,
+ Images,
+ Camera,
+ Shirt,
+ UserRoundCog,
type LucideIcon,
} from "lucide-react";
import {
@@ -110,6 +114,10 @@ const NAV: NavGroupDef[] = [
label: "Studios",
items: [
{ href: "/cinema", label: "Cinema Studio", icon: Clapperboard },
+ { href: "/moodboards", label: "Moodboards", icon: Images },
+ { href: "/photodump", label: "Photodump", icon: Camera },
+ { href: "/fashion-factory", label: "Fashion Factory", icon: Shirt },
+ { href: "/character-sheet", label: "Character Sheet", icon: UserRoundCog },
{ href: "/lipsync", label: "Lipsync & avatars", icon: Mic2 },
{ href: "/motion-control", label: "Motion control", icon: PersonStanding },
{ href: "/video-edit", label: "Edit video", icon: Scissors },
diff --git a/src/components/moodboards/cards.tsx b/src/components/moodboards/cards.tsx
new file mode 100644
index 00000000..412d5a23
--- /dev/null
+++ b/src/components/moodboards/cards.tsx
@@ -0,0 +1,57 @@
+"use client";
+
+import { AlertCircle, Check, Loader2 } from "lucide-react";
+import type { MoodboardStatus } from "@/lib/catalog/palettes";
+import { cn } from "@/lib/utils";
+import { STATUS_LABEL, type CuratedMoodboard, type Moodboard } from "./logic";
+
+/** A drawn cover for a curated look (no Higgsfield images are hot-linked): its hue, its name. */
+export function CuratedCover({ m, className }: { m: Pick<CuratedMoodboard, "name" | "hue">; className?: string }) {
+ return (
+ <span
+ aria-hidden
+ className={cn("relative block overflow-hidden", className)}
+ style={{ background: `radial-gradient(120% 90% at 20% 15%, oklch(0.86 0.09 ${m.hue}), transparent 60%), linear-gradient(160deg, oklch(0.62 0.14 ${(m.hue + 30) % 360}), oklch(0.32 0.08 ${(m.hue + 70) % 360}))` }}
+ >
+ <span className="absolute inset-x-2 bottom-2 font-heading text-[19px] leading-tight text-white drop-shadow-sm">{m.name}</span>
+ </span>
+ );
+}
+
+export function StatusBadge({ status, className }: { status: MoodboardStatus; className?: string }) {
+ const busy = status !== "complete" && status !== "failed";
+ return (
+ <span
+ className={cn(
+ "inline-flex h-5 items-center gap-1 rounded-full px-2 text-[11px] font-medium",
+ status === "complete" ? "bg-success/15 text-success" : status === "failed" ? "bg-destructive/10 text-destructive" : "bg-background/90 text-foreground",
+ className,
+ )}
+ >
+ {busy && <Loader2 className="size-3 animate-spin" />}
+ {status === "complete" && <Check className="size-3" />}
+ {status === "failed" && <AlertCircle className="size-3" />}
+ {STATUS_LABEL[status]}
+ </span>
+ );
+}
+
+/** A personal board's cover: the cover image (or a 2×2 of its first images while it builds). */
+export function BoardCover({ m, className }: { m: Pick<Moodboard, "cover" | "images" | "status">; className?: string }) {
+ const done = m.status === "complete" && m.cover;
+ return (
+ <span className={cn("relative block overflow-hidden bg-muted", className)}>
+ {done ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={m.cover!} alt="" loading="lazy" className="size-full object-cover" />
+ ) : (
+ <span className="grid size-full grid-cols-2 grid-rows-2 gap-px opacity-80">
+ {m.images.slice(0, 4).map((src) => (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img key={src} src={src} alt="" loading="lazy" className="size-full object-cover" />
+ ))}
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/src/components/moodboards/create-moodboard.tsx b/src/components/moodboards/create-moodboard.tsx
new file mode 100644
index 00000000..aa75f70c
--- /dev/null
+++ b/src/components/moodboards/create-moodboard.tsx
@@ -0,0 +1,254 @@
+"use client";
+
+import { Check, ImagePlus, Library, Loader2, Plus, Upload, X } from "lucide-react";
+import { nanoid } from "nanoid";
+import { useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { LibraryGrid } from "@/components/studio/media-slot";
+import { uploadFile, useEngine } from "@/lib/api";
+import type { RGB } from "@/lib/catalog/palettes";
+import { cn } from "@/lib/utils";
+import { useMoodboardActions } from "./hooks";
+import { loadImage, pixelsOf, renderCollages } from "./images";
+import { colorFeature, COPY, imageProblem, moodboardError, MOODBOARD_LIMITS, representativeOrder, suggestMoodboardName, type Moodboard } from "./logic";
+
+interface Item {
+ id: string;
+ /** Duplicate check: the file's name/size/date, or the library URL. */
+ key: string;
+ preview: string;
+ url?: string;
+ uploading: boolean;
+ pixels: RGB[];
+}
+
+/** Bad / Good / Perfect: how far the board is from the recommended 20+ photos. */
+function quality(n: number): { label: string; tone: string; pct: number } {
+ if (n < MOODBOARD_LIMITS.min) return { label: "Bad", tone: "bg-destructive", pct: (n / 20) * 100 };
+ if (n < 20) return { label: "Good", tone: "bg-warning", pct: (n / 20) * 100 };
+ return { label: "Perfect", tone: "bg-success", pct: 100 };
+}
+
+/**
+ * "Create your moodboard": 5–80 images of one style (≥256 px, no duplicates), a name (suggested from
+ * the board's colours), then the board is ordered by how representative each image is, its 2×2
+ * collages are drawn in the browser, and the server starts the cover job.
+ */
+export function CreateMoodboardDialog({ open, onOpenChange, onCreated }: { open: boolean; onOpenChange: (o: boolean) => void; onCreated?: (m: Moodboard) => void }) {
+ const [items, setItems] = useState<Item[]>([]);
+ const [name, setName] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [libraryOpen, setLibraryOpen] = useState(false);
+ const input = useRef<HTMLInputElement>(null);
+ const [engine] = useEngine();
+ const { create } = useMoodboardActions();
+ const keys = useRef(new Set<string>());
+
+ // Closing throws the draft away.
+ const setOpen = (o: boolean) => {
+ if (!o) {
+ setItems((xs) => {
+ xs.forEach((x) => x.preview.startsWith("blob:") && URL.revokeObjectURL(x.preview));
+ return [];
+ });
+ keys.current = new Set();
+ setName("");
+ }
+ onOpenChange(o);
+ };
+
+ const suggestion = useMemo(() => {
+ const pooled = items.flatMap((i) => i.pixels.slice(0, 400));
+ return pooled.length ? suggestMoodboardName(pooled) : "";
+ }, [items]);
+
+ const add = async (src: { file?: File; url?: string; key: string }) => {
+ if (keys.current.size >= MOODBOARD_LIMITS.max) return toast(COPY.tooMany);
+ const preview = src.file ? URL.createObjectURL(src.file) : src.url!;
+ let img: HTMLImageElement;
+ try {
+ img = await loadImage(preview);
+ } catch {
+ if (src.file) URL.revokeObjectURL(preview);
+ return toast.error("That file isn't an image we can read — try PNG or JPG");
+ }
+ const problem = imageProblem({ width: img.naturalWidth, height: img.naturalHeight, key: src.key }, [...keys.current]);
+ if (problem) {
+ if (src.file) URL.revokeObjectURL(preview);
+ return toast(problem, { id: problem });
+ }
+ keys.current.add(src.key);
+ const id = nanoid(8);
+ setItems((xs) => [...xs, { id, key: src.key, preview, url: src.url, uploading: !src.url, pixels: pixelsOf(img) }]);
+ if (!src.file) return;
+ try {
+ const asset = await uploadFile(src.file);
+ setItems((xs) => xs.map((x) => (x.id === id ? { ...x, url: asset.url, uploading: false } : x)));
+ } catch (e) {
+ keys.current.delete(src.key);
+ setItems((xs) => xs.filter((x) => x.id !== id));
+ toast.error((e as Error).message || "Upload failed");
+ }
+ };
+ const addFiles = (files: Iterable<File>) => {
+ for (const f of files) if (/^image\/(png|jpe?g|webp)$/.test(f.type)) void add({ file: f, key: `${f.name}:${f.size}:${f.lastModified}` });
+ };
+ const remove = (it: Item) => {
+ keys.current.delete(it.key);
+ if (it.preview.startsWith("blob:")) URL.revokeObjectURL(it.preview);
+ setItems((xs) => xs.filter((x) => x.id !== it.id));
+ };
+
+ const submit = async () => {
+ const finalName = (name.trim() || suggestion).trim();
+ const err = moodboardError({ name: finalName, images: items.map((i) => i.id) });
+ if (err) return toast(err, { id: "moodboard-error" });
+ if (items.some((i) => i.uploading)) return toast("Wait for the uploads to finish");
+ setBusy(true);
+ try {
+ // Most representative first: the first 10 go to Recraft / cloud style references, 8 into the collages.
+ const order = representativeOrder(items.map((i) => colorFeature(i.pixels)));
+ const urls = order.map((i) => items[i].url!);
+ const collages = await Promise.all((await renderCollages(urls)).map((b, i) => uploadFile(new File([b], `collage-${i + 1}.jpg`, { type: "image/jpeg" })).then((a) => a.url)));
+ const m = await create.mutateAsync({ name: finalName.slice(0, MOODBOARD_LIMITS.nameMax), images: urls, collages, engine });
+ toast.success("Moodboard created");
+ onCreated?.(m);
+ setOpen(false);
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const q = quality(items.length);
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent
+ className="max-h-[92svh] gap-3 overflow-y-auto sm:max-w-2xl"
+ onPaste={(e) => {
+ const files = [...e.clipboardData.files];
+ if (files.length) {
+ e.preventDefault();
+ addFiles(files);
+ }
+ }}
+ >
+ <DialogHeader>
+ <DialogTitle className="font-sans text-[15px] font-semibold tracking-wide">{COPY.title}</DialogTitle>
+ <DialogDescription>{COPY.subtitle}</DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-2 text-[12.5px] sm:grid-cols-2">
+ <p className="rounded-lg bg-success/10 px-3 py-2">
+ <span className="font-medium">Recommended</span> · {COPY.recommended}
+ </p>
+ <p className="rounded-lg bg-destructive/10 px-3 py-2">
+ <span className="font-medium">Avoid</span> · {COPY.avoid}
+ </p>
+ </div>
+
+ <input ref={input} type="file" accept="image/png,image/jpeg,image/webp" multiple hidden onChange={(e) => (addFiles(e.target.files ?? []), (e.target.value = ""))} />
+ {items.length === 0 ? (
+ <div
+ onDragOver={(e) => e.preventDefault()}
+ onDrop={(e) => {
+ e.preventDefault();
+ addFiles(e.dataTransfer.files);
+ }}
+ className="flex flex-col items-center gap-3 rounded-xl border border-dashed px-4 py-8 text-center"
+ >
+ <ImagePlus className="size-7 text-muted-foreground" />
+ <div className="flex flex-wrap justify-center gap-2">
+ <Button size="sm" onClick={() => input.current?.click()}>
+ <Upload /> Upload from device
+ </Button>
+ <Popover open={libraryOpen} onOpenChange={setLibraryOpen}>
+ <PopoverTrigger asChild>
+ <Button size="sm" variant="outline">
+ <Library /> Upload from assets
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-80 p-2" collisionPadding={12}>
+ <p className="px-1 pb-2 text-[12.5px] text-muted-foreground">Use images you&apos;ve already created</p>
+ {libraryOpen && <LibraryGrid kinds={["image"]} onPick={(v) => void add({ url: v.ref, key: v.ref })} />}
+ </PopoverContent>
+ </Popover>
+ </div>
+ <p className="text-[12px] text-muted-foreground">PNG, JPG or Paste from clipboard</p>
+ </div>
+ ) : (
+ <div className="grid grid-cols-4 gap-1.5 sm:grid-cols-6">
+ {items.map((it, i) => (
+ <div key={it.id} className="relative aspect-square overflow-hidden rounded-lg bg-muted">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={it.preview} alt="" className="size-full object-cover" />
+ {it.uploading && (
+ <span className="absolute inset-0 grid place-items-center bg-background/60" role="status" aria-label="Uploading">
+ <Loader2 className="size-4 animate-spin" />
+ </span>
+ )}
+ <button
+ type="button"
+ onClick={() => remove(it)}
+ aria-label={`Remove image ${i + 1}`}
+ className="absolute top-0.5 right-0.5 grid size-5 place-items-center rounded-full bg-foreground/80 text-background"
+ >
+ <X className="size-3" />
+ </button>
+ </div>
+ ))}
+ {items.length < MOODBOARD_LIMITS.max && (
+ <button
+ type="button"
+ onClick={() => input.current?.click()}
+ className="grid aspect-square place-items-center rounded-lg border border-dashed text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ aria-label="Add image"
+ >
+ <span className="flex flex-col items-center gap-1 text-[11.5px]">
+ <Plus className="size-4" /> Add image
+ </span>
+ </button>
+ )}
+ </div>
+ )}
+
+ {items.length > 0 && (
+ <div className="flex flex-wrap items-center gap-3">
+ <div className="flex min-w-40 flex-1 items-center gap-2">
+ <span className="h-1.5 flex-1 overflow-hidden rounded-full bg-muted">
+ <span className={cn("block h-full rounded-full transition-[width]", q.tone)} style={{ width: `${q.pct}%` }} />
+ </span>
+ <span className="text-[12px] font-medium tabular-nums">
+ {q.label} · {items.length}/{MOODBOARD_LIMITS.max}
+ </span>
+ </div>
+ <Button size="sm" variant="outline" onClick={() => input.current?.click()}>
+ <Upload /> Upload more
+ </Button>
+ </div>
+ )}
+
+ <label className="space-y-1">
+ <span className="text-[12.5px] font-medium">{COPY.nameLabel}</span>
+ <Input value={name} maxLength={MOODBOARD_LIMITS.nameMax + 20} placeholder={suggestion || COPY.namePlaceholder} onChange={(e) => setName(e.target.value)} />
+ {suggestion && !name && (
+ <button type="button" onClick={() => setName(suggestion)} className="inline-flex items-center gap-1 text-[12px] text-brand-text hover:underline">
+ <Check className="size-3" /> Use “{suggestion}”
+ </button>
+ )}
+ </label>
+
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-[12px] text-muted-foreground">{items.length < MOODBOARD_LIMITS.min ? COPY.tooFew : `${engine === "open" ? "Open source: collages for Qwen-Image-Edit" : "Cloud: a Recraft style"} from the ${Math.min(items.length, MOODBOARD_LIMITS.refs)} most representative images`}</p>
+ <Button onClick={submit} disabled={busy}>
+ {busy && <Loader2 className="animate-spin" />} Create moodboard
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/moodboards/hooks.ts b/src/components/moodboards/hooks.ts
new file mode 100644
index 00000000..7c23b1ac
--- /dev/null
+++ b/src/components/moodboards/hooks.ts
@@ -0,0 +1,53 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useCallback, useMemo } from "react";
+import type { Engine } from "@/lib/catalog/types";
+import type { CuratedMoodboard, Moodboard } from "./logic";
+
+async function json<T>(res: Response): Promise<T> {
+ const body = (await res.json().catch(() => ({}))) as T & { error?: string };
+ if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);
+ return body;
+}
+
+const busy = (m: Moodboard) => m.status !== "complete" && m.status !== "failed";
+
+/** Your moodboards (polled while one builds or trains) and Soul 2.0's curated looks. */
+export function useMoodboards(enabled = true) {
+ return useQuery({
+ queryKey: ["moodboards"],
+ queryFn: async () => json<{ items: Moodboard[]; curated: CuratedMoodboard[] }>(await fetch("/api/moodboards")),
+ enabled,
+ staleTime: 5_000,
+ refetchInterval: (q) => (q.state.data?.items.some((m) => busy(m) || m.lora?.status === "training") ? 2000 : false),
+ });
+}
+
+export function useMoodboardActions() {
+ const qc = useQueryClient();
+ const done = useCallback(() => void qc.invalidateQueries({ queryKey: ["moodboards"] }), [qc]);
+ const post = async <T,>(url: string, body?: unknown, method = "POST") =>
+ json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }));
+ const create = useMutation({
+ mutationFn: (b: { name: string; images: string[]; collages: string[]; engine: Engine }) => post<Moodboard>("/api/moodboards", b),
+ onSuccess: done,
+ });
+ const retry = useMutation({ mutationFn: (b: { id: string; engine?: Engine }) => post<Moodboard>(`/api/moodboards/${b.id}/retry`, { engine: b.engine }), onSuccess: done });
+ const train = useMutation({
+ mutationFn: (id: string) => post<Moodboard>(`/api/moodboards/${id}/train`),
+ onSuccess: () => {
+ done();
+ void qc.invalidateQueries({ queryKey: ["elements"] });
+ },
+ });
+ const rename = useMutation({ mutationFn: (b: { id: string; name: string }) => post<Moodboard>(`/api/moodboards/${b.id}`, { name: b.name }, "PATCH"), onSuccess: done });
+ const remove = useMutation({
+ mutationFn: async (id: string) => {
+ const res = await fetch(`/api/moodboards/${id}`, { method: "DELETE" });
+ if (!res.ok && res.status !== 404) await json(res);
+ },
+ onSuccess: done,
+ });
+ return useMemo(() => ({ create, retry, train, rename, remove }), [create, retry, train, rename, remove]);
+}
diff --git a/src/components/moodboards/images.ts b/src/components/moodboards/images.ts
new file mode 100644
index 00000000..c6858ba1
--- /dev/null
+++ b/src/components/moodboards/images.ts
@@ -0,0 +1,51 @@
+"use client";
+
+import { samplePixels, type RGB } from "@/lib/catalog/palettes";
+import { collageGroups, coverCrop } from "./logic";
+
+/** Load an image (object URL or same-origin /api/files URL) fully decoded. */
+export async function loadImage(src: string): Promise<HTMLImageElement> {
+ const img = new Image();
+ img.decoding = "async";
+ img.src = src;
+ await img.decode();
+ return img;
+}
+
+/** A small pixel sample of an image (for its colour signature). */
+export function pixelsOf(img: HTMLImageElement, size = 64): RGB[] {
+ const w = size;
+ const h = Math.max(1, Math.round((img.naturalHeight / Math.max(1, img.naturalWidth)) * size));
+ const c = document.createElement("canvas");
+ c.width = w;
+ c.height = h;
+ const ctx = c.getContext("2d", { willReadFrequently: true });
+ if (!ctx) return [];
+ ctx.drawImage(img, 0, 0, w, h);
+ return samplePixels(ctx.getImageData(0, 0, w, h).data, 2000);
+}
+
+/** Up to two 2×2 collages (1024 px JPEGs) from the board's images, most representative first. */
+export async function renderCollages(srcs: string[], size = 1024): Promise<Blob[]> {
+ const out: Blob[] = [];
+ for (const group of collageGroups(srcs)) {
+ const c = document.createElement("canvas");
+ c.width = size;
+ c.height = size;
+ const ctx = c.getContext("2d");
+ if (!ctx) break;
+ const cell = size / 2;
+ for (const [i, src] of group.entries()) {
+ try {
+ const img = await loadImage(src);
+ const { sx, sy, sw, sh } = coverCrop(img.naturalWidth, img.naturalHeight, cell, cell);
+ ctx.drawImage(img, sx, sy, sw, sh, (i % 2) * cell, Math.floor(i / 2) * cell, cell, cell);
+ } catch {
+ // A cell that won't load stays blank.
+ }
+ }
+ const blob = await new Promise<Blob | null>((r) => c.toBlob(r, "image/jpeg", 0.9));
+ if (blob) out.push(blob);
+ }
+ return out;
+}
diff --git a/src/components/moodboards/logic.ts b/src/components/moodboards/logic.ts
new file mode 100644
index 00000000..9ad51868
--- /dev/null
+++ b/src/components/moodboards/logic.ts
@@ -0,0 +1,183 @@
+/**
+ * Moodboards, pure logic shared by the page, the composer chip and the server (src/server/moodboards.ts):
+ * Higgsfield's limits and exact copy, the status a board shows while its cover job runs, which
+ * images best represent a board, and the 2×2 collages open-source style models take.
+ */
+import { kmeans, suggestName, type MoodboardPick, type MoodboardStatus, type RGB } from "@/lib/catalog/palettes";
+import type { Engine, Generation } from "@/lib/catalog/types";
+
+export interface Moodboard {
+ id: string;
+ name: string;
+ /** All images, most representative first. */
+ images: string[];
+ /** The 10 most representative (Recraft styles, cloud style references). */
+ refs: string[];
+ /** 1–2 collages of 4 images each (open style-reference models take 1–2 images). */
+ collages: string[];
+ engine: Engine;
+ status: MoodboardStatus;
+ cover: string | null;
+ /** Recraft V4 style id, once a real (not demo) cover job made one. */
+ styleId: string | null;
+ error: string | null;
+ generationId: string | null;
+ /** The style element trained from this board (Z-Image Turbo LoRA). */
+ lora: { elementId: string; handle: string; status: "none" | "training" | "ready" | "failed" } | null;
+ createdAt: number;
+}
+
+export interface CuratedMoodboard {
+ id: string;
+ name: string;
+ category: string;
+ description: string;
+ hue: number;
+}
+
+export const MOODBOARD_LIMITS = { min: 5, max: 80, minPx: 256, nameMax: 100, refs: 10, collages: 2 } as const;
+
+/** Higgsfield's copy, word for word. */
+export const COPY = {
+ title: "CREATE YOUR MOODBOARD",
+ subtitle: "Turn your references into a focused moodboard that defines style, tone, consistent details, and creative direction.",
+ recommended: "20+ photos, one cohesive style, no faces.",
+ avoid: "Faces, mixed styles, blurry or low-quality images.",
+ tooFew: "Upload at least 5 photos to continue.",
+ tooMany: "Maximum images per moodboard is 80",
+ duplicate: "This image is already added",
+ noName: "Please enter a moodboard name",
+ longName: "Name is too long, maximum 100 characters allowed",
+ tooSmall: "Image dimensions too small: minimum size is 256x256px.",
+ notReady: "This moodboard is still training. Try again once it is ready.",
+ nameLabel: "Moodboard name",
+ namePlaceholder: "Enter moodboard name",
+ deleteTitle: (name: string) => `Delete moodboard ${name}?`,
+ deleteBody: "This cannot be undone.",
+ deleteYes: "Yes, delete forever",
+ deleteNo: "No, keep them",
+} as const;
+
+export const STATUS_LABEL: Record<MoodboardStatus, string> = {
+ queued: "In queue",
+ running: "In progress",
+ cover: "Preparing cover",
+ complete: "Complete",
+ failed: "Failed",
+};
+
+export const COVER_PROMPT = (name: string) =>
+ `A moodboard cover for “${name}”: one striking image that sums up this style — its palette, light, texture, grain and mood. No text.`;
+
+/** What stops a board from being saved, in Higgsfield's words, or null. */
+export function moodboardError(b: { name: string; images: string[] }): string | null {
+ if (b.images.length < MOODBOARD_LIMITS.min) return COPY.tooFew;
+ if (b.images.length > MOODBOARD_LIMITS.max) return COPY.tooMany;
+ if (!b.name.trim()) return COPY.noName;
+ if (b.name.trim().length > MOODBOARD_LIMITS.nameMax) return COPY.longName;
+ return null;
+}
+
+/** Why one picked image can't join the board, or null. */
+export function imageProblem(img: { width: number; height: number; key: string }, existing: string[]): string | null {
+ if (existing.includes(img.key)) return COPY.duplicate;
+ if (img.width < MOODBOARD_LIMITS.minPx || img.height < MOODBOARD_LIMITS.minPx) return COPY.tooSmall;
+ return null;
+}
+
+/** The board's status from its cover job: queued → running → preparing the cover (past halfway) → done. */
+export function moodboardStatus(g: Pick<Generation, "status" | "progress" | "error"> | null): { status: MoodboardStatus; error?: string } {
+ if (!g) return { status: "failed", error: "The cover job is gone — retry to make it again" };
+ if (g.status === "queued") return { status: "queued" };
+ if (g.status === "running") return { status: (g.progress ?? 0) >= 0.5 ? "cover" : "running" };
+ if (g.status === "succeeded") return { status: "complete" };
+ return { status: "failed", error: g.error ?? (g.status === "canceled" ? "Canceled" : "The cover job didn't finish") };
+}
+
+// ---------------------------------------------------------------------------
+// Which images represent the board
+
+/** A small colour signature per image: a normalised 3×3×3 RGB histogram (27 numbers summing to 1). */
+export function colorFeature(pixels: RGB[]): number[] {
+ const h = new Array<number>(27).fill(0);
+ for (const [r, g, b] of pixels) h[Math.min(2, Math.floor(r / 86)) * 9 + Math.min(2, Math.floor(g / 86)) * 3 + Math.min(2, Math.floor(b / 86))]++;
+ const n = pixels.length || 1;
+ return h.map((v) => v / n);
+}
+
+const l1 = (a: number[], b: number[]) => a.reduce((s, v, i) => s + Math.abs(v - (b[i] ?? 0)), 0);
+
+/**
+ * Images in order of how well they represent the board (facility location, greedy): first the most
+ * typical image, then each next one that brings the rest closest to a chosen one. So the first 10
+ * cover the board's range instead of ten near-copies. Returns indexes into `features`.
+ */
+export function representativeOrder(features: number[][]): number[] {
+ const n = features.length;
+ if (n <= 1) return features.map((_, i) => i);
+ const d = features.map((a) => features.map((b) => l1(a, b)));
+ const chosen: number[] = [];
+ const best = new Array<number>(n).fill(Infinity);
+ while (chosen.length < n) {
+ let pick = -1;
+ let cost = Infinity;
+ for (let c = 0; c < n; c++) {
+ if (chosen.includes(c)) continue;
+ let total = 0;
+ for (let i = 0; i < n; i++) total += Math.min(best[i], d[c][i]);
+ // Ties: keep the earlier image (the order the user added them).
+ if (total < cost - 1e-12) {
+ cost = total;
+ pick = c;
+ }
+ }
+ chosen.push(pick);
+ for (let i = 0; i < n; i++) best[i] = Math.min(best[i], d[pick][i]);
+ }
+ return chosen;
+}
+
+/** A name to start from, from the board's colours ("Teal Dusk"). */
+export function suggestMoodboardName(pixels: RGB[]): string {
+ const clusters = kmeans(pixels, 5, { seed: 3 });
+ return clusters.length ? suggestName(clusters.map((c) => c.color), clusters[0].color) : "My moodboard";
+}
+
+/** Which images go in each 2×2 collage: groups of 4 from the representative order, at most 2 collages. */
+export function collageGroups<T>(ordered: T[]): T[][] {
+ const out: T[][] = [];
+ for (let i = 0; i < Math.min(ordered.length, 4 * MOODBOARD_LIMITS.collages); i += 4) {
+ const g = ordered.slice(i, i + 4);
+ // A collage needs a full grid: a short last group borrows from the start.
+ while (g.length < 4 && ordered.length >= 4) g.push(ordered[g.length]);
+ if (g.length) out.push(g);
+ }
+ return out;
+}
+
+/** Cover-crop a w×h image into a cell (source rect). */
+export function coverCrop(w: number, h: number, cellW: number, cellH: number): { sx: number; sy: number; sw: number; sh: number } {
+ const scale = Math.max(cellW / w, cellH / h);
+ const sw = cellW / scale;
+ const sh = cellH / scale;
+ return { sx: (w - sw) / 2, sy: (h - sh) / 2, sw, sh };
+}
+
+/** What the composer keeps of a board. */
+export function toPick(m: Moodboard): MoodboardPick {
+ return {
+ id: m.id,
+ kind: "personal",
+ name: m.name,
+ status: m.status,
+ cover: m.cover,
+ refs: m.refs,
+ collages: m.collages,
+ styleId: m.styleId,
+ loraHandle: m.lora?.status === "ready" ? m.lora.handle : null,
+ };
+}
+
+export function curatedPick(c: CuratedMoodboard): MoodboardPick {
+ return { id: c.id, kind: "curated", name: c.name, description: c.description, status: "complete" };
+}
diff --git a/src/components/moodboards/moodboard-panel.tsx b/src/components/moodboards/moodboard-panel.tsx
new file mode 100644
index 00000000..c4501b0a
--- /dev/null
+++ b/src/components/moodboards/moodboard-panel.tsx
@@ -0,0 +1,148 @@
+"use client";
+
+import { Plus, Search } from "lucide-react";
+import Link from "next/link";
+import { useMemo, useState } from "react";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import type { MoodboardPick } from "@/lib/catalog/palettes";
+import { cn } from "@/lib/utils";
+import { BoardCover, CuratedCover, StatusBadge } from "./cards";
+import { CreateMoodboardDialog } from "./create-moodboard";
+import { useMoodboards } from "./hooks";
+import { COPY, curatedPick, toPick } from "./logic";
+
+const CURATED_TABS = ["All presets", "Mood", "Styles", "Camera"];
+
+/** The composer's Moodboard panel: Curated (Soul 2.0's looks) and My moodboards, search, Create moodboard. */
+export function MoodboardPanel({ value, onPick }: { value?: MoodboardPick; onPick: (m?: MoodboardPick) => void }) {
+ const { data, isLoading } = useMoodboards();
+ const [tab, setTab] = useState<"curated" | "mine">(value?.kind === "personal" ? "mine" : "curated");
+ const [cat, setCat] = useState("All presets");
+ const [q, setQ] = useState("");
+ const [creating, setCreating] = useState(false);
+ const needle = q.trim().toLowerCase();
+ const curated = useMemo(
+ () => (data?.curated ?? []).filter((c) => (needle ? `${c.name} ${c.description}`.toLowerCase().includes(needle) : cat === "All presets" || c.category === cat)),
+ [data, needle, cat],
+ );
+ const mine = useMemo(() => (data?.items ?? []).filter((m) => !needle || m.name.toLowerCase().includes(needle)), [data, needle]);
+ const card = "group block w-full min-w-0 rounded-lg text-left outline-none focus-visible:ring-2 focus-visible:ring-ring/50";
+
+ return (
+ <div className="min-w-0 space-y-2.5">
+ <div className="flex items-center gap-2">
+ <div role="tablist" aria-label="Moodboards" className="inline-flex rounded-full bg-muted p-0.5">
+ {(
+ [
+ ["curated", "Curated"],
+ ["mine", "My moodboards"],
+ ] as const
+ ).map(([id, label]) => (
+ <button
+ key={id}
+ role="tab"
+ aria-selected={tab === id}
+ onClick={() => setTab(id)}
+ className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground transition", tab === id && "bg-background text-foreground shadow-soft")}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ <button
+ type="button"
+ onClick={() => setCreating(true)}
+ className="ml-auto inline-flex h-7 items-center gap-1 rounded-full bg-primary px-2.5 text-[12px] font-medium text-primary-foreground transition hover:bg-primary/90"
+ >
+ <Plus className="size-3.5" /> Create moodboard
+ </button>
+ </div>
+ <label className="flex h-8 items-center gap-2 rounded-md border bg-background px-2 focus-within:border-primary">
+ <Search className="size-3.5 text-muted-foreground" />
+ <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search presets..." aria-label="Search presets" className="min-w-0 flex-1 bg-transparent text-[13px] outline-none" />
+ </label>
+
+ {tab === "curated" ? (
+ <>
+ {!needle && (
+ <div className="scrollbar-none flex gap-1 overflow-x-auto">
+ {CURATED_TABS.map((c) => (
+ <button
+ key={c}
+ type="button"
+ aria-pressed={cat === c}
+ onClick={() => setCat(c)}
+ className={cn("h-7 shrink-0 rounded-full px-2.5 text-[12px] font-medium transition-colors", cat === c ? "bg-brand-faint text-brand-text" : "text-muted-foreground hover:bg-accent")}
+ >
+ {c}
+ </button>
+ ))}
+ </div>
+ )}
+ <div className="grid max-h-[46svh] grid-cols-3 gap-1.5 overflow-y-auto sm:max-h-[320px]">
+ {isLoading
+ ? Array.from({ length: 6 }, (_, i) => <Skeleton key={i} className="aspect-[3/4]" />)
+ : curated.map((c) => (
+ <button key={c.id} type="button" title={c.description} aria-pressed={value?.id === c.id} onClick={() => onPick(value?.id === c.id ? undefined : curatedPick(c))} className={card}>
+ <CuratedCover m={c} className={cn("aspect-[3/4] rounded-lg ring-offset-2 ring-offset-background", value?.id === c.id && "ring-2 ring-primary")} />
+ </button>
+ ))}
+ {!isLoading && !curated.length && <p className="col-span-3 py-6 text-center text-[13px] text-muted-foreground">No presets match “{q}”</p>}
+ </div>
+ </>
+ ) : (
+ <div className="grid max-h-[50svh] grid-cols-2 gap-2 overflow-y-auto sm:max-h-[340px]">
+ {isLoading ? (
+ Array.from({ length: 4 }, (_, i) => <Skeleton key={i} className="aspect-square" />)
+ ) : mine.length ? (
+ mine.map((m) => {
+ const ready = m.status === "complete";
+ const btn = (
+ <button
+ type="button"
+ aria-disabled={!ready}
+ aria-pressed={value?.id === m.id}
+ onClick={() => ready && onPick(value?.id === m.id ? undefined : toPick(m))}
+ className={cn(card, !ready && "cursor-not-allowed opacity-70")}
+ >
+ <span className={cn("relative block aspect-square overflow-hidden rounded-lg ring-offset-2 ring-offset-background", value?.id === m.id && "ring-2 ring-primary")}>
+ <BoardCover m={m} className="size-full" />
+ <StatusBadge status={m.status} className="absolute top-1.5 left-1.5" />
+ </span>
+ <span className="mt-1 block truncate px-0.5 text-[12px] font-medium">{m.name}</span>
+ </button>
+ );
+ return ready ? (
+ <div key={m.id}>{btn}</div>
+ ) : (
+ <Tooltip key={m.id}>
+ <TooltipTrigger asChild>{btn}</TooltipTrigger>
+ <TooltipContent>{m.status === "failed" ? (m.error ?? "Failed") : COPY.notReady}</TooltipContent>
+ </Tooltip>
+ );
+ })
+ ) : (
+ <div className="col-span-2 rounded-xl border border-dashed p-4 text-center">
+ <p className="text-[13px] font-medium">Create your moodboard</p>
+ <p className="mt-0.5 text-[12px] text-muted-foreground">{COPY.recommended}</p>
+ </div>
+ )}
+ </div>
+ )}
+ <p className="text-[11.5px] text-muted-foreground">
+ Soul 2.0 takes curated looks natively; other models get the look in words or your board&apos;s images as style references.{" "}
+ <Link href="/moodboards" className="text-brand-text hover:underline">
+ Manage moodboards
+ </Link>
+ </p>
+ <CreateMoodboardDialog
+ open={creating}
+ onOpenChange={setCreating}
+ onCreated={() => {
+ setTab("mine");
+ }}
+ />
+ </div>
+ );
+}
diff --git a/src/components/moodboards/moodboards-view.tsx b/src/components/moodboards/moodboards-view.tsx
new file mode 100644
index 00000000..60aad7a9
--- /dev/null
+++ b/src/components/moodboards/moodboards-view.tsx
@@ -0,0 +1,314 @@
+"use client";
+
+import { GraduationCap, Images, MoreHorizontal, Pencil, Plus, RotateCcw, Search, Trash2, Wand2 } from "lucide-react";
+import Link from "next/link";
+import { useRouter, useSearchParams } from "next/navigation";
+import { Suspense, useEffect, useMemo, useState } from "react";
+import { toast } from "sonner";
+import { PageHeader, PageShell } from "@/components/page-shell";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
+import { Skeleton } from "@/components/ui/skeleton";
+import { EngineSwitch } from "@/components/studio/engine-switch";
+import { useEngine } from "@/lib/api";
+import { cn } from "@/lib/utils";
+import { BoardCover, CuratedCover, StatusBadge } from "./cards";
+import { CreateMoodboardDialog } from "./create-moodboard";
+import { useMoodboardActions, useMoodboards } from "./hooks";
+import { COPY, MOODBOARD_LIMITS, type Moodboard } from "./logic";
+
+const CURATED_TABS = ["All presets", "Mood", "Styles", "Camera"];
+
+/** ?create=1 opens the Create dialog (links from the Image studio and Home). */
+function CreateFromUrl({ onOpen }: { onOpen: () => void }) {
+ const sp = useSearchParams();
+ const create = sp.get("create");
+ useEffect(() => {
+ if (create) onOpen();
+ }, [create, onOpen]);
+ return null;
+}
+
+function BoardCard({ m, onRename, onDelete }: { m: Moodboard; onRename: () => void; onDelete: () => void }) {
+ const { retry, train } = useMoodboardActions();
+ const router = useRouter();
+ const ready = m.status === "complete";
+ return (
+ <div className="group/board min-w-0">
+ <div className="relative">
+ <Link
+ href={ready ? `/image?moodboard=${m.id}` : "#"}
+ aria-disabled={!ready}
+ onClick={(e) => {
+ if (!ready) {
+ e.preventDefault();
+ toast(m.status === "failed" ? (m.error ?? "This moodboard failed") : COPY.notReady);
+ }
+ }}
+ className="block overflow-hidden rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ aria-label={`Use ${m.name} in the Image studio`}
+ >
+ <BoardCover m={m} className="aspect-square transition-transform duration-300 group-hover/board:scale-[1.02]" />
+ </Link>
+ <StatusBadge status={m.status} className="absolute top-2 left-2" />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label={`Options for ${m.name}`}
+ className="absolute top-2 right-2 grid size-7 place-items-center rounded-full bg-background/90 shadow-soft outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ <MoreHorizontal className="size-4" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem asChild disabled={!ready}>
+ <Link href={`/image?moodboard=${m.id}`}>
+ <Wand2 /> Use preset
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => setTimeout(onRename)}>
+ <Pencil /> Rename
+ </DropdownMenuItem>
+ {(m.status === "failed" || m.status === "complete") && (
+ <DropdownMenuItem
+ onSelect={() =>
+ retry.mutate(
+ { id: m.id, engine: m.status === "complete" ? (m.engine === "cloud" ? "open" : "cloud") : undefined },
+ { onSuccess: () => toast("Rebuilding the moodboard"), onError: (e) => toast.error((e as Error).message) },
+ )
+ }
+ >
+ <RotateCcw /> {m.status === "failed" ? "Retry" : `Rebuild for ${m.engine === "cloud" ? "open source" : "cloud"}`}
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem
+ disabled={!ready || m.lora?.status === "training"}
+ onSelect={() =>
+ train.mutate(m.id, {
+ onSuccess: () => toast.success("Training a style LoRA on your GPU"),
+ onError: (e) => toast.error((e as Error).message, { action: /Settings/.test((e as Error).message) ? { label: "Settings", onClick: () => router.push("/settings#training") } : undefined }),
+ })
+ }
+ >
+ <GraduationCap /> {m.lora?.status === "ready" ? "Retrain style LoRA" : "Train a style LoRA"}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onSelect={() => setTimeout(onDelete)}>
+ <Trash2 /> Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ <div className="mt-2 flex items-baseline justify-between gap-2 px-0.5">
+ <p className="min-w-0 truncate text-[13.5px] font-medium">{m.name}</p>
+ <p className="shrink-0 text-[12px] text-muted-foreground tabular-nums">{m.images.length} images</p>
+ </div>
+ <p className="truncate px-0.5 text-[12px] text-muted-foreground">
+ {m.status === "failed"
+ ? (m.error ?? "Failed")
+ : m.lora?.status === "ready"
+ ? `Style LoRA ready · @${m.lora.handle}`
+ : m.lora?.status === "training"
+ ? "Training style LoRA…"
+ : m.styleId
+ ? "Recraft style saved"
+ : m.engine === "open"
+ ? "Open source · collages"
+ : "Cloud · style references"}
+ </p>
+ </div>
+ );
+}
+
+/** /moodboards: Curated looks and your own boards; create, use, rename, retry, train, delete. */
+export function MoodboardsView() {
+ const { data, isLoading } = useMoodboards();
+ const { rename, remove } = useMoodboardActions();
+ const [engine, setEngine] = useEngine();
+ const [tab, setTab] = useState<"mine" | "curated">("mine");
+ const [cat, setCat] = useState("All presets");
+ const [q, setQ] = useState("");
+ const [creating, setCreating] = useState(false);
+ const [renaming, setRenaming] = useState<Moodboard | null>(null);
+ const [newName, setNewName] = useState("");
+ const [deleting, setDeleting] = useState<Moodboard | null>(null);
+ const needle = q.trim().toLowerCase();
+ const mine = useMemo(() => (data?.items ?? []).filter((m) => !needle || m.name.toLowerCase().includes(needle)), [data, needle]);
+ const curated = useMemo(
+ () => (data?.curated ?? []).filter((c) => (needle ? `${c.name} ${c.description}`.toLowerCase().includes(needle) : cat === "All presets" || c.category === cat)),
+ [data, needle, cat],
+ );
+
+ return (
+ <PageShell>
+ <Suspense fallback={null}>
+ <CreateFromUrl onOpen={() => setCreating(true)} />
+ </Suspense>
+ <PageHeader title="Moodboards" description="Define your style: turn 5–80 reference images into a look you can reuse in the Image studio — or start from a curated one.">
+ <div className="flex items-center gap-2">
+ <EngineSwitch value={engine} onChange={setEngine} />
+ <Button onClick={() => setCreating(true)}>
+ <Plus /> Create moodboard
+ </Button>
+ </div>
+ </PageHeader>
+
+ <div className="mb-5 flex flex-wrap items-center gap-3">
+ <div role="tablist" aria-label="Moodboards" className="inline-flex rounded-full bg-muted p-0.5">
+ {(
+ [
+ ["mine", `My moodboards${data ? ` · ${data.items.length}` : ""}`],
+ ["curated", "Curated"],
+ ] as const
+ ).map(([id, label]) => (
+ <button
+ key={id}
+ role="tab"
+ aria-selected={tab === id}
+ onClick={() => setTab(id)}
+ className={cn("h-8 rounded-full px-3.5 text-[13px] font-medium text-muted-foreground transition", tab === id && "bg-background text-foreground shadow-soft")}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ <label className="flex h-9 min-w-0 flex-1 items-center gap-2 rounded-full border bg-background px-3 focus-within:border-primary sm:max-w-xs">
+ <Search className="size-4 text-muted-foreground" />
+ <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search presets..." aria-label="Search moodboards" className="min-w-0 flex-1 bg-transparent text-[13px] outline-none" />
+ </label>
+ </div>
+
+ {tab === "mine" ? (
+ isLoading ? (
+ <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
+ {Array.from({ length: 4 }, (_, i) => (
+ <Skeleton key={i} className="aspect-square rounded-xl" />
+ ))}
+ </div>
+ ) : mine.length ? (
+ <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
+ {mine.map((m) => (
+ <BoardCard
+ key={m.id}
+ m={m}
+ onRename={() => {
+ setRenaming(m);
+ setNewName(m.name);
+ }}
+ onDelete={() => setDeleting(m)}
+ />
+ ))}
+ </div>
+ ) : needle ? (
+ <p className="py-16 text-center text-[14px] text-muted-foreground">No moodboards match “{q}”</p>
+ ) : (
+ <div className="mx-auto flex max-w-xl flex-col items-center rounded-2xl border border-dashed px-6 py-12 text-center">
+ <span className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">
+ <Images className="size-6" />
+ </span>
+ <h2 className="mt-4 font-heading text-[24px]">Create your moodboard</h2>
+ <p className="mt-1 text-[14px] text-muted-foreground">{COPY.subtitle}</p>
+ <p className="mt-3 text-[12.5px] text-muted-foreground">
+ Recommended: {COPY.recommended} {MOODBOARD_LIMITS.min}–{MOODBOARD_LIMITS.max} images.
+ </p>
+ <Button className="mt-5" onClick={() => setCreating(true)}>
+ <Plus /> Create moodboard
+ </Button>
+ </div>
+ )
+ ) : (
+ <>
+ {!needle && (
+ <div className="scrollbar-none mb-4 flex gap-1.5 overflow-x-auto">
+ {CURATED_TABS.map((c) => (
+ <button
+ key={c}
+ type="button"
+ aria-pressed={cat === c}
+ onClick={() => setCat(c)}
+ className={cn("h-8 shrink-0 rounded-full px-3 text-[13px] font-medium transition-colors", cat === c ? "bg-brand-faint text-brand-text" : "bg-secondary text-secondary-foreground hover:bg-accent")}
+ >
+ {c}
+ </button>
+ ))}
+ </div>
+ )}
+ <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-5">
+ {isLoading
+ ? Array.from({ length: 10 }, (_, i) => <Skeleton key={i} className="aspect-[3/4] rounded-xl" />)
+ : curated.map((c) => (
+ <Link key={c.id} href={`/image?moodboard=curated:${c.id}`} className="group/cur min-w-0 rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring/50">
+ <CuratedCover m={c} className="aspect-[3/4] rounded-xl transition-transform duration-300 group-hover/cur:scale-[1.02]" />
+ <p className="mt-1.5 px-0.5 text-[12px] text-muted-foreground">{c.category}</p>
+ <p className="line-clamp-2 px-0.5 text-[12.5px]">{c.description}</p>
+ </Link>
+ ))}
+ </div>
+ {!isLoading && !curated.length && <p className="py-16 text-center text-[14px] text-muted-foreground">No presets match “{q}”</p>}
+ <p className="mt-6 text-[12.5px] text-muted-foreground">
+ Curated looks are Soul 2.0 presets: Higgsfield Soul 2.0 takes them as its style; other models, including the open-source ones, get each look as a prompt.
+ </p>
+ </>
+ )}
+
+ <CreateMoodboardDialog open={creating} onOpenChange={setCreating} onCreated={() => setTab("mine")} />
+
+ <Dialog open={!!renaming} onOpenChange={(o) => !o && setRenaming(null)}>
+ <DialogContent className="sm:max-w-sm">
+ <DialogHeader>
+ <DialogTitle>Rename moodboard</DialogTitle>
+ </DialogHeader>
+ <Input value={newName} onChange={(e) => setNewName(e.target.value)} aria-label={COPY.nameLabel} autoFocus onFocus={(e) => e.currentTarget.select()} />
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setRenaming(null)}>
+ Cancel
+ </Button>
+ <Button
+ disabled={rename.isPending}
+ onClick={() =>
+ renaming &&
+ rename.mutate(
+ { id: renaming.id, name: newName },
+ { onSuccess: () => (setRenaming(null), toast("Renamed")), onError: (e) => toast.error((e as Error).message) },
+ )
+ }
+ >
+ Save
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <AlertDialog open={!!deleting} onOpenChange={(o) => !o && setDeleting(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{COPY.deleteTitle(deleting?.name ?? "")}</AlertDialogTitle>
+ <AlertDialogDescription>{COPY.deleteBody}</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{COPY.deleteNo}</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => deleting && remove.mutate(deleting.id, { onSuccess: () => toast("Moodboard deleted"), onError: (e) => toast.error((e as Error).message) })}
+ >
+ {COPY.deleteYes}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </PageShell>
+ );
+}
diff --git a/src/components/palettes/color-picker.tsx b/src/components/palettes/color-picker.tsx
new file mode 100644
index 00000000..6fed6f59
--- /dev/null
+++ b/src/components/palettes/color-picker.tsx
@@ -0,0 +1,162 @@
+"use client";
+
+import { Pipette } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { Switch } from "@/components/ui/switch";
+import { hexToRgb, hsvToHex, normalizeHex, rgbToHsv } from "@/lib/catalog/palettes";
+import { cn } from "@/lib/utils";
+
+interface EyeDropperLike {
+ open: () => Promise<{ sRGBHex: string }>;
+}
+
+const eyeDropper = (): (new () => EyeDropperLike) | null =>
+ typeof window !== "undefined" && "EyeDropper" in window ? (window as unknown as { EyeDropper: new () => EyeDropperLike }).EyeDropper : null;
+
+/**
+ * A colour picker: saturation/value field and hue slider (pointer and arrow keys), a hex field that
+ * only hands on valid #RRGGBB values, the EyeDropper where the browser has it, and "Use as background".
+ */
+export function ColorPicker({
+ value,
+ onChange,
+ background,
+ onBackground,
+}: {
+ value: string;
+ onChange: (hex: string) => void;
+ background?: boolean;
+ onBackground?: (on: boolean) => void;
+}) {
+ const [hsv, setHsv] = useState(() => rgbToHsv(hexToRgb(value)));
+ const [text, setText] = useState(value.toUpperCase());
+ const last = useRef(value.toUpperCase());
+ // Follow outside changes (another swatch picked) without fighting our own drags.
+ useEffect(() => {
+ if (value.toUpperCase() === last.current) return;
+ last.current = value.toUpperCase();
+ setHsv(rgbToHsv(hexToRgb(value)));
+ setText(value.toUpperCase());
+ }, [value]);
+ const emit = (h: number, s: number, v: number) => {
+ setHsv([h, s, v]);
+ const hex = hsvToHex(h, s, v);
+ last.current = hex;
+ setText(hex);
+ onChange(hex);
+ };
+ const field = useRef<HTMLDivElement>(null);
+ const drag = (e: React.PointerEvent, el: HTMLElement | null, fn: (x: number, y: number) => void) => {
+ if (!el) return;
+ const move = (ev: PointerEvent | React.PointerEvent) => {
+ const r = el.getBoundingClientRect();
+ fn(Math.max(0, Math.min(1, (ev.clientX - r.left) / r.width)), Math.max(0, Math.min(1, (ev.clientY - r.top) / r.height)));
+ };
+ move(e);
+ const up = () => {
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", up);
+ };
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
+ };
+ const [h, s, v] = hsv;
+ const Dropper = eyeDropper();
+ return (
+ <div className="w-56 space-y-3">
+ <div
+ ref={field}
+ role="slider"
+ tabIndex={0}
+ aria-label="Saturation and brightness"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={Math.round(s * 100)}
+ aria-valuetext={`saturation ${Math.round(s * 100)}%, brightness ${Math.round(v * 100)}%`}
+ onPointerDown={(e) => drag(e, field.current, (x, y) => emit(h, x, 1 - y))}
+ onKeyDown={(e) => {
+ const step = e.shiftKey ? 0.1 : 0.02;
+ if (e.key === "ArrowRight") emit(h, Math.min(1, s + step), v);
+ else if (e.key === "ArrowLeft") emit(h, Math.max(0, s - step), v);
+ else if (e.key === "ArrowUp") emit(h, s, Math.min(1, v + step));
+ else if (e.key === "ArrowDown") emit(h, s, Math.max(0, v - step));
+ else return;
+ e.preventDefault();
+ }}
+ className="relative h-36 w-full cursor-crosshair touch-none rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ style={{ background: `linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, ${hsvToHex(h, 1, 1)})` }}
+ >
+ <span className="pointer-events-none absolute size-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow" style={{ left: `${s * 100}%`, top: `${(1 - v) * 100}%` }} />
+ </div>
+ <div
+ role="slider"
+ tabIndex={0}
+ aria-label="Hue"
+ aria-valuemin={0}
+ aria-valuemax={360}
+ aria-valuenow={Math.round(h)}
+ onPointerDown={(e) => drag(e, e.currentTarget, (x) => emit(x * 360, s, v))}
+ onKeyDown={(e) => {
+ const step = e.shiftKey ? 15 : 3;
+ if (e.key === "ArrowRight" || e.key === "ArrowUp") emit((h + step) % 360, s, v);
+ else if (e.key === "ArrowLeft" || e.key === "ArrowDown") emit((h - step + 360) % 360, s, v);
+ else return;
+ e.preventDefault();
+ }}
+ className="relative h-3 w-full cursor-pointer touch-none rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ style={{ background: "linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)" }}
+ >
+ <span className="pointer-events-none absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow" style={{ left: `${(h / 360) * 100}%`, background: hsvToHex(h, 1, 1) }} />
+ </div>
+ <div className="flex items-center gap-2">
+ <label className="flex h-8 min-w-0 flex-1 items-center gap-1.5 rounded-md border bg-background px-2 focus-within:border-primary">
+ <span className="sr-only">Hex color code</span>
+ <span className="size-4 shrink-0 rounded-sm ring-1 ring-foreground/10" style={{ background: normalizeHex(text) ?? value }} />
+ <input
+ value={text}
+ spellCheck={false}
+ maxLength={7}
+ onChange={(e) => {
+ const t = e.target.value.toUpperCase();
+ setText(t);
+ const hex = /^#?[0-9A-F]{6}$/.test(t) ? normalizeHex(t) : null;
+ if (hex) {
+ last.current = hex;
+ setHsv(rgbToHsv(hexToRgb(hex)));
+ onChange(hex);
+ }
+ }}
+ onBlur={() => setText(last.current)}
+ aria-invalid={!normalizeHex(text)}
+ className={cn("min-w-0 flex-1 bg-transparent font-mono text-[12.5px] outline-none", !/^#?[0-9A-F]{6}$/.test(text) && "text-destructive")}
+ />
+ </label>
+ <button
+ type="button"
+ disabled={!Dropper}
+ title={Dropper ? "Pick a color from the screen" : "Picking from the screen isn't supported in this browser"}
+ aria-label="Pick a color from the screen"
+ onClick={async () => {
+ if (!Dropper) return;
+ try {
+ const { sRGBHex } = await new Dropper().open();
+ const hex = normalizeHex(sRGBHex);
+ if (hex) emit(...rgbToHsv(hexToRgb(hex)));
+ } catch {
+ // closed with Escape
+ }
+ }}
+ className="grid size-8 shrink-0 place-items-center rounded-md border transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50 disabled:opacity-40"
+ >
+ <Pipette className="size-3.5" />
+ </button>
+ </div>
+ {onBackground && (
+ <label className="flex items-center justify-between gap-2 text-[12.5px]">
+ Use as background
+ <Switch checked={!!background} onCheckedChange={onBackground} size="sm" />
+ </label>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/palettes/color-signature-panel.tsx b/src/components/palettes/color-signature-panel.tsx
new file mode 100644
index 00000000..d8a9f467
--- /dev/null
+++ b/src/components/palettes/color-signature-panel.tsx
@@ -0,0 +1,292 @@
+"use client";
+
+import { ArrowLeft, ImagePlus, Loader2, Palette as PaletteIcon, Upload, X } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Switch } from "@/components/ui/switch";
+import { uploadFile } from "@/lib/api";
+import { MAX_SOURCE_IMAGES, NAME_MAX, suggestName, type Palette, type PalettePick } from "@/lib/catalog/palettes";
+import { cn } from "@/lib/utils";
+import { extractFromFiles } from "./extract";
+import { usePaletteActions, usePalettes } from "./hooks";
+import { PaletteCard, Strip } from "./palette-card";
+import { manualDraft, PaletteEditor, type PaletteDraft } from "./palette-editor";
+
+export const toPalettePick = (p: Palette, lock?: boolean): PalettePick => ({ id: p.id, name: p.name, colors: p.colors, background: p.background, slug: p.slug, thumb: p.thumb, lock });
+
+type View = "list" | "create" | "images" | "manual";
+
+/** Upload & Create: review the photos, extract their colours (in a worker), name the palette, save. */
+function FromImages({ files, setFiles, onSaved }: { files: File[]; setFiles: (f: File[]) => void; onSaved: (p: Palette) => void }) {
+ // The extraction result belongs to the exact list of files it was made from.
+ const [done, setDone] = useState<{ files: File[]; colors: string[]; background: string | null; name: string } | null>(null);
+ const [name, setName] = useState("");
+ const [saving, setSaving] = useState(false);
+ const { create } = usePaletteActions();
+ const urls = useMemo(() => files.map((f) => URL.createObjectURL(f)), [files]);
+ useEffect(() => () => urls.forEach((u) => URL.revokeObjectURL(u)), [urls]);
+ useEffect(() => {
+ if (!files.length) return;
+ let live = true;
+ extractFromFiles(files)
+ .then((r) => live && setDone({ files, ...r }))
+ .catch((e) => {
+ if (!live) return;
+ setDone({ files, colors: [], background: null, name: "" });
+ toast.error((e as Error).message);
+ });
+ return () => {
+ live = false;
+ };
+ }, [files]);
+ const result = done?.files === files ? done : null;
+ const extracting = !result && files.length > 0;
+
+ const save = async () => {
+ if (!result?.colors.length) return;
+ setSaving(true);
+ try {
+ // The first photo becomes the card's picture.
+ const thumb = await uploadFile(files[0]).then((a) => a.url).catch(() => null);
+ const p = await create.mutateAsync({ name: (name || result.name).trim().slice(0, NAME_MAX), colors: result.colors, background: result.background, source: "images", thumb });
+ toast.success("Palette saved");
+ onSaved(p);
+ } catch (e) {
+ toast.error((e as Error).message || "Failed to save palette");
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <div className="space-y-3">
+ <div className="grid grid-cols-4 gap-1.5">
+ {files.map((f, i) => (
+ <div key={`${f.name}-${i}`} className="relative aspect-square overflow-hidden rounded-md bg-muted">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={urls[i]} alt="" className="size-full object-cover" />
+ <button
+ type="button"
+ aria-label={`Remove image ${i + 1}`}
+ onClick={() => setFiles(files.filter((x) => x !== f))}
+ className="absolute top-0.5 right-0.5 grid size-5 place-items-center rounded-full bg-foreground/80 text-background"
+ >
+ <X className="size-3" />
+ </button>
+ </div>
+ ))}
+ </div>
+ <div className="space-y-1.5">
+ <p className="text-[12.5px] font-medium">Colors</p>
+ {extracting || !result ? (
+ <div className="flex h-8 items-center gap-2 rounded-md bg-muted px-2 text-[12px] text-muted-foreground">
+ <Loader2 className="size-3.5 animate-spin" /> Extracting colors from your images…
+ </div>
+ ) : (
+ <Strip colors={result.colors} className="h-8 rounded-md ring-1 ring-foreground/10" />
+ )}
+ </div>
+ <div className="flex items-end gap-2">
+ <label className="min-w-0 flex-1 space-y-1">
+ <span className="text-[12px] text-muted-foreground">Name</span>
+ <Input value={name} maxLength={NAME_MAX} placeholder={result?.name || "Looking for name..."} onChange={(e) => setName(e.target.value)} className="h-8" aria-label="Enter palette name" />
+ </label>
+ <Button size="sm" className="h-8" disabled={!result?.colors.length || extracting || saving} onClick={save}>
+ {saving && <Loader2 className="animate-spin" />} Save
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * The Color signature panel: saved palettes (yours, then Cinema Studio's 50) as cards, Upload &
+ * Create (colours extracted from up to 20 photos) and Pick colors manually.
+ */
+export function ColorSignaturePanel({ value, onPick, engine }: { value?: PalettePick; onPick: (p?: PalettePick) => void; engine: "cloud" | "open" }) {
+ const { items, isLoading } = usePalettes();
+ const { create, remove } = usePaletteActions();
+ const [view, setView] = useState<View>("list");
+ const [files, setFiles] = useState<File[]>([]);
+ const [draft, setDraft] = useState<PaletteDraft>(manualDraft);
+ const [confirmLeave, setConfirmLeave] = useState(false);
+ const [compact, setCompact] = useState(false);
+ const input = useRef<HTMLInputElement>(null);
+ const mine = items?.filter((p) => p.source !== "builtin") ?? [];
+ const builtins = items?.filter((p) => p.source === "builtin") ?? [];
+
+ const back = () => (view === "images" && files.length ? setConfirmLeave(true) : setView(view === "list" ? "list" : view === "create" ? "list" : "create"));
+ const pickFiles = (list: FileList | null) => {
+ const imgs = [...(list ?? [])].filter((f) => /^image\/(jpeg|png|webp)$/.test(f.type));
+ if (!imgs.length) return toast("Pick JPEG, PNG or WebP photos");
+ if (imgs.length > MAX_SOURCE_IMAGES) toast(`Up to ${MAX_SOURCE_IMAGES} photos — using the first ${MAX_SOURCE_IMAGES}`);
+ setFiles(imgs.slice(0, MAX_SOURCE_IMAGES));
+ setView("images");
+ };
+
+ const header = view !== "list" && (
+ <div className="mb-3 flex items-center gap-2">
+ <button type="button" onClick={back} aria-label="Back" className="grid size-7 place-items-center rounded-full hover:bg-accent">
+ <ArrowLeft className="size-4" />
+ </button>
+ <p className="text-[13px] font-medium">{view === "create" ? "Upload photo or create manually to continue" : view === "images" ? "Create from your photos" : "Create manually to continue"}</p>
+ </div>
+ );
+
+ return (
+ <div className="min-w-0">
+ <input ref={input} type="file" accept="image/jpeg,image/png,image/webp" multiple hidden onChange={(e) => (pickFiles(e.target.files), (e.target.value = ""))} />
+ {header}
+ {view === "list" && (
+ <>
+ <div className={cn("mb-3 rounded-xl bg-brand-faint p-3 transition-all", compact && "flex items-center gap-2 p-2")}>
+ {!compact && (
+ <>
+ <p className="text-[14px] font-semibold text-brand-text">Control your colors</p>
+ <p className="mt-0.5 text-[12.5px] text-muted-foreground">Upload a reference image and bring its colors into your own style.</p>
+ </>
+ )}
+ {compact && <p className="min-w-0 flex-1 truncate text-[12px] text-muted-foreground">Upload a reference image to create your color signature.</p>}
+ <Button size="sm" className={cn("h-8", !compact && "mt-2")} onClick={() => setView("create")}>
+ <Upload /> Upload &amp; Create
+ </Button>
+ </div>
+ {engine === "open" && value && (
+ <label className="mb-3 flex items-center justify-between gap-3 rounded-lg border px-3 py-2 text-[12.5px]">
+ <span>
+ Lock the colours after generating
+ <span className="block text-[11.5px] text-muted-foreground">A palette-transfer step recolours each image (open source, CPU)</span>
+ </span>
+ <Switch checked={!!value.lock} onCheckedChange={(lock) => onPick({ ...value, lock })} aria-label="Lock the colours after generating" />
+ </label>
+ )}
+ <div className="max-h-[52svh] space-y-4 overflow-y-auto pr-0.5 sm:max-h-[360px]" onScroll={(e) => setCompact(e.currentTarget.scrollTop > 24)}>
+ <section>
+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Your palettes</p>
+ {isLoading ? (
+ <div className="grid grid-cols-2 gap-2">
+ <Skeleton className="aspect-video" />
+ <Skeleton className="aspect-video" />
+ </div>
+ ) : mine.length ? (
+ <div className="grid grid-cols-2 gap-2">
+ {mine.map((p) => (
+ <PaletteCard
+ key={p.id}
+ palette={p}
+ selected={value?.id === p.id}
+ onSelect={() => onPick(value?.id === p.id ? undefined : toPalettePick(p, value?.lock))}
+ onDelete={() =>
+ remove.mutate(p.id, {
+ onSuccess: () => {
+ if (value?.id === p.id) onPick(undefined);
+ toast("Palette deleted");
+ },
+ onError: (e) => toast.error((e as Error).message),
+ })
+ }
+ />
+ ))}
+ </div>
+ ) : (
+ <div className="rounded-lg border border-dashed p-4 text-center">
+ <p className="text-[13px] font-medium">Ready to create your color signature?</p>
+ <p className="mt-0.5 text-[12px] text-muted-foreground">Saved palettes will appear here. No palettes yet — upload an image to begin.</p>
+ </div>
+ )}
+ </section>
+ <section>
+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Cinema palettes</p>
+ <div className="grid grid-cols-2 gap-2">
+ {builtins.map((p) => (
+ <PaletteCard key={p.id} palette={p} selected={value?.id === p.id} onSelect={() => onPick(value?.id === p.id ? undefined : toPalettePick(p, value?.lock))} />
+ ))}
+ </div>
+ </section>
+ </div>
+ </>
+ )}
+ {view === "create" && (
+ <div className="grid grid-cols-2 gap-2">
+ <button type="button" onClick={() => input.current?.click()} className="flex flex-col items-start gap-2 rounded-xl border p-3 text-left transition-colors hover:bg-accent">
+ <ImagePlus className="size-5 text-brand-text" />
+ <span className="text-[13px] font-medium">Upload from device</span>
+ <span className="text-[11.5px] text-muted-foreground">JPEG, PNG or WebP · up to {MAX_SOURCE_IMAGES} photos, 1 is enough</span>
+ </button>
+ <button type="button" onClick={() => setView("manual")} className="flex flex-col items-start gap-2 rounded-xl border p-3 text-left transition-colors hover:bg-accent">
+ <PaletteIcon className="size-5 text-brand-text" />
+ <span className="text-[13px] font-medium">Pick colors manually</span>
+ <span className="text-[11.5px] text-muted-foreground">Up to 12 colours, a background, random starters</span>
+ </button>
+ </div>
+ )}
+ {view === "images" && (
+ <FromImages
+ files={files}
+ setFiles={(f) => (f.length ? setFiles(f) : (setFiles([]), setView("create")))}
+ onSaved={(p) => {
+ setFiles([]);
+ setView("list");
+ onPick(toPalettePick(p, value?.lock));
+ }}
+ />
+ )}
+ {view === "manual" && (
+ <PaletteEditor
+ value={draft}
+ onChange={setDraft}
+ saving={create.isPending}
+ onSave={() =>
+ create.mutate(
+ { name: (draft.name || "").trim() || suggestNameFor(draft), colors: draft.colors, background: draft.background, source: "manual" },
+ {
+ onSuccess: (p) => {
+ toast.success("Palette saved");
+ setDraft(manualDraft());
+ setView("list");
+ onPick(toPalettePick(p, value?.lock));
+ },
+ onError: (e) => toast.error((e as Error).message || "Failed to save palette"),
+ },
+ )
+ }
+ />
+ )}
+ <AlertDialog open={confirmLeave} onOpenChange={setConfirmLeave}>
+ <AlertDialogContent size="sm">
+ <AlertDialogHeader>
+ <AlertDialogTitle>Are you sure?</AlertDialogTitle>
+ <AlertDialogDescription>Your uploaded photos will be lost.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>No, keep them</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => {
+ setFiles([]);
+ setView("create");
+ }}
+ >
+ Yes, discard
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
+
+const suggestNameFor = (d: PaletteDraft) => suggestName(d.colors, d.background);
diff --git a/src/components/palettes/extract.ts b/src/components/palettes/extract.ts
new file mode 100644
index 00000000..c32bdaea
--- /dev/null
+++ b/src/components/palettes/extract.ts
@@ -0,0 +1,80 @@
+"use client";
+
+import { extractPalette, samplePixels, suggestName, type RGB } from "@/lib/catalog/palettes";
+import type { ExtractRequest, ExtractResult } from "./extract.worker";
+
+/**
+ * Extract a palette from up to 20 images in a Web Worker (k-means, src/lib/catalog/palettes.ts).
+ * Browsers without module workers or OffscreenCanvas get the same maths on the main thread.
+ */
+
+let worker: Worker | null = null;
+let seq = 0;
+const waiting = new Map<number, (r: ExtractResult) => void>();
+
+function getWorker(): Worker | null {
+ if (worker) return worker;
+ if (typeof Worker === "undefined" || typeof OffscreenCanvas === "undefined") return null;
+ try {
+ worker = new Worker(new URL("./extract.worker.ts", import.meta.url), { type: "module" });
+ worker.onmessage = (e: MessageEvent<ExtractResult>) => {
+ waiting.get(e.data.id)?.(e.data);
+ waiting.delete(e.data.id);
+ };
+ worker.onerror = () => {
+ // A worker that can't start: answer everyone waiting, then fall back to the main thread from now on.
+ for (const [id, done] of waiting) done({ id, colors: [], background: null, weights: [], name: "", error: "worker" });
+ waiting.clear();
+ worker?.terminate();
+ worker = null;
+ broken = true;
+ };
+ return worker;
+ } catch {
+ return null;
+ }
+}
+
+let broken = false;
+
+async function onMainThread(files: Blob[], count?: number): Promise<Omit<ExtractResult, "id">> {
+ const sets: RGB[][] = [];
+ for (const f of files) {
+ const url = URL.createObjectURL(f);
+ try {
+ const img = new Image();
+ img.src = url;
+ await img.decode();
+ const w = 160;
+ const h = Math.max(1, Math.round((img.naturalHeight / Math.max(1, img.naturalWidth)) * w));
+ const c = document.createElement("canvas");
+ c.width = w;
+ c.height = h;
+ const ctx = c.getContext("2d");
+ if (!ctx) continue;
+ ctx.drawImage(img, 0, 0, w, h);
+ sets.push(samplePixels(ctx.getImageData(0, 0, w, h).data, 3000));
+ } catch {
+ // skip undecodable files
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+ }
+ if (!sets.length) throw new Error("Couldn't read those images — try JPEG, PNG or WebP");
+ const res = extractPalette(sets, { count });
+ return { ...res, name: suggestName(res.colors, res.background) };
+}
+
+export async function extractFromFiles(files: Blob[], count = 8): Promise<Omit<ExtractResult, "id" | "error">> {
+ const w = broken ? null : getWorker();
+ if (w) {
+ const id = ++seq;
+ const res = await new Promise<ExtractResult>((resolve) => {
+ waiting.set(id, resolve);
+ w.postMessage({ id, files, count } satisfies ExtractRequest);
+ });
+ if (!res.error) return res;
+ if (res.error !== "worker") throw new Error(res.error);
+ }
+ return onMainThread(files, count);
+}
diff --git a/src/components/palettes/extract.worker.ts b/src/components/palettes/extract.worker.ts
new file mode 100644
index 00000000..edfe7411
--- /dev/null
+++ b/src/components/palettes/extract.worker.ts
@@ -0,0 +1,51 @@
+/**
+ * Palette extraction off the main thread: decode each picked image at ~160 px, sample its pixels and
+ * run k-means over all of them (src/lib/catalog/palettes.ts). Nothing leaves the browser.
+ */
+import { extractPalette, samplePixels, suggestName, type RGB } from "@/lib/catalog/palettes";
+
+export interface ExtractRequest {
+ id: number;
+ files: Blob[];
+ count?: number;
+}
+
+export interface ExtractResult {
+ id: number;
+ colors: string[];
+ background: string | null;
+ weights: number[];
+ name: string;
+ error?: string;
+}
+
+async function pixelsOf(file: Blob): Promise<RGB[]> {
+ const bmp = await createImageBitmap(file, { resizeWidth: 160, resizeQuality: "medium" });
+ const canvas = new OffscreenCanvas(bmp.width, bmp.height);
+ const ctx = canvas.getContext("2d");
+ if (!ctx) throw new Error("No 2D canvas in this worker");
+ ctx.drawImage(bmp, 0, 0);
+ bmp.close();
+ return samplePixels(ctx.getImageData(0, 0, canvas.width, canvas.height).data, 3000);
+}
+
+const post = (m: ExtractResult) => (self as unknown as { postMessage: (m: ExtractResult) => void }).postMessage(m);
+
+self.onmessage = async (e: MessageEvent<ExtractRequest>) => {
+ const { id, files, count } = e.data;
+ try {
+ const sets: RGB[][] = [];
+ for (const f of files) {
+ try {
+ sets.push(await pixelsOf(f));
+ } catch {
+ // An image the browser can't decode is skipped; the others still count.
+ }
+ }
+ if (!sets.length) throw new Error("Couldn't read those images — try JPEG, PNG or WebP");
+ const res = extractPalette(sets, { count });
+ post({ id, ...res, name: suggestName(res.colors, res.background) });
+ } catch (err) {
+ post({ id, colors: [], background: null, weights: [], name: "", error: (err as Error).message });
+ }
+};
diff --git a/src/components/palettes/hooks.ts b/src/components/palettes/hooks.ts
new file mode 100644
index 00000000..39d7d883
--- /dev/null
+++ b/src/components/palettes/hooks.ts
@@ -0,0 +1,42 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useCallback, useMemo } from "react";
+import type { Palette, SignatureCaps } from "@/lib/catalog/palettes";
+
+async function json<T>(res: Response): Promise<T> {
+ const body = (await res.json().catch(() => ({}))) as T & { error?: string };
+ if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);
+ return body;
+}
+
+const EMPTY_CAPS: SignatureCaps = { native: {} };
+
+/** Your palettes + the built-ins, and which models take a palette natively. */
+export function usePalettes(enabled = true) {
+ const q = useQuery({
+ queryKey: ["palettes"],
+ queryFn: async () => json<{ items: Palette[]; caps: SignatureCaps }>(await fetch("/api/palettes")),
+ staleTime: 60_000,
+ enabled,
+ });
+ return { ...q, items: q.data?.items, caps: q.data?.caps ?? EMPTY_CAPS };
+}
+
+export function usePaletteActions() {
+ const qc = useQueryClient();
+ const done = useCallback(() => void qc.invalidateQueries({ queryKey: ["palettes"] }), [qc]);
+ const create = useMutation({
+ mutationFn: async (body: { name: string; colors: string[]; background?: string | null; source: "manual" | "images"; thumb?: string | null }) =>
+ json<Palette>(await fetch("/api/palettes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })),
+ onSuccess: done,
+ });
+ const remove = useMutation({
+ mutationFn: async (id: string) => {
+ const res = await fetch(`/api/palettes/${id}`, { method: "DELETE" });
+ if (!res.ok && res.status !== 404) await json(res);
+ },
+ onSuccess: done,
+ });
+ return useMemo(() => ({ create, remove }), [create, remove]);
+}
diff --git a/src/components/palettes/palette-card.tsx b/src/components/palettes/palette-card.tsx
new file mode 100644
index 00000000..79514a9f
--- /dev/null
+++ b/src/components/palettes/palette-card.tsx
@@ -0,0 +1,100 @@
+"use client";
+
+import { Check, Loader2, MoreHorizontal, Trash2 } from "lucide-react";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { cardStrip, type Palette } from "@/lib/catalog/palettes";
+import { cn } from "@/lib/utils";
+
+/** Equal stripes of a palette's colours (background first, as on Higgsfield's cards). */
+export function Strip({ colors, className }: { colors: string[]; className?: string }) {
+ return (
+ <span aria-hidden className={cn("flex overflow-hidden", className)}>
+ {colors.map((c, i) => (
+ <span key={`${c}-${i}`} className="h-full min-w-0 flex-1" style={{ background: c }} />
+ ))}
+ </span>
+ );
+}
+
+/** A small round swatch for chips and pickers: the palette's colours as a conic wheel. */
+export function SwatchDot({ colors, className }: { colors: string[]; className?: string }) {
+ const stops = colors.length ? colors.map((c, i) => `${c} ${(i / colors.length) * 360}deg ${((i + 1) / colors.length) * 360}deg`).join(", ") : "var(--muted) 0deg 360deg";
+ return <span aria-hidden className={cn("inline-block size-4 shrink-0 rounded-full ring-1 ring-foreground/10", className)} style={{ background: `conic-gradient(${stops})` }} />;
+}
+
+/**
+ * A palette card: a 16:9 picture with a 5 px colour strip along the bottom (or pure stripes when
+ * there's no picture), the name under it, a ring and a check when it's selected.
+ */
+export function PaletteCard({
+ palette,
+ selected,
+ onSelect,
+ onDelete,
+ pending,
+}: {
+ palette: Pick<Palette, "id" | "name" | "colors" | "background" | "thumb" | "source">;
+ selected?: boolean;
+ onSelect: () => void;
+ onDelete?: () => void;
+ /** Colours are still being extracted. */
+ pending?: boolean;
+}) {
+ const strip = cardStrip(palette);
+ return (
+ <div className="group/card relative min-w-0">
+ <button
+ type="button"
+ onClick={onSelect}
+ disabled={pending}
+ aria-pressed={selected}
+ title={pending ? "Extracting colors from your images. You can use this palette once it's ready." : `${palette.name}: ${strip.join(" ")}`}
+ className={cn(
+ "block w-full rounded-lg text-left outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
+ selected && "[&>span:first-child]:ring-2 [&>span:first-child]:ring-primary",
+ )}
+ >
+ <span className="relative block aspect-video overflow-hidden rounded-lg bg-muted ring-offset-2 ring-offset-background">
+ {palette.thumb ? (
+ <>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={palette.thumb} alt="" loading="lazy" className="size-full object-cover" />
+ <Strip colors={strip} className="absolute inset-x-0 bottom-0 h-[5px]" />
+ </>
+ ) : (
+ <Strip colors={strip} className="size-full" />
+ )}
+ {pending && (
+ <span className="absolute inset-0 grid place-items-center bg-background/60">
+ <Loader2 className="size-4 animate-spin" />
+ </span>
+ )}
+ {selected && (
+ <span className="absolute top-1.5 right-1.5 grid size-5 place-items-center rounded-full bg-primary text-primary-foreground">
+ <Check className="size-3" />
+ </span>
+ )}
+ </span>
+ <span className="mt-1 block truncate px-0.5 text-[12px] font-medium">{palette.name}</span>
+ </button>
+ {onDelete && palette.source !== "builtin" && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label={`Palette options for ${palette.name}`}
+ className="absolute top-1.5 left-1.5 grid size-6 place-items-center rounded-full bg-background/85 opacity-100 shadow-soft transition outline-none focus-visible:ring-2 focus-visible:ring-ring/50 sm:opacity-0 sm:group-hover/card:opacity-100 sm:focus-visible:opacity-100"
+ >
+ <MoreHorizontal className="size-3.5" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuItem variant="destructive" onSelect={onDelete}>
+ <Trash2 /> Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/palettes/palette-editor.tsx b/src/components/palettes/palette-editor.tsx
new file mode 100644
index 00000000..13775228
--- /dev/null
+++ b/src/components/palettes/palette-editor.tsx
@@ -0,0 +1,143 @@
+"use client";
+
+import { Plus, RefreshCw, X } from "lucide-react";
+import { useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { MANUAL_DEFAULT, MAX_COLORS, MAX_COLORS_RECRAFT, NAME_MAX, paletteError, randomPalettes, suggestName } from "@/lib/catalog/palettes";
+import { cn } from "@/lib/utils";
+import { ColorPicker } from "./color-picker";
+
+export interface PaletteDraft {
+ name: string;
+ colors: string[];
+ background: string | null;
+}
+
+export const manualDraft = (): PaletteDraft => ({ name: "", colors: [...MANUAL_DEFAULT.colors], background: MANUAL_DEFAULT.background });
+
+/**
+ * "Pick colors manually": the current palette as 40 px swatches (click to edit, × to remove, + Add
+ * color, Clear all), a picker per swatch with "Use as background", and four random palettes to start
+ * from. Save is the parent's.
+ */
+export function PaletteEditor({ value, onChange, onSave, saving }: { value: PaletteDraft; onChange: (v: PaletteDraft) => void; onSave: () => void; saving?: boolean }) {
+ const [editing, setEditing] = useState<number | null>(null);
+ const [randoms, setRandoms] = useState(() => randomPalettes());
+ // The background is its own swatch when it isn't one of the colours.
+ const swatches = value.background && !value.colors.includes(value.background) ? [...value.colors, value.background] : value.colors;
+ const set = (patch: Partial<PaletteDraft>) => onChange({ ...value, ...patch });
+ const error = paletteError({ name: value.name || suggestName(value.colors, value.background), colors: value.colors, background: value.background });
+
+ const replace = (i: number, hex: string) => {
+ const old = swatches[i];
+ if (old === value.background && !value.colors.includes(old)) return set({ background: hex });
+ set({ colors: value.colors.map((c, j) => (j === i ? hex : c)), background: value.background === old ? hex : value.background });
+ };
+ const remove = (i: number) => {
+ const c = swatches[i];
+ set({ colors: value.colors.filter((x, j) => !(j === i && x === c)), background: value.background === c ? null : value.background });
+ setEditing(null);
+ };
+
+ return (
+ <div className="space-y-4">
+ <section className="space-y-2">
+ <div className="flex items-center justify-between">
+ <p className="text-[12.5px] font-medium">Current palette</p>
+ <button type="button" onClick={() => onChange({ ...value, colors: [], background: null })} className="text-[12px] text-muted-foreground hover:text-foreground">
+ Clear all
+ </button>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ {swatches.map((c, i) => (
+ <Popover key={`${i}-${c}`} open={editing === i} onOpenChange={(o) => setEditing(o ? i : null)}>
+ <div className="group/sw relative">
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ aria-label={`Edit color ${c}${c === value.background ? " (background)" : ""}`}
+ className="grid size-10 place-items-center rounded-full ring-1 ring-foreground/15 outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ style={{ background: c }}
+ >
+ {c === value.background && <span className="rounded bg-background/85 px-1 text-[9px] font-semibold tracking-wide">BG</span>}
+ </button>
+ </PopoverTrigger>
+ <button
+ type="button"
+ aria-label={`Remove color ${c}`}
+ title="Remove color"
+ onClick={() => remove(i)}
+ className="absolute -top-1 -right-1 grid size-4 place-items-center rounded-full bg-foreground text-background opacity-100 transition sm:opacity-0 sm:group-hover/sw:opacity-100 sm:focus-visible:opacity-100"
+ >
+ <X className="size-2.5" />
+ </button>
+ </div>
+ <PopoverContent className="w-auto p-3" align="start" collisionPadding={12}>
+ <ColorPicker
+ value={c}
+ onChange={(hex) => replace(i, hex)}
+ background={c === value.background}
+ onBackground={(on) => set({ background: on ? c : null })}
+ />
+ </PopoverContent>
+ </Popover>
+ ))}
+ <button
+ type="button"
+ disabled={value.colors.length >= MAX_COLORS}
+ onClick={() => set({ colors: [...value.colors, "#FFFFFF"] })}
+ className="inline-flex h-10 items-center gap-1 rounded-full border border-dashed px-3 text-[12.5px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"
+ >
+ <Plus className="size-3.5" /> Add color
+ </button>
+ </div>
+ <p className="text-[11.5px] text-muted-foreground">
+ {value.colors.length}/{MAX_COLORS} colours · Recraft uses the first {MAX_COLORS_RECRAFT}
+ </p>
+ </section>
+
+ <section className="space-y-2">
+ <div className="flex items-center justify-between">
+ <p className="text-[12.5px] font-medium">Random palettes</p>
+ <button
+ type="button"
+ onClick={() => setRandoms(randomPalettes())}
+ aria-label="Generate random palettes"
+ title="Generate random palettes"
+ className="grid size-7 place-items-center rounded-full text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ >
+ <RefreshCw className="size-3.5" />
+ </button>
+ </div>
+ <div className="space-y-1.5">
+ {randoms.map((p, i) => (
+ <button
+ key={i}
+ type="button"
+ onClick={() => onChange({ ...value, colors: p.slice(0, MAX_COLORS), background: null })}
+ aria-label={`Use random palette ${i + 1}: ${p.slice(0, 6).join(", ")}`}
+ className="flex h-7 w-full overflow-hidden rounded-md ring-1 ring-foreground/10 transition outline-none hover:ring-2 hover:ring-primary/60 focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {p.slice(0, 6).map((c, j) => (
+ <span key={j} className="h-full flex-1" style={{ background: c }} />
+ ))}
+ </button>
+ ))}
+ </div>
+ </section>
+
+ <div className="flex items-end gap-2">
+ <label className="min-w-0 flex-1 space-y-1">
+ <span className="text-[12px] text-muted-foreground">Name</span>
+ <Input value={value.name} maxLength={NAME_MAX} placeholder={suggestName(value.colors, value.background)} onChange={(e) => set({ name: e.target.value })} className="h-8" />
+ </label>
+ <Button size="sm" className={cn("h-8")} disabled={!!error || saving} onClick={onSave} title={error ?? undefined}>
+ Save palette
+ </Button>
+ </div>
+ {error && value.colors.length === 0 && <p className="text-[12px] text-muted-foreground">Add at least one colour</p>}
+ </div>
+ );
+}
diff --git a/src/components/palettes/signature-chips.tsx b/src/components/palettes/signature-chips.tsx
new file mode 100644
index 00000000..aa0db74b
--- /dev/null
+++ b/src/components/palettes/signature-chips.tsx
@@ -0,0 +1,127 @@
+"use client";
+
+import { Images, Palette as PaletteIcon } from "lucide-react";
+import { useSearchParams } from "next/navigation";
+import { Suspense, useEffect, useRef, useState } from "react";
+import { Chip, ClearableChip } from "@/components/studio/chip";
+import { ResponsivePanel } from "@/components/studio/responsive-panel";
+import { CuratedCover } from "@/components/moodboards/cards";
+import { useMoodboards } from "@/components/moodboards/hooks";
+import { curatedPick, toPick } from "@/components/moodboards/logic";
+import { MoodboardPanel } from "@/components/moodboards/moodboard-panel";
+import { cardStrip, type Signature } from "@/lib/catalog/palettes";
+import { hueOf } from "@/lib/catalog/packs";
+import type { Engine } from "@/lib/catalog/types";
+import { ColorSignaturePanel, toPalettePick } from "./color-signature-panel";
+import { usePalettes } from "./hooks";
+import { SwatchDot } from "./palette-card";
+
+/**
+ * Hand-offs into the Image studio: /image?moodboard=<id> (or curated:<id>) and /image?palette=<id>
+ * pick them once, as soon as the lists are known.
+ */
+function UrlSignature({ onChange }: { onChange: (update: (s: Signature | undefined) => Signature) => void }) {
+ const sp = useSearchParams();
+ const mb = sp.get("moodboard");
+ const pal = sp.get("palette");
+ const boards = useMoodboards(!!mb);
+ const palettes = usePalettes(!!pal);
+ const done = useRef({ mb: false, pal: false });
+ useEffect(() => {
+ if (mb && !done.current.mb && boards.data) {
+ done.current.mb = true;
+ const curated = boards.data.curated.find((c) => c.id === mb.replace(/^curated:/, ""));
+ const mine = boards.data.items.find((m) => m.id === mb);
+ const pick = mine ? toPick(mine) : curated ? curatedPick(curated) : undefined;
+ if (pick) onChange((s) => ({ ...s, moodboard: pick }));
+ }
+ }, [mb, boards.data, onChange]);
+ useEffect(() => {
+ if (pal && !done.current.pal && palettes.items) {
+ done.current.pal = true;
+ const p = palettes.items.find((x) => x.id === pal);
+ if (p) onChange((s) => ({ ...s, palette: toPalettePick(p) }));
+ }
+ }, [pal, palettes.items, onChange]);
+ return null;
+}
+
+/**
+ * The Image studio's style signature chips: Color signature (a saved palette) and Moodboard. Each
+ * opens a popover on desktop and a bottom sheet on phones; the choice lives in the composer's draft.
+ */
+export default function SignatureChips({
+ value,
+ onChange,
+ engine,
+}: {
+ value: Signature | undefined;
+ onChange: (update: (s: Signature | undefined) => Signature) => void;
+ engine: Engine;
+}) {
+ const [colorOpen, setColorOpen] = useState(false);
+ const [boardOpen, setBoardOpen] = useState(false);
+ const pal = value?.palette;
+ const mb = value?.moodboard;
+ return (
+ <>
+ <Suspense fallback={null}>
+ <UrlSignature onChange={onChange} />
+ </Suspense>
+ <ClearableChip active={!!pal} onClear={() => onChange((s) => ({ ...s, palette: undefined }))} clearLabel="Clear color signature">
+ <ResponsivePanel
+ open={colorOpen}
+ onOpenChange={setColorOpen}
+ title="Color signature"
+ tooltip="Color signature"
+ className="w-[min(92vw,440px)]"
+ trigger={
+ <Chip icon={pal ? undefined : PaletteIcon} active={!!pal} aria-label={pal ? `Color signature: ${pal.name}` : "Color signature"}>
+ {pal && <SwatchDot colors={cardStrip(pal)} />}
+ <span className="max-w-32 truncate">{pal ? pal.name : "Color"}</span>
+ </Chip>
+ }
+ >
+ <ColorSignaturePanel
+ value={pal}
+ engine={engine}
+ onPick={(p) => {
+ onChange((s) => ({ ...s, palette: p }));
+ // Toggling the lock keeps the panel open; picking a palette closes it.
+ if (!p || p.id !== pal?.id) setColorOpen(false);
+ }}
+ />
+ </ResponsivePanel>
+ </ClearableChip>
+ <ClearableChip active={!!mb} onClear={() => onChange((s) => ({ ...s, moodboard: undefined }))} clearLabel="Clear moodboard">
+ <ResponsivePanel
+ open={boardOpen}
+ onOpenChange={setBoardOpen}
+ title="Moodboard"
+ tooltip="Moodboard"
+ className="w-[min(92vw,460px)]"
+ trigger={
+ <Chip icon={mb ? undefined : Images} active={!!mb} aria-label={mb ? `Moodboard: ${mb.name}` : "Moodboard"}>
+ {mb &&
+ (mb.kind === "curated" ? (
+ <CuratedCover m={{ name: "", hue: hueOf(mb.id) }} className="size-4 rounded-full" />
+ ) : mb.cover ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={mb.cover} alt="" className="size-4 rounded-full object-cover" />
+ ) : null)}
+ <span className="max-w-32 truncate">{mb ? mb.name : "Moodboard"}</span>
+ </Chip>
+ }
+ >
+ <MoodboardPanel
+ value={mb}
+ onPick={(m) => {
+ onChange((s) => ({ ...s, moodboard: m }));
+ setBoardOpen(false);
+ }}
+ />
+ </ResponsivePanel>
+ </ClearableChip>
+ </>
+ );
+}
diff --git a/src/components/palettes/use-signature.ts b/src/components/palettes/use-signature.ts
new file mode 100644
index 00000000..bda5cc29
--- /dev/null
+++ b/src/components/palettes/use-signature.ts
@@ -0,0 +1,35 @@
+"use client";
+
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useCallback } from "react";
+import { applySignature, type Signature, type SignedRequest } from "@/lib/catalog/palettes";
+import type { Generation, GenerationRequest } from "@/lib/catalog/types";
+import { useCatalog } from "@/components/studio/catalog";
+import { usePalettes } from "./hooks";
+
+/**
+ * The composer's hook for the style signature (Color signature + Moodboard chips): `apply` routes a
+ * request for the picked palette and moodboard (pure, src/lib/catalog/palettes.ts) — the composer
+ * plans and prices with it while you type and sends what it returns. `lock` sends a run whose
+ * images are recoloured afterwards (open engine) through POST /api/palettes/lock.
+ */
+export function useSignature(enabled: boolean, signature: Signature | undefined) {
+ const { getModel } = useCatalog();
+ // The palette list carries which models take a palette natively; the chip has usually loaded it already.
+ const { caps } = usePalettes(enabled && !!signature?.palette);
+ const apply = useCallback(
+ (req: GenerationRequest): SignedRequest => (enabled && signature ? applySignature(req, signature, { caps, getModel }) : { request: req, modelId: req.modelId, notes: [] }),
+ [enabled, signature, caps, getModel],
+ );
+ const qc = useQueryClient();
+ const lock = useMutation({
+ mutationFn: async (b: { request: GenerationRequest; colors: string[] }) => {
+ const res = await fetch("/api/palettes/lock", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(b) });
+ const body = (await res.json().catch(() => ({}))) as { items?: Generation[]; error?: string };
+ if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);
+ return body.items ?? [];
+ },
+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["generations"] }),
+ });
+ return { apply, lock };
+}
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index b9e92675..4fec1ec3 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -31,6 +31,7 @@ import { SketchTools } from "./sketch-tools";
import { RECENT_MODELS, useStoredList } from "./stored-list";
import { useStudio, type Draft } from "./studio-context";
import { useEdgeFade } from "./use-edge-fade";
+import { useSignature } from "../palettes/use-signature";
const EMPTY: StudioElement[] = [];
@@ -39,6 +40,11 @@ const PresetChips = dynamic(() => import("./preset-chips"), {
loading: () => <span aria-hidden className="h-8 w-32 shrink-0 animate-pulse rounded-full bg-secondary" />,
});
+/** Color signature + Moodboard chips (studios with `signature`): their own chunk too. */
+const SignatureChips = dynamic(() => import("../palettes/signature-chips"), {
+ loading: () => <span aria-hidden className="h-8 w-40 shrink-0 animate-pulse rounded-full bg-secondary" />,
+});
+
/** Two speakers to start a dialogue with. */
const defaultLines = (m: ModelDef) => {
const v = m.options.voices ?? [];
@@ -188,13 +194,17 @@ export function Composer({ docked }: { docked: boolean }) {
};
}, [bridgeRef, attach.attachFiles]);
+ // A picked palette / moodboard routes the request (and can move it to another model) before anything else.
+ const signature = useSignature(!!config.signature, draft.signature);
const prepare = (d: typeof draft) => {
- const raw = buildRequest(config.feature, d, studioOp, config.promptSuffix, config.multiRef?.kind);
- const mentions = model ? applyMentions(raw, model, elements) : { request: raw, mentioned: [], notes: [] };
- const sketched = model ? applySketch(mentions.request, model) : { request: mentions.request };
- return { mentions, sketched, request: model ? stripMotionPaths(sketched.request, model) : sketched.request };
+ const signed = signature.apply(buildRequest(config.feature, d, studioOp, config.promptSuffix, config.multiRef?.kind));
+ const raw = signed.request;
+ const m = catalog.getModel(raw.modelId) ?? model;
+ const mentions = m ? applyMentions(raw, m, elements) : { request: raw, mentioned: [], notes: [] };
+ const sketched = m ? applySketch(mentions.request, m) : { request: mentions.request };
+ return { mentions, sketched, signed, request: m ? stripMotionPaths(sketched.request, m) : sketched.request };
};
- const { mentions, sketched } = prepare(draft);
+ const { mentions, sketched, signed } = prepare(draft);
const resolvesOnServer = mentions.mentioned.length > 0 || !!draft.slots.mask?.ref || !!draft.slots.sketch?.ref;
// Plan with stand-ins for attachments that are missing or still uploading, so the cost and the
@@ -224,6 +234,7 @@ export function Composer({ docked }: { docked: boolean }) {
planError = (e as Error).message;
}
}
+ if (signed.blocker) planError = signed.blocker;
// Models that take no prompt (try-on, 3D, transcription, upscalers) never ask for one.
const promptMissing =
!config.promptOptional && !opts.promptless && preset?.userPrompt !== "none" && preset?.userPrompt !== "optional" && !draft.prompt.trim() && !draft.params.shots?.some((s) => s.prompt.trim());
@@ -238,7 +249,7 @@ export function Composer({ docked }: { docked: boolean }) {
});
const submit = () => {
- if (blocker || create.isPending) {
+ if (blocker || create.isPending || signature.lock.isPending) {
if (blocker) {
// One blocker toast at a time (pressing Generate again replaces it), gone once a run starts.
toast(blocker.message, { id: "composer-blocker" });
@@ -252,7 +263,10 @@ export function Composer({ docked }: { docked: boolean }) {
setRecent((r) => pushRecent(r, draft.modelId));
// The server resolves @mentions and drawings itself; only pin the operation when there are none.
// No "Queued" toast: the new card (and the "1 generating ↑" pill when it's off-screen) says it.
- create.mutate(buildRequest(config.feature, draft, resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind), {
+ const sent = signature.apply(buildRequest(config.feature, draft, resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind));
+ // Open palette lock: the images are recoloured to the palette by a chained step (POST /api/palettes/lock).
+ if (sent.lock) return signature.lock.mutate({ request: sent.request, colors: sent.lock.colors }, { onError: (e) => toast.error((e as Error).message) });
+ create.mutate(sent.request, {
onError: (e) => toast.error((e as Error).message),
});
};
@@ -356,6 +370,7 @@ export function Composer({ docked }: { docked: boolean }) {
onMix={(patch) => setDraft(patch)}
/>
)}
+ {config.signature && <SignatureChips value={draft.signature} onChange={(update) => setDraft((d) => ({ signature: update(d.signature) }))} engine={engine} />}
{opts.presets && <ProviderPresetChip spec={opts.presets} value={p.extra?.[opts.presets.param] as string | undefined} onChange={(id) => setExtra(opts.presets!.param, id)} />}
{opts.controls && <ControlsChip controls={opts.controls} values={p.extra ?? {}} onChange={setExtra} />}
</>
@@ -363,6 +378,7 @@ export function Composer({ docked }: { docked: boolean }) {
const hasSecondary =
(!!model && (!!opts.voices?.length || !!opts.voiceClone || !!opts.languages || !!opts.presets || !!opts.controls)) ||
!!config.presetPicker ||
+ !!config.signature ||
preset?.type === "motion" ||
preset?.type === "effect";
@@ -629,11 +645,11 @@ export function Composer({ docked }: { docked: boolean }) {
<Button
size="icon"
onClick={submit}
- disabled={create.isPending}
+ disabled={create.isPending || signature.lock.isPending}
aria-label={blocker ? `Generate — ${blocker.message}` : "Generate"}
className={cn("size-10 shrink-0 rounded-full", blocker && "bg-muted text-subtle-foreground hover:bg-muted")}
>
- {create.isPending ? <Loader2 className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}
+ {create.isPending || signature.lock.isPending ? <Loader2 className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}
</Button>
</TooltipTrigger>
<TooltipContent>
@@ -647,6 +663,7 @@ export function Composer({ docked }: { docked: boolean }) {
</Tooltip>
</div>
{sketched.note && <p className="px-2 pt-1 text-[12px] text-muted-foreground">{sketched.note}</p>}
+ {signed.notes.length > 0 && <p className="px-2 pt-1 text-[12px] text-muted-foreground">{signed.notes.join(" · ")}</p>}
{model && op && model.options.endFrame === undefined && draft.slots.endImage?.ref && (
<p className="px-2 pt-1 text-[12px] text-warning">{model.name} ignores the end frame — pick Kling 2.5, Veo 3.1, Seedance or Wan 2.2 to use it.</p>
)}
diff --git a/src/components/studio/model-controls.tsx b/src/components/studio/model-controls.tsx
index 2bdb7c0c..2fec3de8 100644
--- a/src/components/studio/model-controls.tsx
+++ b/src/components/studio/model-controls.tsx
@@ -14,6 +14,41 @@ interface ProviderPreset {
name: string;
preview?: string;
group?: string;
+ /** Soul presets: Higgsfield's picker categories and a one-line description (from the research list). */
+ categories?: string[];
+ description?: string;
+ /** Built-in list: a hue for the drawn preview (no images are hot-linked). */
+ hue?: number;
+}
+
+interface PresetList {
+ items: ProviderPreset[];
+ error?: string;
+ /** Category tabs (All is added in front). */
+ categories?: string[];
+ /** The built-in list stands in for Higgsfield's (no key, or the live list failed). */
+ fallback?: boolean;
+ note?: string;
+}
+
+/** A preset tile without a preview image: a soft gradient in the preset's hue with its initials. */
+function DrawnPreview({ name, hue }: { name: string; hue: number }) {
+ const initials = name
+ .replace(/[^\p{L}\p{N} ]/gu, "")
+ .split(/\s+/)
+ .filter(Boolean)
+ .slice(0, 2)
+ .map((w) => w[0]?.toUpperCase())
+ .join("");
+ return (
+ <span
+ aria-hidden
+ className="grid size-full place-items-center font-heading text-[22px] text-white/90"
+ style={{ background: `linear-gradient(150deg, oklch(0.74 0.12 ${hue}), oklch(0.46 0.15 ${(hue + 50) % 360}))` }}
+ >
+ {initials}
+ </span>
+ );
}
const label = (v: string | number) =>
@@ -36,13 +71,24 @@ export function ProviderPresetChip({
}) {
const [open, setOpen] = useState(false);
const [q, setQ] = useState("");
+ const [tab, setTab] = useState("All");
const list = useQuery({
queryKey: ["provider-presets", spec.source],
- queryFn: async () => (await (await fetch(`/api/providers/higgsfield/presets?source=${spec.source}`)).json()) as { items: ProviderPreset[]; error?: string },
+ queryFn: async () => (await (await fetch(`/api/providers/higgsfield/presets?source=${spec.source}`)).json()) as PresetList,
staleTime: 60 * 60 * 1000,
enabled: open || !!value,
});
- const items = useMemo(() => (list.data?.items ?? []).filter((p) => !q || p.name.toLowerCase().includes(q.toLowerCase())), [list.data, q]);
+ const tabs = useMemo(() => {
+ const cats = list.data?.categories;
+ return cats?.length ? ["All", ...cats.filter((c) => list.data!.items.some((p) => p.categories?.includes(c)))] : [];
+ }, [list.data]);
+ const items = useMemo(
+ () =>
+ (list.data?.items ?? []).filter(
+ (p) => (!q || p.name.toLowerCase().includes(q.toLowerCase()) || p.description?.toLowerCase().includes(q.toLowerCase())) && (q || tab === "All" || p.categories?.includes(tab)),
+ ),
+ [list.data, q, tab],
+ );
const selected = list.data?.items.find((p) => p.id === value);
return (
<ClearableChip active={!!value && !spec.required} onClear={() => onChange(undefined)} clearLabel={`Clear ${spec.label.toLowerCase()}`}>
@@ -60,6 +106,26 @@ export function ProviderPresetChip({
aria-label={`Search ${spec.label.toLowerCase()}s`}
className="mb-2 h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:border-primary"
/>
+ {tabs.length > 0 && !q && (
+ <div role="tablist" aria-label={`${spec.label} categories`} className="scrollbar-none -mx-0.5 mb-2 flex gap-1 overflow-x-auto px-0.5">
+ {tabs.map((t) => (
+ <button
+ key={t}
+ type="button"
+ role="tab"
+ aria-selected={tab === t}
+ onClick={() => setTab(t)}
+ className={cn(
+ "h-7 shrink-0 rounded-full px-2.5 text-[12px] font-medium transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
+ tab === t ? "bg-brand-faint text-brand-text" : "text-muted-foreground hover:bg-accent",
+ )}
+ >
+ {t}
+ </button>
+ ))}
+ </div>
+ )}
+ {list.data?.note && <p className="mb-2 px-0.5 text-[11.5px] text-muted-foreground">{list.data.note}</p>}
{list.isLoading ? (
<div className="grid h-40 place-items-center">
<Loader2 className="size-4 animate-spin text-muted-foreground" />
@@ -89,6 +155,7 @@ export function ProviderPresetChip({
key={p.id}
type="button"
aria-pressed={value === p.id}
+ title={p.description}
onClick={() => {
onChange(p.id, p.name);
setOpen(false);
@@ -96,14 +163,17 @@ export function ProviderPresetChip({
className={cn("group flex flex-col gap-1 rounded-lg p-1 text-left ring-primary transition hover:bg-accent", value === p.id && "ring-2")}
>
<span className="aspect-[3/4] w-full overflow-hidden rounded-md bg-muted">
- {p.preview && (
+ {p.preview ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={p.preview} alt="" loading="lazy" className="size-full object-cover transition-transform duration-300 group-hover:scale-105" />
- )}
+ ) : p.hue !== undefined ? (
+ <DrawnPreview name={p.name} hue={p.hue} />
+ ) : null}
</span>
<span className="truncate px-0.5 text-[12px] font-medium">{p.name}</span>
</button>
))}
+ {!items.length && q && <p className="col-span-3 py-8 text-center text-[13px] text-muted-foreground">No styles match “{q}”</p>}
</div>
)}
</PopoverContent>
diff --git a/src/components/studio/studio-context.tsx b/src/components/studio/studio-context.tsx
index 0d68a816..b087f4a6 100644
--- a/src/components/studio/studio-context.tsx
+++ b/src/components/studio/studio-context.tsx
@@ -3,6 +3,7 @@
import { createContext, useCallback, useContext, useMemo, useState } from "react";
import type { GenParams, InputSlot, MediaKind, Operation, Preset } from "@/lib/catalog/types";
import type { FeedFilter } from "@/lib/api";
+import type { Signature } from "@/lib/catalog/palettes";
import type { SlotValue } from "./media-slot";
export type SlotKey = InputSlot["key"];
@@ -40,6 +41,10 @@ export interface StudioConfig {
promptSuffix?: string;
/** Optional slots of which one is needed (Lipsync: a portrait or a video): Generate names the group. */
anyOf?: SlotKey[][];
+ /** Color signature + Moodboard chips (Image studio): a saved palette and a style, routed per model (src/lib/catalog/palettes.ts). */
+ signature?: boolean;
+ /** Models the studio can be moved to (by the signature chips) beyond its picker list and defaults: kept in its model slice. */
+ extraModels?: string[];
}
export interface Draft {
@@ -54,6 +59,8 @@ export interface Draft {
/** Motions/effects: strength of the preset, and an optional second one mixed in (Mix). */
presetStrength?: number;
mix?: { presetId: string; strength: number };
+ /** The Color signature and Moodboard picked in the composer (studios with `signature`). */
+ signature?: Signature;
}
interface Actions {
diff --git a/src/lib/catalog/cloud-models.generated.ts b/src/lib/catalog/cloud-models.generated.ts
index 547e1516..951bf219 100644
--- a/src/lib/catalog/cloud-models.generated.ts
+++ b/src/lib/catalog/cloud-models.generated.ts
@@ -1965,6 +1965,77 @@ export const CLOUD_MODELS: ModelDef[] = [
"note": "+$0.005 when a new style is made from references"
}
},
+ {
+ "id": "recraft-4-style-saved",
+ "name": "Recraft V4 Styles \u00b7 saved style",
+ "vendor": "Recraft",
+ "family": "recraft",
+ "engine": "cloud",
+ "kind": "image",
+ "tagline": "A new picture in a style saved from your moodboard",
+ "routes": [
+ {
+ "op": "t2i",
+ "provider": "fal",
+ "endpoint": "recraft/v4/style/text-to-image",
+ "map": {
+ "styleId": "style_id",
+ "palette": {
+ "key": "colors",
+ "format": "rgb-object",
+ "background": "background_color"
+ },
+ "aspectRatio": {
+ "key": "image_size",
+ "values": {
+ "1:1": "square_hd",
+ "4:3": "landscape_4_3",
+ "3:4": "portrait_4_3",
+ "16:9": "landscape_16_9",
+ "9:16": "portrait_16_9",
+ "3:2": "landscape_4_3",
+ "2:3": "portrait_4_3",
+ "21:9": "landscape_16_9",
+ "5:4": "landscape_4_3",
+ "4:5": "portrait_4_3"
+ }
+ }
+ }
+ }
+ ],
+ "options": {
+ "controls": [
+ {
+ "param": "style_match",
+ "label": "Style match",
+ "values": [
+ "precise",
+ "flexible"
+ ]
+ }
+ ],
+ "aspectRatios": [
+ "1:1",
+ "4:3",
+ "3:4",
+ "16:9",
+ "9:16",
+ "3:2",
+ "2:3",
+ "21:9",
+ "5:4",
+ "4:5"
+ ]
+ },
+ "defaults": {
+ "aspectRatio": "1:1"
+ },
+ "pricing": {
+ "unit": "image",
+ "usd": 0.035
+ },
+ "hidden": true
+ },
{
"id": "ideogram-3",
"name": "Ideogram 3.0",
diff --git a/src/lib/catalog/higgsfield-presets.generated.ts b/src/lib/catalog/higgsfield-presets.generated.ts
new file mode 100644
index 00000000..6572a151
--- /dev/null
+++ b/src/lib/catalog/higgsfield-presets.generated.ts
@@ -0,0 +1,1537 @@
+// GENERATED by scripts/gen-higgsfield-presets.py from docs/research/higgsfield-image-studios.json — do not edit.
+// Higgsfield's own preset ids (the API's style_id), names and categories; descriptions marked `inferred` are ours.
+
+export type SoulPresetModel = "soul-v1" | "soul-v2";
+
+export interface SoulPreset {
+ id: string;
+ name: string;
+ model: SoulPresetModel;
+ categories: string[];
+ description: string;
+ /** The description is Fuobe's (Higgsfield publishes none for this preset). */
+ inferred: boolean;
+ /** Soul 2.0: one of the curated moodboards in the Moodboard panel. */
+ curated?: boolean;
+}
+
+export interface PackMeta {
+ id: string;
+ higgsfieldId?: string;
+ name: string;
+ count: number;
+ description: string;
+ inferred: boolean;
+ product: "photodump" | "instadump";
+ author?: string;
+}
+
+export interface FashionTemplateMeta {
+ id: string;
+ higgsfieldId?: string;
+ name: string;
+ /** Shots in Higgsfield's preview carousel (Fuobe's photoset makes one photo per shot). */
+ shots: number;
+ description: string;
+ inferred: boolean;
+}
+
+export const SOUL_CATEGORIES: Record<SoulPresetModel, string[]> = {
+ "soul-v1": [
+ "New",
+ "TikTok Core",
+ "Instagram Aesthetics",
+ "Camera Presets",
+ "Beauty",
+ "Mood",
+ "Surreal",
+ "Graphic Art"
+ ],
+ "soul-v2": [
+ "Mood",
+ "Styles",
+ "Camera"
+ ]
+};
+
+/** The default ("General") preset of each model. */
+export const SOUL_DEFAULT: Record<SoulPresetModel, string> = {
+ "soul-v1": "464ea177-8d40-4940-8d9d-b438bab269c7",
+ "soul-v2": "3db34ab5-3439-4317-9e03-08dc30852e69"
+};
+
+export const SOUL_PRESETS: SoulPreset[] = [
+ {
+ "id": "464ea177-8d40-4940-8d9d-b438bab269c7",
+ "name": "General",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Clean, balanced, and natural—your go-to look with true-to-life colors and soft lighting. Effortlessly versatile for any style",
+ "inferred": false
+ },
+ {
+ "id": "1b798b54-03da-446a-93bf-12fcba1050d7",
+ "name": "iPhone",
+ "model": "soul-v1",
+ "categories": [
+ "Instagram Aesthetics",
+ "Camera Presets",
+ "Beauty"
+ ],
+ "description": "Natural light, casual framing, soft HDR glow. Looks real, but a little better",
+ "inferred": false
+ },
+ {
+ "id": "1cb4b936-77bf-4f9a-9039-f3d349a4cdbe",
+ "name": "Realistic",
+ "model": "soul-v1",
+ "categories": [
+ "Instagram Aesthetics"
+ ],
+ "description": "No filters, just flawless clarity. Light, pores, fabric—everything exactly as it is, but better",
+ "inferred": false
+ },
+ {
+ "id": "ca4e6ad3-3e93-4e03-81a0-d1722d2c128b",
+ "name": "DigitalCam",
+ "model": "soul-v1",
+ "categories": [
+ "TikTok Core",
+ "Camera Presets",
+ "Beauty"
+ ],
+ "description": "Harsh flash, timestamp corner, and raw textures. Feels like 2007 captured forever",
+ "inferred": false
+ },
+ {
+ "id": "3f90dc5b-f474-4259-95c4-d29fbd6be645",
+ "name": "Flight mode",
+ "model": "soul-v1",
+ "categories": [
+ "New",
+ "TikTok Core",
+ "Instagram Aesthetics"
+ ],
+ "description": "Airports, terminals — everything designed to feel like you're traveling. Modern architecture, clean lines, and a subtle “main character leaves town” aura.",
+ "inferred": false
+ },
+ {
+ "id": "26241c54-ed78-4ea7-b1bf-d881737c9feb",
+ "name": "Sunset beach",
+ "model": "soul-v1",
+ "categories": [
+ "New",
+ "TikTok Core",
+ "Instagram Aesthetics",
+ "Camera Presets",
+ "Beauty"
+ ],
+ "description": "Golden-hour dreams. The sky melts from purple to peach while you pose like you don’t know the sun’s watching. Glowy skin, backlit outlines, and luxury vacation stillness.",
+ "inferred": false
+ },
+ {
+ "id": "de0118ba-7c27-49f7-9841-38abe2aae8e1",
+ "name": "Mt. Fuji",
+ "model": "soul-v1",
+ "categories": [
+ "New",
+ "Mood",
+ "Surreal"
+ ],
+ "description": "Postcard surrealism. Crystal-blue skies, iconic mountain symmetry, and convenience store drama.",
+ "inferred": false
+ },
+ {
+ "id": "a13917c7-02a4-450f-b007-e72d53151980",
+ "name": "Street view",
+ "model": "soul-v1",
+ "categories": [
+ "New",
+ "TikTok Core",
+ "Mood"
+ ],
+ "description": "Candid street-level shot, as if caught by a passing camera on a city sidewalk",
+ "inferred": true
+ },
+ {
+ "id": "99de6fc5-1177-49b9-b2e9-19e17d95bcaf",
+ "name": "Tokyo Streetstyle",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Layered looks, sharp silhouettes, and fearless color. A street-level runway of innovation and self-expression",
+ "inferred": false
+ },
+ {
+ "id": "f96913e8-2fcf-4358-8545-75dd6c34c518",
+ "name": "Bimbocore",
+ "model": "soul-v1",
+ "categories": [
+ "TikTok Core"
+ ],
+ "description": "Hyperfeminine overload: glossed lips, tiny skirts, and confidence cranked to 100. Plastic fantastic, but make it powerful",
+ "inferred": false
+ },
+ {
+ "id": "07a85fb3-4407-4122-a4eb-42124e57734c",
+ "name": "CCTV",
+ "model": "soul-v1",
+ "categories": [
+ "TikTok Core",
+ "Instagram Aesthetics",
+ "Camera Presets",
+ "Beauty"
+ ],
+ "description": "Grainy surveillance vibe. Raw, unfiltered and highly realistic",
+ "inferred": false
+ },
+ {
+ "id": "524be50a-4388-4ff5-a843-a73d2dd7ef87",
+ "name": "Elevator Mirror",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Full-body mirror selfie in a metallic elevator, phone in hand",
+ "inferred": true
+ },
+ {
+ "id": "6b9e6b4d-325a-4a78-a0fb-a00ddf612380",
+ "name": "Y2K",
+ "model": "soul-v1",
+ "categories": [
+ "TikTok Core"
+ ],
+ "description": "Gloss, glitter, and baby tees. A shiny reboot of early 2000s maximalism—flip phones and all",
+ "inferred": false
+ },
+ {
+ "id": "9de8ed26-c8dd-413c-a5e3-47eec97bc243",
+ "name": "RingSelfie",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Manicured hands, glossy lips, and a flash that catches the sparkle. Casual flex, maximal impact",
+ "inferred": false
+ },
+ {
+ "id": "40ff999c-f576-443c-b5b3-c7d1391a666e",
+ "name": "Spotlight",
+ "model": "soul-v1",
+ "categories": [
+ "Mood"
+ ],
+ "description": "Direct light creating high-contrast drama, paparazzi flash, and instant icon energy",
+ "inferred": false
+ },
+ {
+ "id": "cbefda85-0f76-49bd-82d7-9bcd65be00ca",
+ "name": "Y2K Posters",
+ "model": "soul-v1",
+ "categories": [
+ "TikTok Core"
+ ],
+ "description": "Chrome text, airbrushed skin, and floating objects. Early internet meets teen bedroom wall",
+ "inferred": false
+ },
+ {
+ "id": "4b66c2db-8166-4293-b1aa-5269c9effb07",
+ "name": "Nail Check",
+ "model": "soul-v1",
+ "categories": [
+ "Surreal"
+ ],
+ "description": "Close-up hands showing off nail art, rings, and textures. Precision beauty with attitude",
+ "inferred": false
+ },
+ {
+ "id": "96758335-d1d1-42b7-9c21-5ac38c433485",
+ "name": "Gorpcore",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Function becomes fashion. Technical fabrics, bulky sneakers, and colorblocked gear that looks runway-ready - on a hike or in the city",
+ "inferred": false
+ },
+ {
+ "id": "f5c094c7-4671-4d86-90d2-369c8fdbd7a5",
+ "name": "90s Grain",
+ "model": "soul-v1",
+ "categories": [
+ "Beauty"
+ ],
+ "description": "Warm tones, film texture, and a soft blur—retro mood in every pixel",
+ "inferred": false
+ },
+ {
+ "id": "8dd89de9-1cff-402e-88a8-580c29d91473",
+ "name": "0.5 Selfie",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Front cam, half-body, mirror or not. Unfiltered fits and real-life lighting - effortlessly authentic",
+ "inferred": false
+ },
+ {
+ "id": "71fecd8c-6696-42df-b5eb-f69e4150ca01",
+ "name": "0.5 Outfit",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Shot from the waist down with wide-angle distortion. Casual, candid, and effortlessly cool—your fit, half-framed, full vibe",
+ "inferred": false
+ },
+ {
+ "id": "1fc861ed-5923-41a6-9963-b9f04681dddd",
+ "name": "Medieval",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Chainmail chic, velvet drapes, and candlelit intrigue. Courtly vibes with cinematic weight",
+ "inferred": false
+ },
+ {
+ "id": "0089e17c-d0f0-4d0c-b522-6d25c88a29fc",
+ "name": "Japandi",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Minimalism with warmth. Clean lines, natural light, and a serene sense of balance between form and feeling",
+ "inferred": false
+ },
+ {
+ "id": "bd78cfc6-9b92-4889-9347-f21dbf0a269c",
+ "name": "Coquette core",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Soft focus and lace daydreams. Bows, blush, and a wink - sweetness laced with irony",
+ "inferred": false
+ },
+ {
+ "id": "ba3d7634-447e-455c-98e3-63705d5403b8",
+ "name": "Sand",
+ "model": "soul-v1",
+ "categories": [
+ "Mood"
+ ],
+ "description": "Sculptural silhouettes in windswept dunes. Neutral tones, survivalist edge-high fashion lost in a dust storm",
+ "inferred": false
+ },
+ {
+ "id": "181b3796-008a-403b-b31e-a9b760219f17",
+ "name": "2000s Cam",
+ "model": "soul-v1",
+ "categories": [
+ "Camera Presets",
+ "Beauty"
+ ],
+ "description": "Low-rise everything, rhinestones, and visible thongs. Nostalgia wrapped in early paparazzi glam",
+ "inferred": false
+ },
+ {
+ "id": "ff1ad8a2-94e7-4e70-a12f-e992ca9a0d36",
+ "name": "Quiet luxury",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Understated old-money styling: neutral cashmere, tailored lines, no logos",
+ "inferred": true
+ },
+ {
+ "id": "70fbb531-5ee2-492e-8c53-5dbd6923e8c2",
+ "name": "Giant Accessory",
+ "model": "soul-v1",
+ "categories": [
+ "Surreal"
+ ],
+ "description": "One item exaggerated to surreal scale—bags, bows, or earrings blown up for visual drama",
+ "inferred": false
+ },
+ {
+ "id": "ea6f4dc0-d6dd-4bdf-a8cf-94ed1db91ab2",
+ "name": "HairClips",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Chunky, colorful, or pearl-lined-accessories that turn heads and frame the face with playful precision",
+ "inferred": false
+ },
+ {
+ "id": "673cf0d4-c193-4fa2-8ad3-b4db4611e3ae",
+ "name": "505room",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Moody hotel-room scene in low warm lamp light",
+ "inferred": true
+ },
+ {
+ "id": "7df83cc9-1e13-4bd0-b6ff-1e6a456b9e5a",
+ "name": "Eating Food",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Candid close-up mid-bite, casual food-diary energy",
+ "inferred": true
+ },
+ {
+ "id": "53bdadfa-8eb6-4eaa-8923-ebece4faa91c",
+ "name": "Rainy Day",
+ "model": "soul-v1",
+ "categories": [
+ "Mood"
+ ],
+ "description": "Moody skies, reflections in wet pavement, soft sweaters. A slow, cinematic quiet",
+ "inferred": false
+ },
+ {
+ "id": "0fe8ad66-ff61-411f-9186-b392e140b18c",
+ "name": "Foggy Morning",
+ "model": "soul-v1",
+ "categories": [
+ "Mood"
+ ],
+ "description": "Muted colors, blurred horizons, and quiet light. Dreamlike stillness in early hours",
+ "inferred": false
+ },
+ {
+ "id": "0c636e12-3411-4a65-8d86-67858caf2fa7",
+ "name": "Avant-garde",
+ "model": "soul-v1",
+ "categories": [
+ "Mood"
+ ],
+ "description": "Sculptural beauty, unexpected forms. A look that speaks in bold shapes and silent statements",
+ "inferred": false
+ },
+ {
+ "id": "0367d609-dfa1-4a81-a983-b2b19ecd6480",
+ "name": "Tumblr",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Grainy gifs, soft blur, and blue-toned melancholy—effortlessly curated and emotionally charged",
+ "inferred": false
+ },
+ {
+ "id": "1900111a-4ce8-42a7-9394-7367f0e0385c",
+ "name": "Through The Glass",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Shot behind fogged-up windows or café panes. A quiet moment seen, not staged",
+ "inferred": false
+ },
+ {
+ "id": "83caff04-691c-468c-b4a0-fd6bbabe062b",
+ "name": "Vintage PhotoBooth",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Flash-lit nostalgia in strip form. Grain, glare, and a kiss of chaos",
+ "inferred": false
+ },
+ {
+ "id": "cc4e7248-dcfe-4c93-b264-2ab418a7556b",
+ "name": "Fisheye",
+ "model": "soul-v1",
+ "categories": [
+ "Camera Presets",
+ "Beauty"
+ ],
+ "description": "Exaggerated depth and playful proportions. Face or object up close, background stretched to infinity",
+ "inferred": false
+ },
+ {
+ "id": "372cc37b-9add-4952-a415-53db3998139f",
+ "name": "Geominimal",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Clean lines, geometric overlays. Sharp, modern, minimalist settings",
+ "inferred": false
+ },
+ {
+ "id": "5659c554-9367-4a27-8c66-333c072cbbc2",
+ "name": "7\\",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Distorted realism of Aphex Twin with eerie edits, glitch vibes, cult-classic weirdness",
+ "inferred": false
+ },
+ {
+ "id": "d24c016c-9fb1-47d0-9909-19f57a2830d4",
+ "name": "Selfcare",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Candles, skincare, robes. Glowing peace in muted tones and soft light",
+ "inferred": false
+ },
+ {
+ "id": "b7c621b5-9d3c-46a3-8efb-4cdfbc592271",
+ "name": "Babydoll MakeUp",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Fluttery lashes, pouty lips, and porcelain skin-sweet meets surreal in a hyper-feminine glow-up",
+ "inferred": false
+ },
+ {
+ "id": "7f21e7bd-4df6-4cef-a9a9-9746bceaea1d",
+ "name": "Fairycore",
+ "model": "soul-v1",
+ "categories": [
+ "Mood"
+ ],
+ "description": "Glittery woodland fantasy. Soft pastels, magical sparkles, enchanted innocence",
+ "inferred": false
+ },
+ {
+ "id": "e454956b-caf2-4913-a398-dbc03f1cbedf",
+ "name": "Office beach",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Corporate meets coastal. Suits and sand, spreadsheets with sunglasses - chaotic and sun-bleached",
+ "inferred": false
+ },
+ {
+ "id": "5b6f467e-f509-4afe-a8db-4c07a6f3770d",
+ "name": "Swords Hill",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "High fantasy on a mountain slope. Capes, steel, wind-blown drama—part legend, part editorial",
+ "inferred": false
+ },
+ {
+ "id": "dab472a6-23f4-4cf8-98fe-f3e256f1b549",
+ "name": "Amalfi Summer",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Lemon light, sunkissed skin, linen dresses fluttering on cobblestone-luxury by the sea",
+ "inferred": false
+ },
+ {
+ "id": "b3c8075a-cb4c-42de-b8b3-7099dd2df672",
+ "name": "Creatures",
+ "model": "soul-v1",
+ "categories": [
+ "Surreal"
+ ],
+ "description": "Animalistic details fused with human edge, strange, eerie and beautiful",
+ "inferred": false
+ },
+ {
+ "id": "ad9de607-3941-4540-81ea-ba978ef1550b",
+ "name": "Grunge",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Distressed denim, oversized flannel, and don’t-care hair. Moody, messy, iconic",
+ "inferred": false
+ },
+ {
+ "id": "a2a42ada-75cc-42a9-be12-cb16c1dec2a8",
+ "name": "Glazed doll skin makeup",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Glass-like skin with high-shine finish. Dewy, doll-like, and flawlessly unreal",
+ "inferred": false
+ },
+ {
+ "id": "82edba1e-b093-4484-a25e-9276e0454999",
+ "name": "Invertethereal",
+ "model": "soul-v1",
+ "categories": [
+ "Graphic Art"
+ ],
+ "description": "Negative tones and ghostly hues. Dreamlike, eerie, and light turned inside out",
+ "inferred": false
+ },
+ {
+ "id": "5a72fec7-a12e-43db-8ef3-1d193b4f7ab4",
+ "name": "Indie sleaze",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Flash-lit chaos, smudged eyeliner, and blurry rebellion. Tumblr-era nightlife energy in its rawest, hottest form",
+ "inferred": false
+ },
+ {
+ "id": "2fcf02e2-919a-4642-8b31-d58bde5e6bd9",
+ "name": "Mixed Media",
+ "model": "soul-v1",
+ "categories": [
+ "Graphic Art"
+ ],
+ "description": "Layers of photo, paint, text, and texture. A visual collage with chaotic elegance",
+ "inferred": false
+ },
+ {
+ "id": "7fa63380-64b7-48b1-b684-4c9ef37560a9",
+ "name": "Paper Face",
+ "model": "soul-v1",
+ "categories": [
+ "Graphic Art"
+ ],
+ "description": "A face collaged from torn paper, textures, and cutouts-raw edges meet artistic expression. Mixed media magic with a surreal twist",
+ "inferred": false
+ },
+ {
+ "id": "facaafeb-4ab5-4384-92a1-b4086180e9ac",
+ "name": "2000s Fashion",
+ "model": "soul-v1",
+ "categories": [
+ "Graphic Art"
+ ],
+ "description": "Flashy fits, shiny textures, and Y2K icons—low-rise, high-attitude, totally throwback",
+ "inferred": false
+ },
+ {
+ "id": "811de7ab-7aaf-4a6b-b352-cdea6c34c8f1",
+ "name": "Movie",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Widescreen film-still look with cinematic lighting and grade",
+ "inferred": true
+ },
+ {
+ "id": "d8a35238-ba42-48a0-a76a-186a97734b9d",
+ "name": "Overexposed",
+ "model": "soul-v1",
+ "categories": [
+ "Mood"
+ ],
+ "description": "Washed-out whites, crushed detail, and intense brightness. A raw visual effect that feels accidental, emotional, and unfiltered",
+ "inferred": false
+ },
+ {
+ "id": "12eda704-18e5-4783-aa0f-deba5296cc83",
+ "name": "Long legs",
+ "model": "soul-v1",
+ "categories": [
+ "Graphic Art"
+ ],
+ "description": "Elongated limbs and stretched proportions. Stylized drama with a runway edge",
+ "inferred": false
+ },
+ {
+ "id": "62ba1751-63af-4648-a11c-711ac64e216a",
+ "name": "Night Beach",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Moonlit waves, dark silhouettes, and salt in the air. Intimate and a little unreal",
+ "inferred": false
+ },
+ {
+ "id": "710f9073-f580-48dc-b5c3-9bbc7cbb7f37",
+ "name": "90’s Editorial",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Retro fashion magazine style image with film grain, soft blur, moody colors, and pure nostalgia",
+ "inferred": false
+ },
+ {
+ "id": "7696fd45-6e67-47d7-b800-096ce21cd449",
+ "name": "Sitting on the Street",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Laid-back pose meets city grit. Candid, cool, and consciously unbothered",
+ "inferred": false
+ },
+ {
+ "id": "62355e77-7096-45ae-9bea-e7c5b88c3b70",
+ "name": "Glitch",
+ "model": "soul-v1",
+ "categories": [
+ "Graphic Art"
+ ],
+ "description": "Pixel drag, color distortion, and digital noise. Beautiful errors in motion",
+ "inferred": false
+ },
+ {
+ "id": "86fc814e-856a-4af0-98b0-d4da75d0030b",
+ "name": "FashionShow",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Backstage flashes, bold looks, and runway energy—where chaos meets couture",
+ "inferred": false
+ },
+ {
+ "id": "b9e2d7dc-78e6-4f7d-95dd-b62690e7b200",
+ "name": "Artwork",
+ "model": "soul-v1",
+ "categories": [
+ "Graphic Art"
+ ],
+ "description": "Framed moments with painterly depth. A still life of emotion, texture, and light",
+ "inferred": false
+ },
+ {
+ "id": "0b4dac9a-f73a-4e5b-a5a7-1a40ee40d6ac",
+ "name": "Graffiti",
+ "model": "soul-v1",
+ "categories": [
+ "Graphic Art"
+ ],
+ "description": "Spray textures, bold lines, and rebellious color. Raw energy in every frame",
+ "inferred": false
+ },
+ {
+ "id": "4c24b43b-1984-407a-a0ae-c514f29b7e66",
+ "name": "Angel Wings",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Soft look with delicate wings giving dreamy and weightless",
+ "inferred": false
+ },
+ {
+ "id": "34c50302-83ff-487d-b3a9-e35e501d80a7",
+ "name": "PixeletedFace",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Retro-glitch vibe with a pixelated face—playful, edgy, straight out of an early-internet dream",
+ "inferred": false
+ },
+ {
+ "id": "255f4045-d68b-42b1-9e4c-f49d3263a9d7",
+ "name": "Grillz Selfie",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Flash-heavy close-up of shiny teeth, with grills, bold attitude, underground luxury",
+ "inferred": false
+ },
+ {
+ "id": "30458874-d9c0-4d5a-b2b7-597e0eee2404",
+ "name": "Shoe Check",
+ "model": "soul-v1",
+ "categories": [
+ "Surreal"
+ ],
+ "description": "A visual trend where the focus is on footwear, often captured from a top-down or ground-level angle",
+ "inferred": false
+ },
+ {
+ "id": "cc099663-9621-422e-8626-c8ee68953a0c",
+ "name": "Bleached Brows",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Barely-there brows, futuristic face. A blank canvas for bold energy and alien glam",
+ "inferred": false
+ },
+ {
+ "id": "b7908955-2868-4e35-87a0-35e50cb92e5d",
+ "name": "Object Makeup",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Collage-style layers. An object below, makeup above, colors duplicated for surreal, editorial face art",
+ "inferred": false
+ },
+ {
+ "id": "294bb3ee-eaef-4d2a-93e3-164268803db4",
+ "name": "360 cam",
+ "model": "soul-v1",
+ "categories": [
+ "Camera Presets",
+ "Beauty"
+ ],
+ "description": "Wrap-around perspective with immersive distortion. Captures everything-warped, wide, and wonderfully weird",
+ "inferred": false
+ },
+ {
+ "id": "a5f63c3b-70eb-4979-af5e-98c7ee1e18e8",
+ "name": "Giant People",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Surreal scale play: the subject towers over a miniature world",
+ "inferred": true
+ },
+ {
+ "id": "5ad23bca-4a4b-4316-8c59-b80d7709d8ee",
+ "name": "Help It's Too Big",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Comedic oversized prop or garment dwarfing the subject",
+ "inferred": true
+ },
+ {
+ "id": "88126a43-86fb-4047-a2d6-c9146d6ca6ce",
+ "name": "Duplicate",
+ "model": "soul-v1",
+ "categories": [
+ "Graphic Art"
+ ],
+ "description": "Echoed figures, mirrored forms, or repeated poses-surreal symmetry that bends perception",
+ "inferred": false
+ },
+ {
+ "id": "6fb3e1f5-d721-4523-ac38-9902f2b2b850",
+ "name": "Library",
+ "model": "soul-v1",
+ "categories": [
+ "New"
+ ],
+ "description": "Soft indoor lighting meets cozy academia. Perfect for quiet power, timeless knits, and capturing the stillness of thought between the shelves.",
+ "inferred": false
+ },
+ {
+ "id": "bab6e4bd-9093-4bb5-a371-01ef6cbd58ad",
+ "name": "Escalator",
+ "model": "soul-v1",
+ "categories": [
+ "New"
+ ],
+ "description": "Gliding style in motion. This preset captures that effortless mall paparazzi look — structured outfits, steel gradients, and motion frozen in frame.",
+ "inferred": false
+ },
+ {
+ "id": "36061eb7-4907-4cba-afb1-47afcf699873",
+ "name": "Gallery",
+ "model": "soul-v1",
+ "categories": [
+ "New"
+ ],
+ "description": "Neutral walls, high taste. This preset frames your subject like a work of art — minimal, polished, and modern.",
+ "inferred": false
+ },
+ {
+ "id": "d3e2b71d-b24b-462e-bd96-12f7a22b5142",
+ "name": "Crossing the street",
+ "model": "soul-v1",
+ "categories": [
+ "New"
+ ],
+ "description": "Boss walk energy. Overhead angles, harsh midday shadows, and that perfect step mid-cross. Looks stolen from a fashion mag.",
+ "inferred": false
+ },
+ {
+ "id": "bc00b419-f8ca-4887-a990-e2760c3cb761",
+ "name": "Sunbathing",
+ "model": "soul-v1",
+ "categories": [
+ "New"
+ ],
+ "description": "Clear turquoise water, woven bags, towel texture, and heat-soaked skin.",
+ "inferred": false
+ },
+ {
+ "id": "d2e8ba04-9935-4dee-8bc4-39ac789746fc",
+ "name": "Subway",
+ "model": "soul-v1",
+ "categories": [
+ "New"
+ ],
+ "description": "Fluorescent-lit subway car or platform, candid commuter vibe",
+ "inferred": true
+ },
+ {
+ "id": "2d47f079-c021-4b8e-b2c0-3b927a80fc31",
+ "name": "birthday mess",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Flash-lit party aftermath with cake, balloons and confetti",
+ "inferred": true
+ },
+ {
+ "id": "fb9cee2b-632f-4fd4-ae4f-4664deecc0f4",
+ "name": "static glow",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Soft TV-static haze and analog light bloom",
+ "inferred": true
+ },
+ {
+ "id": "493bda5b-bb4b-46fe-9343-7d5e414534ef",
+ "name": "Clouded Dream",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Dreamy pastel sky, soft clouds and airy haze",
+ "inferred": true
+ },
+ {
+ "id": "2a1898d0-548f-4433-8503-5721157b93a1",
+ "name": "Double take",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "The same subject appears twice in one frame",
+ "inferred": true
+ },
+ {
+ "id": "3de71b9e-3973-4828-b246-a34c606e25a7",
+ "name": "Red balloon",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Minimal scene with a single red balloon as the accent",
+ "inferred": true
+ },
+ {
+ "id": "ce9a88c2-c962-45e2-abaa-c8979d48f8d5",
+ "name": "tokyo drift",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Neon Tokyo night streets and car culture, motion-blurred lights",
+ "inferred": true
+ },
+ {
+ "id": "c7ea4e7a-c40c-498d-948c-1f6919631f60",
+ "name": "Rhyme & blues",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Moody 90s R&B album-cover look, deep blues and a soft spotlight",
+ "inferred": true
+ },
+ {
+ "id": "90df2935-3ded-477f-8253-1d67dd939cbe",
+ "name": "Bike mafia",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Crew posing with motorbikes, gritty street attitude",
+ "inferred": true
+ },
+ {
+ "id": "923e4fb0-d4ea-480c-876d-ac7cad862b9d",
+ "name": "dmv",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Flat, harsh ID-photo lighting like a driver's-licence portrait",
+ "inferred": true
+ },
+ {
+ "id": "71ac929c-4002-4640-9b65-cb06402844c6",
+ "name": "Sea breeze",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Windswept seaside portrait, linen and salt air",
+ "inferred": true
+ },
+ {
+ "id": "79bfaa63-4e12-4ea2-8ada-7d4406eecece",
+ "name": "It’s french",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Parisian chic: stripes, berets, cafe terraces",
+ "inferred": true
+ },
+ {
+ "id": "d4775423-d214-4862-b061-47baa1978208",
+ "name": "Fish-eye twin",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Fisheye close-up with a mirrored twin",
+ "inferred": true
+ },
+ {
+ "id": "a643a36a-85e6-4e3d-80db-13e4997203cc",
+ "name": "hallway noir",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Dark hallway, hard single-source light, noir shadows",
+ "inferred": true
+ },
+ {
+ "id": "84c23cef-7eda-4f8f-9931-e3e6af8192d9",
+ "name": "burgundy suit",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Tailored burgundy suit editorial on a muted backdrop",
+ "inferred": true
+ },
+ {
+ "id": "5dbb6a20-0541-4f06-8352-a2408d8781dc",
+ "name": "Nicotine glow",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Warm smoky low light, amber haze, late-night mood",
+ "inferred": true
+ },
+ {
+ "id": "91abc4fe-1cf8-4a77-8ade-d36d46699014",
+ "name": "green editorial",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Fashion editorial built around saturated greens",
+ "inferred": true
+ },
+ {
+ "id": "5765d07d-1525-4d4d-ae06-9091e2bdac2d",
+ "name": "afterparty cam",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Direct-flash point-and-shoot snaps from the after-party",
+ "inferred": true
+ },
+ {
+ "id": "53959c8a-4323-4b78-9888-e9f6fb0f6b98",
+ "name": "2049",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Dystopian sci-fi haze in orange and teal",
+ "inferred": true
+ },
+ {
+ "id": "373420f7-489e-4a5d-930e-cc4ecfcc23cc",
+ "name": "Fireproof",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Posing amid flames and sparks, heat-haze drama",
+ "inferred": true
+ },
+ {
+ "id": "1fba888b-9ab0-447f-a6a4-9ce5251ec2a6",
+ "name": "Night rider",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Night ride under streetlights with motion streaks",
+ "inferred": true
+ },
+ {
+ "id": "5e01339d-745e-4bba-96f7-e8ce4af79f17",
+ "name": "chrome exit",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Chrome and metallic surfaces, futuristic styling",
+ "inferred": true
+ },
+ {
+ "id": "f3968a4f-a125-4c16-8673-45ce9874520e",
+ "name": "brick shade",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Streetwear portrait against a brick wall in hard shade",
+ "inferred": true
+ },
+ {
+ "id": "f8dac072-d11f-438a-b283-fd52fe8aa744",
+ "name": "blackout fit",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "All-black monochrome outfit",
+ "inferred": true
+ },
+ {
+ "id": "aed71142-673c-4908-a6a7-326d5252eb06",
+ "name": "cocktail",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Glamorous cocktail-bar scene in warm bar light",
+ "inferred": true
+ },
+ {
+ "id": "3c975998-cb5b-4980-80fc-7977e4c60972",
+ "name": "mount view",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Mountain-top portrait with a panoramic vista",
+ "inferred": true
+ },
+ {
+ "id": "e439bd89-8176-4729-b6a4-a9977120507d",
+ "name": "Sunburnt",
+ "model": "soul-v1",
+ "categories": [],
+ "description": "Sun-baked warm tones, flushed skin, harsh midday light",
+ "inferred": true
+ },
+ {
+ "id": "3db34ab5-3439-4317-9e03-08dc30852e69",
+ "name": "General",
+ "model": "soul-v2",
+ "categories": [],
+ "description": "Soul 2.0's neutral default look",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "fafd3087-0d0f-4fb1-9af6-91b7d304687c",
+ "name": "Warm ambient",
+ "model": "soul-v2",
+ "categories": [
+ "Styles"
+ ],
+ "description": "Soft warm interior ambience with golden practical light",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "7ee16ff3-c0b0-4f5f-a0e1-e7fc46144230",
+ "name": "Y2K studio",
+ "model": "soul-v2",
+ "categories": [
+ "Camera"
+ ],
+ "description": "Glossy early-2000s studio shoot on coloured seamless",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "6dffca48-f9fe-43f2-8589-da58a172fa3e",
+ "name": "Swag era",
+ "model": "soul-v2",
+ "categories": [
+ "Mood"
+ ],
+ "description": "2010s swag streetwear: snapbacks, bling, flash",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "7876c2a5-aa83-4530-ad09-2b368bbb5e95",
+ "name": "Theatrical light",
+ "model": "soul-v2",
+ "categories": [
+ "Styles"
+ ],
+ "description": "Stage-style spotlighting and deep shadows",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "d7e58c26-b74e-4a72-8c78-d061d600c9a5",
+ "name": "Y2K street",
+ "model": "soul-v2",
+ "categories": [
+ "Styles"
+ ],
+ "description": "Early-2000s street fashion snapped outdoors",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "5e87c5bd-86b6-491a-94ab-046891d1e35e",
+ "name": "Flash editorial",
+ "model": "soul-v2",
+ "categories": [
+ "Styles"
+ ],
+ "description": "Direct on-camera flash fashion editorial",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "a7cb654b-eba7-4e9b-af41-8eaa482bf7c9",
+ "name": "Old smartphone",
+ "model": "soul-v2",
+ "categories": [
+ "Camera"
+ ],
+ "description": "Low-res early phone camera: noise, soft focus, blown highlights",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "95151de0-e0e5-4e04-bd45-c58c8a4ac023",
+ "name": "Street photography",
+ "model": "soul-v2",
+ "categories": [
+ "Camera"
+ ],
+ "description": "Candid documentary street photography",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "069f5a5f-8c4b-4591-a3dd-bde488672228",
+ "name": "Retro BW",
+ "model": "soul-v2",
+ "categories": [
+ "Camera"
+ ],
+ "description": "Grainy black-and-white film portrait",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "99716f25-c133-438a-829a-ec53258980b4",
+ "name": "Asian nostalgia",
+ "model": "soul-v2",
+ "categories": [
+ "Mood"
+ ],
+ "description": "Nostalgic East Asian film tones and settings",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "26bb19d1-25cc-4455-9a80-522eb136a4de",
+ "name": "Surreal solarization",
+ "model": "soul-v2",
+ "categories": [
+ "Mood"
+ ],
+ "description": "Solarised, partly inverted tones for a surreal glow",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "e62e75c2-b1bb-433d-9192-f1196faed74e",
+ "name": "Subtle flash",
+ "model": "soul-v2",
+ "categories": [
+ "Styles"
+ ],
+ "description": "Gentle fill flash for natural editorial snaps",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "74abc530-cec8-4c13-88a6-2b3f78bfd0ff",
+ "name": "Digital camera",
+ "model": "soul-v2",
+ "categories": [
+ "Camera"
+ ],
+ "description": "2000s compact digicam look with harsh flash",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "cfd92ced-4801-42c4-b8ca-e096a405ff1a",
+ "name": "Siren",
+ "model": "soul-v2",
+ "categories": [
+ "Mood"
+ ],
+ "description": "Dark alluring siren make-up and moody glamour",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "d6371f60-a70c-4a43-9393-6e3d8206590c",
+ "name": "Mystique city",
+ "model": "soul-v2",
+ "categories": [
+ "Mood"
+ ],
+ "description": "Mysterious night city, haze and neon",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "cd55643f-812c-461d-9837-baa9a88dff2e",
+ "name": "Candy pop",
+ "model": "soul-v2",
+ "categories": [
+ "Styles"
+ ],
+ "description": "Bright candy-coloured pop styling",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "7a42d44e-0dab-4dd1-be49-c83fec827251",
+ "name": "Double exposure",
+ "model": "soul-v2",
+ "categories": [
+ "Mood"
+ ],
+ "description": "Two images blended in-camera",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "330789e8-cb50-410c-a31f-b1ba10188176",
+ "name": "2000s band",
+ "model": "soul-v2",
+ "categories": [
+ "Styles"
+ ],
+ "description": "Early-2000s band promo photo",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "599d96ce-be5b-4071-9ee0-5b3494f6c757",
+ "name": "Frutiger aero",
+ "model": "soul-v2",
+ "categories": [
+ "Styles"
+ ],
+ "description": "Glossy aqua, bubbles and sky-blue 2000s tech optimism",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "8261de31-258b-4a58-997c-b65bbd6d367f",
+ "name": "Drain",
+ "model": "soul-v2",
+ "categories": [
+ "Styles"
+ ],
+ "description": "Washed-out, melancholic emo-rap aesthetic",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "82e55816-3b41-4f01-8500-d36f235e08e6",
+ "name": "Extraterrestrial",
+ "model": "soul-v2",
+ "categories": [],
+ "description": "Otherworldly sci-fi light and alien landscapes",
+ "inferred": true,
+ "curated": false
+ },
+ {
+ "id": "3d5584b2-4d15-48d2-8a09-c1073259f4c6",
+ "name": "Editorial street style",
+ "model": "soul-v2",
+ "categories": [
+ "Styles"
+ ],
+ "description": "Fashion-week street-style snaps",
+ "inferred": true,
+ "curated": true
+ },
+ {
+ "id": "dbe816eb-c651-4361-aee3-9386f8372121",
+ "name": "Nature light",
+ "model": "soul-v2",
+ "categories": [],
+ "description": "Natural outdoor daylight, soft and true to life",
+ "inferred": true,
+ "curated": false
+ },
+ {
+ "id": "184401c9-65d8-4d4b-b2e1-fd6a87a5b60c",
+ "name": "New Indie",
+ "model": "soul-v2",
+ "categories": [],
+ "description": "Modern indie look: film grain, candid framing, soft colour",
+ "inferred": true,
+ "curated": false
+ },
+ {
+ "id": "04022c41-6164-47d9-b33f-cf241f0b5e15",
+ "name": "Underwater",
+ "model": "soul-v2",
+ "categories": [],
+ "description": "Submerged portrait with caustic light",
+ "inferred": true,
+ "curated": false
+ },
+ {
+ "id": "313f3e05-0d79-4d2f-a56a-d9d289321fd8",
+ "name": "80s horror",
+ "model": "soul-v2",
+ "categories": [],
+ "description": "1980s horror lighting: red and blue gels, fog",
+ "inferred": true,
+ "curated": false
+ },
+ {
+ "id": "7ef8747e-c925-4851-b9e9-6400ddb19df9",
+ "name": "Disposable camera",
+ "model": "soul-v2",
+ "categories": [],
+ "description": "Disposable film camera flash snapshots",
+ "inferred": true,
+ "curated": false
+ },
+ {
+ "id": "adbca234-bfff-4c19-835f-f8647655d295",
+ "name": "Neutral pastel film",
+ "model": "soul-v2",
+ "categories": [],
+ "description": "Film stock with neutral pastel tones",
+ "inferred": true,
+ "curated": false
+ },
+ {
+ "id": "dbaabc25-7fee-438c-bd65-ae4d1775d4ab",
+ "name": "Warm vivid film",
+ "model": "soul-v2",
+ "categories": [],
+ "description": "Saturated warm film stock",
+ "inferred": true,
+ "curated": false
+ },
+ {
+ "id": "3ece570b-a9a3-4b86-8c20-8eaa7c58cc4f",
+ "name": "BW film",
+ "model": "soul-v2",
+ "categories": [],
+ "description": "Classic black-and-white film stock",
+ "inferred": true,
+ "curated": false
+ },
+ {
+ "id": "2c109e42-bf29-47a2-ae16-aa6cbbba8b8a",
+ "name": "Warm contrast film",
+ "model": "soul-v2",
+ "categories": [],
+ "description": "Warm, high-contrast film",
+ "inferred": true,
+ "curated": false
+ },
+ {
+ "id": "a15510bf-2439-4964-a2cc-0e35d1b5e70f",
+ "name": "Muted cool film",
+ "model": "soul-v2",
+ "categories": [],
+ "description": "Desaturated cool-toned film",
+ "inferred": true,
+ "curated": false
+ }
+];
+
+export const PHOTODUMP_PACKS: PackMeta[] = [
+ {
+ "id": "sleepy-head",
+ "higgsfieldId": "5bab1c9f-b8f6-4dfa-9b24-d9ad44655f96",
+ "name": "Sleepy Head",
+ "count": 17,
+ "description": "Cosy in-bed / slow-morning set: pyjamas, rumpled sheets, soft window light",
+ "inferred": true,
+ "product": "photodump"
+ },
+ {
+ "id": "zen",
+ "higgsfieldId": "b6fc607f-e56a-4afb-8208-7cd692422173",
+ "name": "Zen",
+ "count": 10,
+ "description": "Calm wellness set: yoga, tea, quiet natural spaces",
+ "inferred": true,
+ "product": "photodump"
+ },
+ {
+ "id": "candid-glow",
+ "higgsfieldId": "09c85832-bc13-4681-88aa-1386d492a369",
+ "name": "Candid Glow",
+ "count": 12,
+ "description": "Sun-lit candid lifestyle snaps with golden glow",
+ "inferred": true,
+ "product": "photodump"
+ },
+ {
+ "id": "office-dresscode",
+ "higgsfieldId": "b0548ae3-df8f-4231-a20f-14e55df25231",
+ "name": "Office dresscode",
+ "count": 11,
+ "description": "Workwear set: office looks, desks, city commute",
+ "inferred": true,
+ "product": "photodump"
+ },
+ {
+ "id": "surreal-self",
+ "higgsfieldId": "d18022e7-8095-4580-9250-cd22fc41164a",
+ "name": "Surreal Self",
+ "count": 12,
+ "description": "Surreal edits of you: scale play, doubles, impossible scenes",
+ "inferred": true,
+ "product": "photodump"
+ },
+ {
+ "id": "surreal-self-ii",
+ "higgsfieldId": "de32178c-a24c-445e-aa05-6e8d3604f99e",
+ "name": "Surreal Self II",
+ "count": 10,
+ "description": "Second surreal set with new impossible scenes",
+ "inferred": true,
+ "product": "photodump"
+ },
+ {
+ "id": "alter-ego",
+ "higgsfieldId": "56674954-ade3-4b3e-837b-eececda86267",
+ "name": "Alter ego",
+ "count": 12,
+ "description": "Dramatic alter-ego personas and costume looks",
+ "inferred": true,
+ "product": "photodump"
+ },
+ {
+ "id": "cool-girl-dump",
+ "higgsfieldId": "417116dd-21e0-4b9c-b215-56dd880200c4",
+ "name": "Cool Girl Dump",
+ "count": 15,
+ "description": "Tailored compositions, settings, and styling for female characters",
+ "inferred": false,
+ "product": "photodump"
+ },
+ {
+ "id": "male-archive",
+ "higgsfieldId": "14d68d47-3946-4a31-83e6-88df9ad62db6",
+ "name": "Male Archive",
+ "count": 15,
+ "description": "Tailored compositions, settings, and styling for male characters",
+ "inferred": false,
+ "product": "photodump"
+ },
+ {
+ "id": "winter-special",
+ "higgsfieldId": "2f6029e9-16f0-474e-9ae3-917b5d2de60d",
+ "name": "Winter special",
+ "count": 9,
+ "description": "Seasonal winter set (snow, knitwear, holiday lights)",
+ "inferred": true,
+ "product": "instadump"
+ },
+ {
+ "id": "aura-farming",
+ "higgsfieldId": "f3c76708-107e-4444-8918-72b25560e415",
+ "name": "Aura farming",
+ "count": 14,
+ "description": "Effortless-cool \"aura farming\" poses and moody vibes",
+ "inferred": true,
+ "product": "instadump",
+ "author": "neonfluke"
+ },
+ {
+ "id": "looksmaxing",
+ "higgsfieldId": "cb271bcc-81cb-482b-ac9f-47547a534779",
+ "name": "Looksmaxing",
+ "count": 15,
+ "description": "Sharp, flattering glow-up portraits",
+ "inferred": true,
+ "product": "instadump",
+ "author": "wispomatic"
+ },
+ {
+ "id": "2000s-nostalgia",
+ "higgsfieldId": "0c7bcb83-64c6-48f9-ad18-4924b7d93868",
+ "name": "2000s nostalgia",
+ "count": 15,
+ "description": "Y2K flash snaps and 2000s styling",
+ "inferred": true,
+ "product": "instadump",
+ "author": "trunxel"
+ },
+ {
+ "id": "editorial-shots",
+ "higgsfieldId": "e32f5a1f-febf-4edf-9fb3-678f1092ecf5",
+ "name": "Editorial shots",
+ "count": 15,
+ "description": "Magazine-style editorial portraits",
+ "inferred": true,
+ "product": "instadump",
+ "author": "lostsignal"
+ }
+];
+
+export const FASHION_TEMPLATES: FashionTemplateMeta[] = [
+ {
+ "id": "ultra-bold",
+ "higgsfieldId": "6dfebdbd-c474-4366-8e53-f3a96ea8d143",
+ "name": "Ultra bold",
+ "shots": 11,
+ "description": "Bold, saturated colour-blocked studio fashion",
+ "inferred": true
+ },
+ {
+ "id": "blue-green-gradient",
+ "higgsfieldId": "cc02bdd1-3701-4095-9c29-302075bdb78f",
+ "name": "Blue-Green Gradient",
+ "shots": 10,
+ "description": "Studio set on a blue-to-green gradient backdrop",
+ "inferred": true
+ },
+ {
+ "id": "street-style-paparazzi",
+ "higgsfieldId": "72e4c773-dafa-475b-b3d2-bd34828e7d1e",
+ "name": "Street style Paparazzi",
+ "shots": 9,
+ "description": "Street-style shots with paparazzi flash energy",
+ "inferred": true
+ },
+ {
+ "id": "view-from-the-top",
+ "higgsfieldId": "5fa94115-b1b9-494b-8e5d-cf1079d93918",
+ "name": "View from the top",
+ "shots": 6,
+ "description": "High-angle / top-down fashion framing",
+ "inferred": true
+ },
+ {
+ "id": "light-blue-studio",
+ "higgsfieldId": "e8375a6b-a192-45da-9492-a3ee867d9689",
+ "name": "Light blue studio",
+ "shots": 10,
+ "description": "Clean pale-blue studio seamless",
+ "inferred": true
+ },
+ {
+ "id": "red-room",
+ "higgsfieldId": "b22b05c2-549f-49d1-85fd-afeb8bed80a0",
+ "name": "Red room",
+ "shots": 9,
+ "description": "Monochrome all-red set",
+ "inferred": true
+ }
+];
diff --git a/src/lib/catalog/packs.ts b/src/lib/catalog/packs.ts
new file mode 100644
index 00000000..ef9fc25f
--- /dev/null
+++ b/src/lib/catalog/packs.ts
@@ -0,0 +1,762 @@
+/**
+ * Prompt packs for the image studios (docs/research/higgsfield-image-studios.md §2, §3, §6, §7):
+ * the Soul preset fallback (and its open-source prompt template), Photodump / Instadump packs,
+ * Fashion Factory templates, Character Sheet prompts, and the pure planning steps that turn them
+ * into generation requests.
+ *
+ * Catalog-free on purpose: the pages import it in the browser. What depends on the catalog or
+ * the install (a Higgsfield key, trained identities, model options) comes in as `PlanCaps`; the
+ * server (src/server/photodump.ts) fills those in and validates every request before creating it.
+ *
+ * Pack names, photo counts and template shot counts come from the generated research file; the
+ * per-photo prompts are Fuobe's (Higgsfield's are opaque style ids). tests/image-studios.test.ts
+ * checks that every pack has exactly as many prompts as Higgsfield has photos.
+ */
+import type { ElementLora } from "./elements";
+import { styleWords } from "./palettes";
+import { FASHION_TEMPLATES, PHOTODUMP_PACKS, SOUL_CATEGORIES, SOUL_PRESETS, type FashionTemplateMeta, type PackMeta, type SoulPreset, type SoulPresetModel } from "./higgsfield-presets.generated";
+import type { Engine, GenerationRequest } from "./types";
+
+// ---------------------------------------------------------------------------
+// Soul presets: the static fallback for the style picker, and the open-source prompt template
+
+export interface PresetItem {
+ id: string;
+ name: string;
+ /** First category (the live list's `group`). */
+ group?: string;
+ categories: string[];
+ description: string;
+ /** Hue for the drawn preview (no Higgsfield images are hot-linked). */
+ hue: number;
+}
+
+/** A stable 0–359 hue from a string (FNV-1a). */
+export function hueOf(s: string): number {
+ let h = 0x811c9dc5;
+ for (let i = 0; i < s.length; i++) {
+ h ^= s.charCodeAt(i);
+ h = Math.imul(h, 0x01000193);
+ }
+ return (h >>> 0) % 360;
+}
+
+const isSoulSource = (s: string): s is SoulPresetModel => s === "soul-v1" || s === "soul-v2";
+
+/**
+ * The preset list for a style picker source when Higgsfield can't be asked (no key, or the live
+ * list failed): Higgsfield's own ids, so `style_id` still works once a key is added. Null for
+ * sources that have no static list (Genjutsu, Marketing Studio).
+ */
+export function presetFallback(source: string): { items: PresetItem[]; categories: string[] } | null {
+ if (!isSoulSource(source)) return null;
+ const items = SOUL_PRESETS.filter((p) => p.model === source).map((p) => ({
+ id: p.id,
+ name: p.name,
+ group: p.categories[0],
+ categories: p.categories,
+ description: p.description,
+ hue: hueOf(p.id),
+ }));
+ return { items, categories: SOUL_CATEGORIES[source] };
+}
+
+/** Category tabs: All first, then the model's categories that have presets. */
+export function presetTabs(items: Pick<PresetItem, "categories">[], categories: string[]): string[] {
+ return ["All", ...categories.filter((c) => items.some((i) => i.categories.includes(c)))];
+}
+
+export const inTab = (item: Pick<PresetItem, "categories">, tab: string) => tab === "All" || item.categories.includes(tab);
+
+export const getSoulPreset = (id: string): SoulPreset | undefined => SOUL_PRESETS.find((p) => p.id === id);
+
+/** Soul 2.0's curated moodboards (the 33 Soul 2.0 presets), in Higgsfield's order. */
+export const CURATED_MOODBOARDS: SoulPreset[] = SOUL_PRESETS.filter((p) => p.model === "soul-v2");
+
+/**
+ * The open route of a Soul preset: its description as a prompt template on Z-Image Turbo
+ * ("{prompt}. In the style of “Retro BW”: grainy black-and-white film portrait.").
+ */
+export function presetPrompt(preset: Pick<SoulPreset, "name" | "description">, userPrompt: string): string {
+ const style = styleWords(preset);
+ const p = userPrompt.trim().replace(/[.\s]+$/, "");
+ return p ? `${p}. ${style}` : `A photo. ${style}`;
+}
+
+// ---------------------------------------------------------------------------
+// Photodump / Instadump packs
+
+const SHOTS: Record<string, string[]> = {
+ "sleepy-head": [
+ "waking up tangled in white linen sheets, morning sun through sheer curtains, shot from above",
+ "sitting up in bed holding a steaming mug with both hands, oversized pyjama shirt",
+ "lying on their stomach reading a paperback on rumpled sheets, bare feet in the air",
+ "hugging a pillow and laughing with eyes half closed, soft backlight",
+ "a sleepy close-up on a pillow, messy hair, one hand under the cheek",
+ "stretching by the bedroom window in pyjamas, warm golden light",
+ "a breakfast tray on the duvet with a croissant and orange juice, sitting cross-legged on the bed",
+ "a slightly blurry mirror selfie in the bedroom with bed hair",
+ "under a fluffy blanket with only the face peeking out, playful look",
+ "sitting on the edge of the bed pulling on fluffy socks",
+ "scrolling a phone in bed at dawn, screen glow on the face, blue morning tones",
+ "lying on the floor beside the bed with a record player and big headphones",
+ "a sleepy smile while brushing teeth in a sunlit bathroom, in pyjamas",
+ "curled up in an armchair by the bed in a knitted blanket with a cat on the lap",
+ "overhead shot sprawled across the bed with arms out, pillows everywhere",
+ "a silk eye mask pushed up on the forehead, sleepy grin, sitting in bed",
+ "making the bed and throwing the duvet in the air, motion blur, bright morning",
+ ],
+ zen: [
+ "seated cross-legged on a yoga mat in a sunlit studio full of plants, eyes closed",
+ "pouring matcha in a minimal wooden tea room, loose linen clothes",
+ "walking barefoot on a misty forest path in the early morning",
+ "a downward-dog stretch on a wooden deck overlooking the sea",
+ "meditating on a smooth rock beside a still lake at sunrise",
+ "reading in a hammock under trees, dappled light, loose linen",
+ "a close-up holding a ceramic tea cup with steam rising, eyes closed",
+ "journaling on a tatami floor beside a low table with a curl of incense",
+ "floating in a still pool shot from above, arms relaxed, soft daylight",
+ "arranging white flowers in a vase on a bright windowsill, calm expression",
+ ],
+ "candid-glow": [
+ "laughing mid-step on a sunny street, golden-hour backlight making the hair glow",
+ "at a café terrace with an iced coffee, sun flare across the lens",
+ "riding a bicycle along a seaside road at sunset, candid side angle",
+ "eating an ice cream cone and squinting into the sun, warm tones",
+ "leaning out of a car window with hair blowing in golden light",
+ "a picnic on a blanket in a park, caught mid-laugh in golden-hour haze",
+ "walking through tall grass at sunset, one hand brushing the grass",
+ "looking back over the shoulder on a rooftop at golden hour",
+ "dancing barefoot on the beach at dusk, slight motion blur, warm glow",
+ "browsing a market stall, sunlight filtering through the awnings",
+ "sitting on a pier with legs dangling over the water, the sun behind",
+ "a candid close-up with sun-kissed skin and light through the leaves",
+ ],
+ "office-dresscode": [
+ "walking into a glass office lobby in a tailored blazer, coffee in hand",
+ "working at a standing desk with a laptop, crisp shirt, city view behind",
+ "presenting at a whiteboard in a meeting room with a confident gesture",
+ "commuting along a city sidewalk in a trench coat with a tote bag, morning light",
+ "an elevator mirror selfie in office wear with an ID badge",
+ "a lunch break on the office building steps with a salad, smart casual",
+ "typing in a minimalist co-working space under a warm desk lamp in the evening",
+ "on a phone call by a floor-to-ceiling window in a suit, skyline at dusk",
+ "pouring coffee in a modern office kitchen, relaxed workwear",
+ "crossing a busy crosswalk with a laptop bag, street-style snap",
+ "sitting on the edge of a desk with arms crossed, editorial office portrait",
+ ],
+ "surreal-self": [
+ "as a giant sitting among city skyscrapers with tiny cars around the feet",
+ "as a tiny figure standing on the rim of a giant teacup on a breakfast table",
+ "floating upside down in a room where the furniture hangs from the ceiling",
+ "two copies of the same person having coffee together at one café table",
+ "walking on clouds holding an umbrella under a pastel sky",
+ "stepping out of a picture frame on a gallery wall",
+ "sitting calmly in a bedroom flooded with clear water up to the shoulders",
+ "surrounded by floating oranges in a blue void, studio light",
+ "sitting on a crescent moon above a sleeping town",
+ "held like a doll in a giant version of their own hand",
+ "a mirror reflection that shows a different season than the room",
+ "lying in a field of flowers that tower above them",
+ ],
+ "surreal-self-ii": [
+ "riding a giant goldfish down a city street",
+ "standing in a desert whose dunes are made of pink sugar",
+ "climbing out of a giant open book with pages swirling around",
+ "sitting inside a soap bubble floating over a lake",
+ "climbing a staircase that leads up into the sky, long coat flowing",
+ "under an umbrella where the rain falls upward, the street dry",
+ "walking a giant cat on a leash through a tiny village",
+ "several copies of themselves climbing a ladder into a cloud",
+ "sitting in an armchair in the middle of a calm ocean",
+ "hair flowing into ribbons of paint across a white studio",
+ ],
+ "alter-ego": [
+ "as a 1920s jazz singer at a vintage microphone in a smoky club",
+ "as a cyberpunk hacker with a neon visor in a rainy alley",
+ "as a medieval knight in polished armour in a misty castle courtyard",
+ "as an astronaut in a white spacesuit, helmet under the arm, on a launch pad",
+ "as a rock star on stage with a guitar, stage lights and smoke",
+ "as a film-noir detective in a trench coat under a streetlamp",
+ "as a Renaissance oil portrait in velvet against a dark background",
+ "as a racing driver in a race suit beside the car in the pit lane",
+ "as a fantasy elf with silver hair in an enchanted forest",
+ "as a 1980s aerobics instructor in a neon leotard in a retro gym",
+ "as a royal in a gilded throne room wearing a crown",
+ "as a wild-west outlaw in a cowboy hat in a dusty desert town",
+ ],
+ "cool-girl-dump": [
+ "a flash mirror selfie in a vintage boutique fitting room, slip dress",
+ "sitting on a Vespa on a Rome street in sunglasses, candid",
+ "a close-up with glossy lips and gold hoops, direct flash at night",
+ "lying on a striped beach towel reading a magazine, shot from above",
+ "flipping through vinyl in a record store in an oversized leather jacket",
+ "walking out of a bakery with a baguette, ballet flats, Paris street",
+ "sitting cross-legged on a hotel bed with room service, in a robe",
+ "in a car's passenger seat with feet on the dashboard, sunset light",
+ "holding a martini at a dim cocktail bar in a black dress, film grain",
+ "on a rooftop at golden hour in a linen set, wind in the hair",
+ "getting ready at a vanity mirror with makeup scattered around",
+ "trying on sunglasses at a flea market, candid street snap",
+ "in a bright pilates studio in a matching set",
+ "sitting on a stone wall by the sea in a white sundress, laughing",
+ "a night-time flash photo on a city street holding a pizza box",
+ ],
+ "male-archive": [
+ "leaning on a vintage car in a white tee and jeans at golden hour",
+ "in a barber's chair getting a fade, warm candid interior",
+ "walking a dog in a park in a knit sweater on a fresh morning",
+ "a gym locker-room mirror selfie after a workout",
+ "on a motorcycle at a gas station at night, leather jacket, neon light",
+ "reading a newspaper at a corner café in an overcoat with an espresso",
+ "on the deck of a sailing boat in a linen shirt, sun and spray",
+ "cooking in a home kitchen with sleeves rolled up, steam rising",
+ "on a basketball court at dusk holding a ball, streetwear",
+ "adjusting cufflinks in a tailored suit, hotel room window light",
+ "hiking a mountain ridge with a backpack, wide vista",
+ "at a record shop counter with headphones around the neck",
+ "in a late-night diner booth with a burger, red neon, film grain",
+ "on a city rooftop in a bomber jacket at blue hour, skyline behind",
+ "a black-and-white portrait with stubble and a slight smirk, hard window light",
+ ],
+ "winter-special": [
+ "catching snowflakes on the tongue in a snowy street, knit beanie",
+ "holding a hot chocolate with marshmallows by a frosty window",
+ "ice skating on an outdoor rink under string lights",
+ "wrapped in a chunky scarf in a snowy forest, breath visible in the cold",
+ "decorating a Christmas tree with warm fairy lights in a cosy sweater",
+ "mid-throw in a snowball fight, laughing, motion blur",
+ "by a crackling fireplace in a wooden cabin in wool socks",
+ "walking through a Christmas market at night between glowing stalls",
+ "making a snow angel in fresh snow, shot from above",
+ ],
+ "aura-farming": [
+ "leaning against a shaded wall, hands in pockets, looking away, totally calm",
+ "standing at the bow of a boat with wind in the hair, an unbothered gaze",
+ "low angle walking toward the camera in a long coat, city at dusk",
+ "sitting on the stairs of an empty subway station under moody fluorescent light",
+ "back to the camera overlooking the city from a rooftop at blue hour",
+ "in a hoodie under a single streetlight in the rain, a calm stare",
+ "sunglasses on, chin up, harsh noon sun and deep shadows",
+ "half the face lit by a window and the rest in darkness, quiet confidence",
+ "standing in a field at golden hour with a jacket over the shoulder",
+ "sitting on the hood of a car at night with the headlights on, relaxed",
+ "walking through drifting smoke on an empty street, cinematic backlight",
+ "a close-up glance over the shoulder, film grain, muted tones",
+ "lying on a skate ramp staring at the sky, wide angle",
+ "on a train looking out of the window at dusk, reflection on the glass",
+ ],
+ looksmaxing: [
+ "a clean studio headshot with a soft key light and a sharp jawline on a neutral backdrop",
+ "a three-quarter portrait with golden rim light and well-groomed hair",
+ "a close-up with clear, glowing skin under a beauty-dish light",
+ "a sculpted side profile against a dark background",
+ "a confident smile in a crisp white shirt, high-key light",
+ "a portrait in a black turtleneck with dramatic Rembrandt light",
+ "a fresh haircut, editorial close-up",
+ "an outdoor golden-hour portrait with a shallow depth of field",
+ "a gym mirror shot with good posture in a fitted tee, flattering light",
+ "a low-angle power portrait against a clear blue sky",
+ "a close-up with direct eye contact and a subtle smile, 85mm lens",
+ "a high-contrast black-and-white portrait with defined features",
+ "an editorial portrait leaning on a column in a minimalist space",
+ "a candid laugh by a window in natural light",
+ "a sharp suit portrait on a city street with blurred lights behind",
+ ],
+ "2000s-nostalgia": [
+ "a digital-camera flash selfie in a bedroom covered in posters, low-rise jeans",
+ "a flip phone to the ear, tinted sunglasses, butterfly clips",
+ "at a mall food court with a smoothie in a velour tracksuit",
+ "a photo-booth snap making a peace sign",
+ "jumping on a backyard trampoline, overexposed flash, date stamp in the corner",
+ "on a bean bag with a handheld game console",
+ "at a house party with cheap flash, red-eye and glitter",
+ "in front of a CRT TV holding a DVD case, frosted lip gloss",
+ "getting into a yellow taxi with shopping bags, paparazzi flash",
+ "in a trucker hat and rhinestone tee in a parking lot at night",
+ "a selfie from above, the classic 2000s angle, heavy flash",
+ "on a sunny beach shot on a disposable camera",
+ "in an arcade lit by neon game screens",
+ "riding a kick scooter down a suburban street",
+ "in a bedroom with a lava lamp and fairy lights, white earbuds",
+ ],
+ "editorial-shots": [
+ "a high-fashion portrait on a seamless red backdrop, bold styling",
+ "sitting on a sculptural chair in a gallery in an avant-garde outfit",
+ "full length in a long coat on an empty runway under a spotlight",
+ "a beauty close-up with graphic eyeliner and glossy skin",
+ "leaning in the doorway of a brutalist building in a monochrome outfit",
+ "lying on a marble floor with draped fabric, shot from above",
+ "walking into the wind with a flowing silk scarf in a white studio",
+ "a portrait framed by palm leaves, tropical editorial",
+ "a hand on the face with dramatic shadows from window blinds",
+ "standing on a ladder in a minimal studio in an oversized suit",
+ "a backlit silhouette with rim light and haze",
+ "sitting on a vintage car in a desert, couture styling",
+ "a cover-style portrait with a direct gaze and soft grain",
+ "jumping mid-air in a pleated dress against a blue sky",
+ "a reflection in a fractured mirror, artful composition",
+ ],
+};
+
+/** How each pack's photos look as a set (added to every photo's prompt). */
+const PACK_LOOK: Record<string, string> = {
+ "sleepy-head": "Soft, cosy morning light, candid phone-photo feel",
+ zen: "Calm natural light, muted earthy tones",
+ "candid-glow": "Warm golden-hour glow, candid lifestyle snapshot",
+ "office-dresscode": "Clean editorial workwear photography",
+ "surreal-self": "Surreal, playful photo-manipulation look, photoreal",
+ "surreal-self-ii": "Surreal, dreamlike photo-manipulation, photoreal",
+ "alter-ego": "Cinematic costume portrait with production-quality styling",
+ "cool-girl-dump": "Effortless, candid 35mm film snapshot",
+ "male-archive": "Candid 35mm film snapshot, effortless menswear",
+ "winter-special": "Cosy winter photo with warm light against the cold",
+ "aura-farming": "Moody, cinematic, effortless-cool photo",
+ looksmaxing: "Flattering, sharp portrait photography",
+ "2000s-nostalgia": "Early-2000s point-and-shoot flash photo",
+ "editorial-shots": "High-end fashion magazine editorial",
+};
+
+export interface Pack extends PackMeta {
+ shots: string[];
+ look: string;
+ /** User packs: one reference photo per shot (the photo to recreate). */
+ refs?: string[];
+ custom?: boolean;
+}
+
+export const PACKS: Pack[] = PHOTODUMP_PACKS.map((p) => ({ ...p, shots: SHOTS[p.id] ?? [], look: PACK_LOOK[p.id] ?? "" }));
+export const getPack = (id: string) => PACKS.find((p) => p.id === id);
+
+/** A user's own pack (Instadump's "Create pack"): up to 15 reference photos to recreate. */
+export const MAX_PACK_REFS = 15;
+/** The one selfie or photo an Instadump starts from. */
+export const MAX_SELFIE_MB = 20;
+export const PHOTODUMP_ASPECTS = ["auto", "9:16", "3:4", "2:3", "1:1", "4:3", "16:9", "3:2"];
+export const DEFAULT_ASPECT = "3:4";
+
+export interface CustomPackLike {
+ id: string;
+ name: string;
+ refs: string[];
+}
+
+/** A user pack as a Pack: one shot per reference photo. */
+export function customPack(p: CustomPackLike): Pack {
+ return {
+ id: p.id,
+ name: p.name,
+ count: p.refs.length,
+ description: `${p.refs.length} reference photo${p.refs.length === 1 ? "" : "s"}`,
+ inferred: false,
+ product: "instadump",
+ shots: p.refs.map(() => "the same pose, framing, setting, outfit style, lighting and colour grade as the reference photo"),
+ look: "",
+ refs: p.refs,
+ custom: true,
+ };
+}
+
+/** Who the photos are of: a saved character (@element) or one uploaded selfie (Instadump, no training). */
+export type PhotoSubject =
+ | { kind: "element"; handle: string; name: string; references: string[]; loras: ElementLora[] }
+ | { kind: "selfie"; url: string };
+
+/** What the server knows about this install, for planning. */
+export interface PlanCaps {
+ /** A Higgsfield key is set (Soul 2.0 with a Soul ID can run for real). */
+ higgsfield: boolean;
+ /** Models this install has (open-source workflows can be missing). */
+ has?: (id: string) => boolean;
+}
+
+export const PHOTODUMP_MODELS: Record<Engine, string[]> = {
+ cloud: ["soul-2", "nano-banana-pro", "seedream-5-pro"],
+ open: ["oss-z-image-turbo", "oss-qwen-edit"],
+};
+
+const soulId = (s: PhotoSubject) => (s.kind === "element" ? s.loras.find((l) => l.modelId === "soul-2" && l.referenceId) : undefined);
+const turboLora = (s: PhotoSubject) => (s.kind === "element" ? s.loras.find((l) => l.modelId === "oss-z-image-turbo" && l.engine === "open" && !l.referenceId) : undefined);
+
+/**
+ * Which model makes a subject's photos: a trained identity where there is one (Soul 2.0 + Soul ID,
+ * Z-Image Turbo + the character LoRA), otherwise a multi-reference edit model with their photos.
+ * `pick` is the user's choice among PHOTODUMP_MODELS, honoured when it can work.
+ */
+export function photodumpModel(subject: PhotoSubject, engine: Engine, caps: PlanCaps, pick?: string, custom = false): { modelId: string; note?: string } {
+ if (engine === "open") {
+ if (!custom && turboLora(subject) && pick !== "oss-qwen-edit") return { modelId: "oss-z-image-turbo" };
+ return { modelId: "oss-qwen-edit", note: subject.kind === "element" && !turboLora(subject) && !custom ? "No trained LoRA yet — Qwen-Image-Edit works from the character's photos" : undefined };
+ }
+ if (!custom && soulId(subject) && caps.higgsfield && (!pick || pick === "soul-2")) return { modelId: "soul-2" };
+ const m = pick === "seedream-5-pro" ? "seedream-5-pro" : "nano-banana-pro";
+ const note =
+ pick === "soul-2"
+ ? soulId(subject)
+ ? "Soul 2.0 needs a Higgsfield key — using Nano Banana Pro with the photos"
+ : "Soul 2.0 needs a trained Soul ID — using Nano Banana Pro with the photos"
+ : undefined;
+ return { modelId: m, note };
+}
+
+const KEEP_FACE = "Keep their exact face, identity, skin tone and hair; a new photo, not a copy of the reference";
+
+/** One photo's prompt for a subject: an @mention for saved characters, image 1 for a selfie. */
+export function shotPrompt(pack: Pick<Pack, "look" | "custom">, shot: string, subject: PhotoSubject, refIndex?: number): string {
+ const who = subject.kind === "element" ? `@${subject.handle}` : "The person in image 1";
+ const look = pack.look ? ` ${pack.look}.` : "";
+ if (pack.custom && refIndex) {
+ return `${who} recreated in image ${refIndex}: ${shot}. Replace the person in image ${refIndex} with them. ${KEEP_FACE}.${look}`.trim();
+ }
+ return `A photo of ${who}, ${shot}.${look}${subject.kind === "selfie" ? ` ${KEEP_FACE}.` : ""}`;
+}
+
+export interface PhotodumpInput {
+ pack: Pack;
+ subject: PhotoSubject;
+ engine: Engine;
+ aspectRatio?: string;
+ modelId?: string;
+}
+
+export interface PhotodumpPlan {
+ modelId: string;
+ requests: GenerationRequest[];
+ notes: string[];
+}
+
+/**
+ * One request per photo of the pack, in order ("Photo 3 of 15"), each making one image. Saved
+ * characters are @mentioned (the server turns that into a Soul ID, a LoRA or reference photos);
+ * a selfie goes in as image 1. User packs add their reference photo after the subject.
+ */
+export function planPhotodump(input: PhotodumpInput, caps: PlanCaps): PhotodumpPlan {
+ const { pack, subject } = input;
+ if (!pack.shots.length) throw new Error("This pack has no photos");
+ if (subject.kind === "element" && !subject.references.length && !subject.loras.length) throw new Error(`Add a photo of ${subject.name} first`);
+ const notes: string[] = [];
+ const route = photodumpModel(subject, input.engine, caps, input.modelId, !!pack.custom);
+ if (route.note) notes.push(route.note);
+ const n = pack.shots.length;
+ const aspect = input.aspectRatio && input.aspectRatio !== "auto" ? input.aspectRatio : undefined;
+ const requests = pack.shots.map((shot, i): GenerationRequest => {
+ const own = subject.kind === "selfie" ? [subject.url] : [];
+ const ref = pack.refs?.[i];
+ // User packs: the reference goes after the identity images; @mention references come after those (applyMentions appends).
+ const images = ref ? [...own, ref] : own;
+ const refIndex = ref ? images.length : undefined;
+ return {
+ feature: "photodump",
+ modelId: route.modelId,
+ prompt: shotPrompt(pack, shot, subject, refIndex),
+ inputs: images.length ? { images } : undefined,
+ params: { numOutputs: 1, ...(aspect && { aspectRatio: aspect }) },
+ step: { label: `Photo ${i + 1} of ${n}`, index: i, of: n },
+ };
+ });
+ return { modelId: route.modelId, requests, notes };
+}
+
+// ---------------------------------------------------------------------------
+// Fashion Factory
+
+interface TemplateLook {
+ /** The set: backdrop, light and mood. */
+ look: string;
+ /** One prompt per photo of the photoset. */
+ shots: string[];
+}
+
+const LOOKS: Record<string, TemplateLook> = {
+ "ultra-bold": {
+ look: "a bold, saturated colour-blocked studio set with primary-colour backdrops and props, hard flash and graphic shadows",
+ shots: [
+ "full body standing on a cobalt-blue seamless next to a red cube",
+ "crouching low on a yellow floor against a green wall, wide angle",
+ "a three-quarter close-up against a hot-pink backdrop, hard flash",
+ "sitting on an orange stool with legs crossed in front of a blue backdrop",
+ "mid-stride across colour-blocked floor panels, a hint of motion",
+ "leaning on a giant red letter-shaped prop, playful pose",
+ "back view looking over the shoulder against a purple backdrop",
+ "arms raised in a dynamic pose in front of a split two-tone wall",
+ "lying on a mint-green floor, shot from above",
+ "hands on hips, cropped at the chest to show the outfit",
+ "jumping in front of a yellow wall with a crisp hard shadow",
+ ],
+ },
+ "blue-green-gradient": {
+ look: "a studio set on a smooth blue-to-green gradient backdrop with soft, even light",
+ shots: [
+ "full body from the front, centred on the gradient",
+ "a three-quarter view with one hand in a pocket",
+ "seated on a white plinth in a relaxed pose",
+ "walking in profile with the gradient behind",
+ "a close-up portrait in soft beauty light",
+ "back view showing the back of the outfit",
+ "a low-angle full-body power pose",
+ "leaning forward on a stool, elbows on the knees",
+ "mid-turn with the fabric in motion",
+ "waist-up with arms crossed",
+ ],
+ },
+ "street-style-paparazzi": {
+ look: "a street-style shoot with paparazzi flash energy: city sidewalks, taxis, night flash and onlookers",
+ shots: [
+ "walking out of a hotel at night under bursts of camera flash, sunglasses on",
+ "crossing a busy crosswalk, candid, telephoto compression",
+ "stepping out of a black car, flash reflections on the pavement",
+ "waiting at a crosswalk with a coffee, looking away",
+ "a hand raised to block the camera, flash glare",
+ "leaning on a shop window at dusk, the full outfit visible",
+ "walking past a crowd of photographers, motion blur behind",
+ "sitting on a street bench with legs crossed under an overcast sky",
+ "a close-up glance over the shoulder in direct flash",
+ ],
+ },
+ "view-from-the-top": {
+ look: "high-angle and top-down fashion framing, graphic floors and patterns",
+ shots: [
+ "shot top-down lying on a patterned rug",
+ "seen from a balcony high above, standing alone on a stone plaza",
+ "a bird's-eye view standing on the white stripes of a crosswalk",
+ "an overhead shot sitting on a staircase with the outfit spread out",
+ "a high angle looking up at the camera, wide lens",
+ "top-down lying on a bed of flowers with arms spread",
+ ],
+ },
+ "light-blue-studio": {
+ look: "a clean pale-blue seamless studio with soft, diffused light and minimal props",
+ shots: [
+ "full body from the front in a relaxed stance",
+ "a three-quarter view with a slight smile",
+ "seated on a pale-blue cube",
+ "a side profile with the chin up",
+ "a close-up portrait",
+ "walking toward the camera",
+ "back view",
+ "leaning against the seamless wall",
+ "hands in the hair, playful",
+ "a crouching pose with the whole outfit visible",
+ ],
+ },
+ "red-room": {
+ look: "a monochrome all-red set: red walls, red floor and red props under warm, hard light",
+ shots: [
+ "full body standing in the middle of the red room",
+ "sitting in a red velvet armchair",
+ "lying on the red floor, shot from above",
+ "leaning in a red door frame",
+ "a close-up portrait against the red walls",
+ "walking down a red corridor",
+ "holding a red telephone receiver",
+ "back view at a red-curtained window",
+ "a dramatic low-angle full-body shot",
+ ],
+ },
+};
+
+export interface FashionTemplate extends FashionTemplateMeta {
+ look: string;
+ photoset: string[];
+ /** Two colours for the drawn preview. */
+ hues: [number, number];
+}
+
+const TEMPLATE_HUES: Record<string, [number, number]> = {
+ "ultra-bold": [25, 255],
+ "blue-green-gradient": [230, 160],
+ "street-style-paparazzi": [270, 45],
+ "view-from-the-top": [95, 30],
+ "light-blue-studio": [215, 205],
+ "red-room": [20, 5],
+};
+
+export const FASHION: FashionTemplate[] = FASHION_TEMPLATES.map((t) => ({
+ ...t,
+ look: LOOKS[t.id]?.look ?? t.description,
+ photoset: LOOKS[t.id]?.shots ?? [],
+ hues: TEMPLATE_HUES[t.id] ?? [hueOf(t.id), (hueOf(t.id) + 60) % 360],
+}));
+export const getTemplate = (id: string) => FASHION.find((t) => t.id === id);
+
+export const FASHION_MODELS = {
+ outfit: { cloud: ["fashn-tryon", "nano-banana-pro"], open: ["oss-tryon-klein"] },
+} as const;
+
+const element = (s: PhotoSubject) => (s.kind === "element" ? `@${s.handle}` : "the person in image 1");
+
+/** Step 2: four base shots of the character in the template's set, 3:4. */
+export function fashionBaseRequest(t: FashionTemplate, subject: Extract<PhotoSubject, { kind: "element" }>, engine: Engine, caps: PlanCaps): GenerationRequest {
+ if (!subject.references.length && !subject.loras.length) throw new Error(`Add a photo of ${subject.name} first`);
+ const { modelId } = photodumpModel(subject, engine, caps);
+ return {
+ feature: "fashion",
+ modelId,
+ prompt: `A full-body fashion photo of ${element(subject)} in ${t.look}. A natural, relaxed model pose looking at the camera, simple fitted basics so the outfit can be changed later, photorealistic, sharp detail.`,
+ params: { aspectRatio: "3:4", numOutputs: 4 },
+ step: { label: "Base shots", index: 0, of: 3 },
+ };
+}
+
+/** Step 4: the base shot wearing the uploaded outfit (try-on, or an edit that dresses them). */
+export function fashionOutfitRequest(t: FashionTemplate, base: string, garment: string, engine: Engine, modelId?: string): GenerationRequest {
+ const id = engine === "open" ? "oss-tryon-klein" : modelId === "nano-banana-pro" ? "nano-banana-pro" : "fashn-tryon";
+ const tryon = id !== "nano-banana-pro";
+ return {
+ feature: "fashion",
+ modelId: id,
+ op: "edit",
+ prompt: tryon
+ ? "A full-body photo of a person. Replace the outfit with the garment shown in the reference image, with its fabric, colour, pattern, logo and fit."
+ : `Dress the person in image 1 in the outfit or product from image 2: its exact fabric, colour, pattern, logo and fit. Keep their face, pose and ${t.name.toLowerCase()} set from image 1.`,
+ inputs: { images: [base, garment] },
+ params: { numOutputs: 2, ...(tryon ? {} : { aspectRatio: "3:4" }) },
+ step: { label: "Outfit", index: 1, of: 3 },
+ };
+}
+
+/** Step 5: one photo per template shot, from the dressed image. */
+export function fashionPhotosetRequests(t: FashionTemplate, dressed: string, engine: Engine): GenerationRequest[] {
+ const modelId = engine === "open" ? "oss-qwen-edit" : "nano-banana-pro";
+ const n = t.photoset.length;
+ return t.photoset.map((shot, i) => ({
+ feature: "fashion",
+ modelId,
+ op: "edit",
+ prompt: `The same person in exactly the same outfit as image 1, ${shot}, in ${t.look}. Keep their face, hair, the garment's fabric, colour, pattern and logo identical; a new fashion photo, photorealistic.`,
+ inputs: { images: [dressed] },
+ params: { numOutputs: 1, aspectRatio: "3:4" },
+ step: { label: `Photoset ${i + 1} of ${n}`, index: i, of: n },
+ }));
+}
+
+// The wizard: template → character → pick 1 of 4 base shots → outfit → photoset.
+
+export type FashionStep = "template" | "character" | "generation" | "clothing" | "photoset";
+export const FASHION_STEPS: FashionStep[] = ["template", "character", "generation", "clothing", "photoset"];
+
+export interface FashionState {
+ step: FashionStep;
+ templateId?: string;
+ elementId?: string;
+ /** The base shots' generation ids, and the one picked. */
+ baseIds: string[];
+ base?: string;
+ garment?: { url: string; uploading: boolean };
+ outfitIds: string[];
+ outfit?: string;
+ photosetBatch?: string;
+}
+
+export const FASHION_START: FashionState = { step: "template", baseIds: [], outfitIds: [] };
+
+export type FashionAction =
+ | { type: "template"; id: string }
+ | { type: "element"; id: string }
+ | { type: "next" }
+ | { type: "back" }
+ | { type: "goto"; step: FashionStep }
+ | { type: "baseStarted"; ids: string[] }
+ | { type: "pickBase"; url: string }
+ | { type: "garment"; garment?: { url: string; uploading: boolean } }
+ | { type: "outfitStarted"; ids: string[] }
+ | { type: "pickOutfit"; url: string }
+ | { type: "photosetStarted"; batchId: string }
+ | { type: "reset" };
+
+/** The exact message Higgsfield shows when a step can't go on, or null. */
+export function fashionBlocker(s: FashionState, action: "next" | "outfit" | "photoset" = "next"): string | null {
+ if (s.step === "template" || !s.templateId) return s.templateId ? null : "Template required";
+ if (s.step === "character") return s.elementId ? null : "Pick or create a character first";
+ if (s.step === "generation") return s.base ? null : "Select an image at the generation step";
+ if (s.step === "clothing") {
+ if (action === "outfit") return !s.garment ? "No product to generate" : s.garment.uploading ? "Please wait for the image to finish processing before generating" : null;
+ return s.outfit ? null : "Select an image at the clothing step";
+ }
+ return null;
+}
+
+export function fashionReducer(s: FashionState, a: FashionAction): FashionState {
+ const at = FASHION_STEPS.indexOf(s.step);
+ switch (a.type) {
+ case "template":
+ // A new set invalidates everything made in the old one.
+ return a.id === s.templateId ? s : { ...FASHION_START, step: s.step, templateId: a.id, elementId: s.elementId };
+ case "element":
+ return a.id === s.elementId ? s : { ...s, elementId: a.id, baseIds: [], base: undefined, outfitIds: [], outfit: undefined, photosetBatch: undefined };
+ case "next":
+ if (fashionBlocker(s) || at === FASHION_STEPS.length - 1) return s;
+ return { ...s, step: FASHION_STEPS[at + 1] };
+ case "back":
+ return at > 0 ? { ...s, step: FASHION_STEPS[at - 1] } : s;
+ case "goto": {
+ // Only back to a step already reached (or the next one once this one is done).
+ const to = FASHION_STEPS.indexOf(a.step);
+ if (to <= at) return { ...s, step: a.step };
+ let cur = s;
+ while (FASHION_STEPS.indexOf(cur.step) < to) {
+ const next = fashionReducer(cur, { type: "next" });
+ if (next === cur) return cur;
+ cur = next;
+ }
+ return cur;
+ }
+ case "baseStarted":
+ return { ...s, step: "generation", baseIds: a.ids, base: undefined, outfitIds: [], outfit: undefined, photosetBatch: undefined };
+ case "pickBase":
+ return { ...s, base: a.url, outfitIds: a.url === s.base ? s.outfitIds : [], outfit: a.url === s.base ? s.outfit : undefined };
+ case "garment":
+ return { ...s, garment: a.garment };
+ case "outfitStarted":
+ return { ...s, outfitIds: [...a.ids, ...s.outfitIds], outfit: undefined };
+ case "pickOutfit":
+ return { ...s, outfit: a.url };
+ case "photosetStarted":
+ return { ...s, step: "photoset", photosetBatch: a.batchId };
+ case "reset":
+ return FASHION_START;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Character Sheet ("Build your AI avatar")
+
+export const SHEET_MAX_REFS = 5;
+
+export const SHEET_PROMPT =
+ "A character turnaround sheet of the person in the reference images: full-body front view, three-quarter view, side profile and back view side by side, plus a close-up of the face, on a seamless light-grey studio backdrop with soft, even light. The same face, hairstyle, body and outfit in every view; photorealistic, natural skin texture, no text.";
+
+/** From Reference: 1–5 photos → a turnaround sheet (Nano Banana Pro, or Qwen-Image-Edit with up to 3). */
+export function sheetFromReference(images: string[], engine: Engine, details?: string): { request: GenerationRequest; notes: string[] } {
+ if (!images.length) throw new Error("Upload at least 1 image");
+ if (images.length > SHEET_MAX_REFS) throw new Error(`Maximum ${SHEET_MAX_REFS} images`);
+ const notes: string[] = [];
+ const max = engine === "open" ? 3 : SHEET_MAX_REFS;
+ if (images.length > max) notes.push(`Qwen-Image-Edit takes 3 photos — the first 3 are used`);
+ const extra = details?.trim().replace(/[.\s]+$/, "");
+ return {
+ request: {
+ feature: "character-sheet",
+ modelId: engine === "open" ? "oss-qwen-edit" : "nano-banana-pro",
+ op: "edit",
+ prompt: extra ? `${SHEET_PROMPT} ${extra}.` : SHEET_PROMPT,
+ inputs: { images: images.slice(0, max) },
+ params: { aspectRatio: engine === "open" ? undefined : "16:9", numOutputs: 1 },
+ },
+ notes,
+ };
+}
+
+/** Build from scratch: the Soul Cast form → its casting sheet model on each engine. */
+export function castSheetModel(engine: Engine, caps: PlanCaps): string {
+ if (engine === "open") return !caps.has || caps.has("oss-zimage-soul-cast") ? "oss-zimage-soul-cast" : "oss-z-image-turbo";
+ return caps.higgsfield ? "soul-2" : "nano-banana-pro";
+}
+
+/** Soul Cast fields that only make sense for some answers (mirrors SOUL_CAST_FIELDS[].when in cinema.ts). */
+const BEARDED = ["Beard", "Long beard", "Mustache", "Short beard"];
+export function castFieldVisible(key: string, values: Record<string, unknown>): boolean {
+ if (key === "facial_hair") return values.gender !== "Female";
+ if (key === "facial_hair_color") return values.gender !== "Female" && BEARDED.includes(String(values.facial_hair));
+ return true;
+}
diff --git a/src/lib/catalog/palettes.ts b/src/lib/catalog/palettes.ts
new file mode 100644
index 00000000..8b34d646
--- /dev/null
+++ b/src/lib/catalog/palettes.ts
@@ -0,0 +1,491 @@
+/**
+ * Colour signatures (Higgsfield's Soul HEX) and the Image studio's style signature: a saved palette
+ * and/or a moodboard picked in the composer, and how each model gets them.
+ *
+ * Pure and catalog-free (the composer runs it in the browser; the server tests it): models are
+ * passed in, and what only the server knows (which models take a palette field, their background
+ * field) arrives as `SignatureCaps` from GET /api/palettes.
+ *
+ * Routing (docs/research/higgsfield-image-studios.md §4, §5):
+ * - Palette → models with a palette field (Recraft V4.1 / Pro / Styles: ≤10 colours, Ideogram 3.0):
+ * `params.palette` (+ the background colour in its own field); Cinema Studio 4.0: the built-in
+ * palette's slug as `color_palette`; every other model: the hex list written into the prompt. Open
+ * engine: Z-Image Turbo becomes Z-Image Turbo · Palette (hex in the prompt + a ColorTransfer lock to
+ * a swatch); other open models can add a palette-transfer post-step (oss-palette-image, chained).
+ * - Moodboard → curated: Soul 2.0's `style_id` on soul-2, the preset's description as words elsewhere.
+ * Personal: cloud = the board's Recraft style id (Recraft models) or its most representative images
+ * as style references (Nano Banana Pro and other multi-reference models); open = the board's collages
+ * on Qwen-Image-Edit Style Reference (or the style-reference model picked), or its trained style LoRA
+ * on Z-Image Turbo.
+ */
+import type { GenerationRequest, ModelDef } from "./types";
+
+export type RGB = [number, number, number];
+
+// ---------------------------------------------------------------------------
+// Palettes
+
+export type PaletteSource = "builtin" | "manual" | "images";
+
+export interface Palette {
+ id: string;
+ name: string;
+ /** 1–12 colours, "#RRGGBB" upper-case. Built-ins: Cinema Studio's 12, dark → light, the accent last. */
+ colors: string[];
+ /** The background colour ("Use as background"); built-ins use their 12th colour. */
+ background: string | null;
+ /** Cinema Studio 4.0 `color_palette` value (built-ins only). */
+ slug: string | null;
+ source: PaletteSource;
+ /** A picture the palette came from (image-made palettes): the card's thumbnail. */
+ thumb: string | null;
+ createdAt: number;
+}
+
+export const MAX_COLORS = 12;
+/** Recraft V4.1 takes at most 10 colours. */
+export const MAX_COLORS_RECRAFT = 10;
+/** "Upload & Create" takes up to 20 photos. */
+export const MAX_SOURCE_IMAGES = 20;
+export const NAME_MAX = 60;
+export const HEX_RE = /^#[0-9a-f]{6}$/i;
+
+/** The manual editor's starting palette (Higgsfield's defaults). */
+export const MANUAL_DEFAULT = { colors: ["#FFFFFF", "#D1FE17", "#1C1E20"], background: "#53C546" } as const;
+
+/** "#abc", "abcdef", " #ABCDEF " → "#ABCDEF"; anything else → null. */
+export function normalizeHex(input: string): string | null {
+ const s = input.trim().replace(/^#/, "");
+ const full = /^[0-9a-f]{3}$/i.test(s) ? s.replace(/./g, (c) => c + c) : s;
+ return /^[0-9a-f]{6}$/i.test(full) ? `#${full.toUpperCase()}` : null;
+}
+
+/** What's wrong with a palette before it can be saved, or null. */
+export function paletteError(p: { name: string; colors: string[]; background?: string | null }): string | null {
+ if (!p.name.trim()) return "Give the palette a name";
+ if (p.name.trim().length > NAME_MAX) return `Keep the name under ${NAME_MAX} characters`;
+ if (!p.colors.length) return "Add at least one colour";
+ if (p.colors.length > MAX_COLORS) return `A palette holds up to ${MAX_COLORS} colours`;
+ const bad = p.colors.find((c) => !HEX_RE.test(c));
+ if (bad) return `${bad} isn't a colour — use #RRGGBB`;
+ if (p.background && !HEX_RE.test(p.background)) return `${p.background} isn't a colour — use #RRGGBB`;
+ return null;
+}
+
+/** The card's colour strip: the background first, then the other colours without repeats. */
+export function cardStrip(p: Pick<Palette, "colors" | "background">): string[] {
+ const out: string[] = [];
+ for (const c of [p.background, ...p.colors]) {
+ const h = c?.toUpperCase();
+ if (h && !out.includes(h)) out.push(h);
+ }
+ return out;
+}
+
+/** The colours sent to a model: the palette's own, then the background when it isn't one of them. */
+export function paletteColors(p: Pick<Palette, "colors" | "background">): string[] {
+ return cardStrip({ colors: p.colors, background: null }).concat(p.background && !p.colors.some((c) => c.toUpperCase() === p.background!.toUpperCase()) ? [p.background.toUpperCase()] : []);
+}
+
+export const hexToRgb = (hex: string): RGB => {
+ const n = parseInt(hex.replace("#", ""), 16);
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
+};
+
+export const rgbToHex = ([r, g, b]: RGB): string =>
+ `#${[r, g, b].map((v) => Math.round(Math.max(0, Math.min(255, v))).toString(16).padStart(2, "0")).join("")}`.toUpperCase();
+
+const luminance = ([r, g, b]: RGB) => 0.2126 * r + 0.7152 * g + 0.0722 * b;
+
+export function rgbToHsv([r, g, b]: RGB): [number, number, number] {
+ const rr = r / 255;
+ const gg = g / 255;
+ const bb = b / 255;
+ const max = Math.max(rr, gg, bb);
+ const d = max - Math.min(rr, gg, bb);
+ let h = 0;
+ if (d) h = max === rr ? ((gg - bb) / d) % 6 : max === gg ? (bb - rr) / d + 2 : (rr - gg) / d + 4;
+ return [((h * 60 + 360) % 360) || 0, max ? d / max : 0, max];
+}
+
+export function hsvToHex(h: number, s: number, v: number): string {
+ const c = v * s;
+ const hh = ((h % 360) + 360) % 360;
+ const x = c * (1 - Math.abs(((hh / 60) % 2) - 1));
+ const m = v - c;
+ const [r, g, b] = hh < 60 ? [c, x, 0] : hh < 120 ? [x, c, 0] : hh < 180 ? [0, c, x] : hh < 240 ? [0, x, c] : hh < 300 ? [x, 0, c] : [c, 0, x];
+ return rgbToHex([(r + m) * 255, (g + m) * 255, (b + m) * 255]);
+}
+
+/** Deterministic PRNG (mulberry32), so tests and "the same image" give the same answer. */
+export function rng(seed = 1): () => number {
+ let a = seed >>> 0;
+ return () => {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/** Higgsfield's "Random palettes": `n` rows of 2–12 uniformly random colours each (shown trimmed to 6). */
+export function randomPalettes(rand: () => number = Math.random, n = 4): string[][] {
+ return Array.from({ length: n }, () => {
+ const len = 2 + Math.floor(rand() * 11);
+ return Array.from({ length: len }, () => rgbToHex([rand() * 255, rand() * 255, rand() * 255]));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Extraction (k-means; runs in a Web Worker in the browser, see components/palettes/extract.worker.ts)
+
+/** RGBA pixels → at most `max` RGB samples (evenly strided; transparent pixels skipped). */
+export function samplePixels(data: ArrayLike<number>, max = 4000): RGB[] {
+ const total = Math.floor(data.length / 4);
+ const step = Math.max(1, Math.floor(total / max));
+ const out: RGB[] = [];
+ for (let i = 0; i < total; i += step) {
+ const o = i * 4;
+ if (data[o + 3] < 128) continue;
+ out.push([data[o], data[o + 1], data[o + 2]]);
+ }
+ return out;
+}
+
+const dist2 = (a: RGB, b: RGB) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
+
+export interface Cluster {
+ color: string;
+ rgb: RGB;
+ /** Share of all sampled pixels. */
+ share: number;
+}
+
+/** k-means++ over RGB samples; clusters by share, largest first (empty ones dropped). */
+export function kmeans(pixels: RGB[], k: number, opts: { iterations?: number; seed?: number } = {}): Cluster[] {
+ if (!pixels.length || k < 1) return [];
+ const rand = rng(opts.seed ?? 7);
+ const kk = Math.min(k, pixels.length);
+ const centres: RGB[] = [pixels[Math.floor(rand() * pixels.length)]];
+ const nearest = pixels.map((p) => dist2(p, centres[0]));
+ while (centres.length < kk) {
+ const sum = nearest.reduce((a, b) => a + b, 0);
+ if (!sum) break;
+ let r = rand() * sum;
+ let idx = 0;
+ while (idx < nearest.length - 1 && r > nearest[idx]) r -= nearest[idx++];
+ const c: RGB = [...pixels[idx]] as RGB;
+ centres.push(c);
+ for (let i = 0; i < pixels.length; i++) nearest[i] = Math.min(nearest[i], dist2(pixels[i], c));
+ }
+ const assign = new Int32Array(pixels.length).fill(-1);
+ for (let it = 0; it < (opts.iterations ?? 16); it++) {
+ let moved = false;
+ for (let i = 0; i < pixels.length; i++) {
+ let best = 0;
+ let bd = Infinity;
+ for (let c = 0; c < centres.length; c++) {
+ const d = dist2(pixels[i], centres[c]);
+ if (d < bd) {
+ bd = d;
+ best = c;
+ }
+ }
+ if (assign[i] !== best) {
+ assign[i] = best;
+ moved = true;
+ }
+ }
+ const sums = centres.map(() => [0, 0, 0, 0]);
+ for (let i = 0; i < pixels.length; i++) {
+ const s = sums[assign[i]];
+ s[0] += pixels[i][0];
+ s[1] += pixels[i][1];
+ s[2] += pixels[i][2];
+ s[3]++;
+ }
+ sums.forEach((s, c) => {
+ if (s[3]) centres[c] = [s[0] / s[3], s[1] / s[3], s[2] / s[3]];
+ });
+ if (!moved) break;
+ }
+ const counts = centres.map(() => 0);
+ for (const a of assign) counts[a]++;
+ return centres
+ .map((c, i) => ({ rgb: c.map(Math.round) as RGB, color: rgbToHex(c), share: counts[i] / pixels.length }))
+ .filter((c) => c.share > 0)
+ .sort((a, b) => b.share - a.share);
+}
+
+/**
+ * A palette from several images: each image gets an equal say (its samples are capped to the same
+ * number), clusters closer than a just-noticeable step are merged, and the result is ordered
+ * dark → light with the dominant colour as the background.
+ */
+export function extractPalette(images: RGB[][], opts: { count?: number; seed?: number } = {}): { colors: string[]; background: string | null; weights: number[] } {
+ const usable = images.filter((px) => px.length);
+ if (!usable.length) return { colors: [], background: null, weights: [] };
+ const per = Math.max(200, Math.floor(6000 / usable.length));
+ const pooled: RGB[] = [];
+ for (const px of usable) {
+ const step = Math.max(1, Math.floor(px.length / per));
+ for (let i = 0; i < px.length; i += step) pooled.push(px[i]);
+ }
+ const count = Math.max(2, Math.min(MAX_COLORS, opts.count ?? 8));
+ const clusters = kmeans(pooled, count, { seed: opts.seed });
+ // Merge near-duplicates (ΔRGB < 18): one flat background shouldn't take three slots.
+ const merged: Cluster[] = [];
+ for (const c of clusters) {
+ const twin = merged.find((m) => dist2(m.rgb, c.rgb) < 18 * 18);
+ if (twin) twin.share += c.share;
+ else merged.push({ ...c });
+ }
+ const background = merged[0]?.color ?? null;
+ const ordered = [...merged].sort((a, b) => luminance(a.rgb) - luminance(b.rgb));
+ return { colors: ordered.map((c) => c.color), background, weights: ordered.map((c) => Math.round(c.share * 1000) / 1000) };
+}
+
+const HUES: [number, string][] = [
+ [15, "Red"],
+ [40, "Amber"],
+ [65, "Gold"],
+ [90, "Lime"],
+ [150, "Green"],
+ [190, "Teal"],
+ [215, "Sky"],
+ [250, "Blue"],
+ [285, "Violet"],
+ [320, "Magenta"],
+ [345, "Rose"],
+ [360, "Red"],
+];
+
+/** A rough colour word for a hex ("Teal", "Ink", "Ivory"). */
+export function colorWord(hex: string): string {
+ const [h, s, v] = rgbToHsv(hexToRgb(hex));
+ if (v < 0.16) return "Ink";
+ if (s < 0.12) return v > 0.9 ? "Ivory" : v > 0.55 ? "Silver" : "Graphite";
+ return HUES.find(([limit]) => h < limit)?.[1] ?? "Red";
+}
+
+/** A name to start from ("Teal Dusk", "Amber Noon"): the dominant colour's word plus a mood from the palette's light. */
+export function suggestName(colors: string[], background?: string | null): string {
+ if (!colors.length) return "My palette";
+ const lead = colorWord(background ?? colors[0]);
+ const lights = colors.map((c) => rgbToHsv(hexToRgb(c))[2]);
+ const sats = colors.map((c) => rgbToHsv(hexToRgb(c))[1]);
+ const v = lights.reduce((a, b) => a + b, 0) / lights.length;
+ const s = sats.reduce((a, b) => a + b, 0) / sats.length;
+ const mood = v < 0.3 ? "Midnight" : v < 0.45 ? (s > 0.45 ? "Ember" : "Dusk") : v > 0.75 ? (s > 0.35 ? "Pop" : "Haze") : s > 0.5 ? "Fever" : s < 0.18 ? "Fog" : "Noon";
+ const second = colors.map(colorWord).find((w) => w !== lead);
+ return lead === mood ? `${second ?? "Soft"} ${mood}` : `${lead} ${mood}`;
+}
+
+/** The sentence models that read hex codes follow (FLUX.2, Nano Banana, Seedream, GPT Image). */
+export function palettePrompt(p: Pick<Palette, "colors" | "background">): string {
+ const colors = cardStrip({ colors: p.colors, background: null });
+ return `Color palette: use only these colors, in roughly this balance: ${colors.join(", ")}${p.background ? `; background color ${p.background.toUpperCase()}` : ""}.`;
+}
+
+// ---------------------------------------------------------------------------
+// The style signature in the Image studio composer
+
+/** What the composer keeps of a picked palette (enough to route it without another fetch). */
+export interface PalettePick {
+ id: string;
+ name: string;
+ colors: string[];
+ background: string | null;
+ slug: string | null;
+ thumb?: string | null;
+ /** Open engine: recolour the result to the palette afterwards (oss-palette-image, chained). */
+ lock?: boolean;
+}
+
+export type MoodboardStatus = "queued" | "running" | "cover" | "complete" | "failed";
+
+/** What the composer keeps of a picked moodboard. */
+export interface MoodboardPick {
+ id: string;
+ kind: "curated" | "personal";
+ name: string;
+ description?: string;
+ status: MoodboardStatus;
+ cover?: string | null;
+ /** Personal: the most representative images, best first (≤10). */
+ refs?: string[];
+ /** Personal: 1–2 collages of 4 images each, for open style-reference models. */
+ collages?: string[];
+ /** Personal: a Recraft V4 style made from the board (cloud). */
+ styleId?: string | null;
+ /** Personal: the @handle of the style element with a trained Z-Image Turbo LoRA (open). */
+ loraHandle?: string | null;
+}
+
+export interface Signature {
+ palette?: PalettePick;
+ moodboard?: MoodboardPick;
+}
+
+export interface SignatureCaps {
+ /** Models whose routes take a palette field: how many colours and the background colour's field. */
+ native: Record<string, { max: number; background?: string }>;
+}
+
+export interface SignatureContext {
+ caps: SignatureCaps;
+ getModel: (id: string) => ModelDef | undefined;
+}
+
+export interface SignedRequest {
+ request: GenerationRequest;
+ /** The model it runs on now (a moodboard or palette can move it). */
+ modelId: string;
+ /** What changed, said once under the composer. */
+ notes: string[];
+ /** Why it can't run (a moodboard still training). */
+ blocker?: string;
+ /** Recolour the result to these colours afterwards (open palette lock, a chained step). */
+ lock?: { colors: string[] };
+}
+
+/** Models a signature can move a request to; studios that offer the chips keep them in their model slice. */
+export const SIGNATURE_MODELS = {
+ cloudRefs: "nano-banana-pro",
+ recraftStyle: "recraft-4-style",
+ recraftSaved: "recraft-4-style-saved",
+ openStyle: "oss-style-qwen-edit",
+ openPalette: "oss-zimage-palette",
+ openTurbo: "oss-z-image-turbo",
+ paletteLock: "oss-palette-image",
+ soul2: "soul-2",
+ cinema: "cinema-studio-4",
+} as const;
+
+const NOT_READY = "This moodboard is still training. Try again once it is ready.";
+
+const hasOp = (m: ModelDef, op: string) => m.routes.some((r) => r.op === op);
+/** Room for style references beyond the user's own images (multi-reference edit models). */
+const refBudget = (m: ModelDef, existing: number) => (hasOp(m, "edit") ? Math.max(0, (m.options.maxImages ?? 1) - existing) : 0);
+const tidy = (s: string | undefined) => (s ?? "").trim().replace(/[.\s]+$/, "");
+const join = (prompt: string | undefined, sentence: string) => (tidy(prompt) ? `${tidy(prompt)}. ${sentence}` : sentence);
+
+/** "In the style of “Retro BW”: grainy black-and-white film portrait." */
+export function styleWords(m: Pick<MoodboardPick, "name" | "description">): string {
+ const d = tidy(m.description);
+ return `In the style of “${m.name}”${d ? `: ${d.charAt(0).toLowerCase()}${d.slice(1)}` : ""}.`;
+}
+
+/** The legend for a board's images sent as references: positions 1-based within inputs.images. */
+export function styleLegend(from: number, to: number): string {
+ const which = from === to ? `image ${from}` : `images ${from}–${to}`;
+ return `Use ${which} only as a style reference: match their colour palette, light, texture, grain and mood, but don't copy their subjects or layout.`;
+}
+
+function swap(request: GenerationRequest, to: ModelDef, from: ModelDef): GenerationRequest {
+ if (to.id === from.id) return request;
+ const p = request.params ?? {};
+ // Keep what the new model takes; drop the old model's own settings.
+ const aspect = p.aspectRatio && (!to.options.aspectRatios || to.options.aspectRatios.includes(p.aspectRatio)) ? p.aspectRatio : to.defaults?.aspectRatio;
+ const resolution = p.resolution && to.options.resolutions?.includes(p.resolution) ? p.resolution : to.defaults?.resolution;
+ return {
+ ...request,
+ modelId: to.id,
+ op: undefined,
+ params: { ...to.defaults, aspectRatio: aspect, resolution, numOutputs: p.numOutputs, seed: p.seed, enhancePrompt: p.enhancePrompt, palette: p.palette, extra: undefined },
+ };
+}
+
+const setExtra = (r: GenerationRequest, key: string, value: unknown): GenerationRequest => ({ ...r, params: { ...r.params, extra: { ...r.params?.extra, [key]: value } } });
+
+/**
+ * Apply the composer's palette and moodboard to a request. Pure: the same call prices the run while
+ * you type and builds what's sent.
+ */
+export function applySignature(req: GenerationRequest, sig: Signature | undefined, ctx: SignatureContext): SignedRequest {
+ let model = ctx.getModel(req.modelId);
+ if (!model || (!sig?.palette && !sig?.moodboard)) return { request: req, modelId: req.modelId, notes: [] };
+ let r: GenerationRequest = req;
+ const notes: string[] = [];
+ const move = (id: string, why: string) => {
+ const to = ctx.getModel(id);
+ if (!to || !model || to.id === model.id) return false;
+ r = swap(r, to, model);
+ notes.push(why.replace("{model}", to.name));
+ model = to;
+ return true;
+ };
+ let styled = false;
+
+ const mb = sig.moodboard;
+ if (mb) {
+ if (mb.kind === "personal" && mb.status !== "complete") return { request: req, modelId: req.modelId, notes: [], blocker: mb.status === "failed" ? "This moodboard failed to build — retry it on the Moodboards page" : NOT_READY };
+ if (mb.kind === "curated") {
+ if (model.id === SIGNATURE_MODELS.soul2) r = setExtra(r, "style_id", mb.id);
+ else {
+ r = { ...r, prompt: join(r.prompt, styleWords(mb)) };
+ notes.push(`${mb.name} is a Soul 2.0 preset — described in words on ${model.name}`);
+ }
+ styled = true;
+ } else {
+ const existing = r.inputs?.images?.length ?? 0;
+ const refs = mb.refs ?? [];
+ const collages = mb.collages?.length ? mb.collages : refs.slice(0, 2);
+ if (model.engine === "cloud") {
+ if (model.family === "recraft" && mb.styleId) {
+ move(SIGNATURE_MODELS.recraftSaved, `Runs on {model} with “${mb.name}”'s saved Recraft style`);
+ r = { ...r, params: { ...r.params, styleId: mb.styleId } };
+ } else if (model.family === "recraft") {
+ move(SIGNATURE_MODELS.recraftStyle, `Runs on {model}, styled by “${mb.name}”'s images`);
+ r = { ...r, op: "edit", inputs: { ...r.inputs, images: refs.slice(0, 10) } };
+ } else {
+ let budget = Math.min(refBudget(model, existing), 6);
+ if (!budget && model.id !== SIGNATURE_MODELS.cloudRefs) {
+ move(SIGNATURE_MODELS.cloudRefs, `${model.name} can't take style references — runs on {model} with “${mb.name}”`);
+ budget = Math.min(refBudget(model, existing), 6);
+ }
+ const take = refs.slice(0, budget);
+ if (!take.length) return { request: req, modelId: req.modelId, notes, blocker: "Remove a reference image to make room for the moodboard" };
+ r = { ...r, op: "edit", inputs: { ...r.inputs, images: [...(r.inputs?.images ?? []), ...take] }, prompt: join(r.prompt, styleLegend(existing + 1, existing + take.length)) };
+ }
+ } else if (mb.loraHandle && (model.id === SIGNATURE_MODELS.openTurbo || model.family !== "style-reference")) {
+ move(SIGNATURE_MODELS.openTurbo, `Runs on {model} with “${mb.name}”'s trained style LoRA`);
+ r = { ...r, prompt: join(r.prompt, `In the style of @${mb.loraHandle}.`) };
+ } else {
+ if (model.family !== "style-reference") move(SIGNATURE_MODELS.openStyle, `Runs on {model} with “${mb.name}”'s collages`);
+ const max = model.options.maxImages ?? 2;
+ const pool = max >= 4 ? refs : collages;
+ const take = pool.slice(0, Math.max(0, max - existing));
+ if (!take.length) return { request: req, modelId: req.modelId, notes, blocker: "Remove a reference image to make room for the moodboard" };
+ r = { ...r, op: undefined, inputs: { ...r.inputs, images: [...(r.inputs?.images ?? []), ...take] } };
+ }
+ styled = true;
+ }
+ }
+
+ const pal = sig.palette;
+ let lock: SignedRequest["lock"];
+ if (pal?.colors.length) {
+ const all = paletteColors(pal);
+ const native = ctx.caps.native[model.id];
+ if (!native && model.engine === "open" && model.id === SIGNATURE_MODELS.openTurbo && !styled && !(r.inputs?.images?.length) && !r.loras?.length) {
+ move(SIGNATURE_MODELS.openPalette, `Runs on {model}: your colours in the prompt, then locked in with a colour transfer`);
+ }
+ const nativeNow = ctx.caps.native[model.id];
+ if (nativeNow) {
+ const colors = cardStrip({ colors: pal.colors, background: null });
+ if (colors.length > nativeNow.max) notes.push(`${model.name} takes ${nativeNow.max} colours — the first ${nativeNow.max} are used`);
+ r = { ...r, params: { ...r.params, palette: colors.slice(0, nativeNow.max) } };
+ if (pal.background && nativeNow.background) r = setExtra(r, nativeNow.background, pal.background.toUpperCase());
+ } else if (model.id === SIGNATURE_MODELS.openPalette) {
+ r = { ...r, params: { ...r.params, palette: all } };
+ } else if (model.id === SIGNATURE_MODELS.cinema && pal.slug) {
+ r = setExtra(r, "color_palette", pal.slug);
+ } else {
+ r = { ...r, prompt: join(r.prompt, palettePrompt(pal)), params: { ...r.params, palette: all.slice(0, 16) } };
+ if (model.engine === "open" && pal.lock) lock = { colors: all };
+ }
+ }
+ return { request: r, modelId: model.id, notes, ...(lock && { lock }) };
+}
diff --git a/src/lib/studio-catalog.ts b/src/lib/studio-catalog.ts
index 06f0dfe4..b4b4eacc 100644
--- a/src/lib/studio-catalog.ts
+++ b/src/lib/studio-catalog.ts
@@ -25,10 +25,10 @@ export function slimModel(m: ModelDef): ModelDef {
};
}
-export function studioCatalog(config: Pick<StudioConfig, "kind" | "ops" | "pickerOps" | "defaultModels" | "preset">): StudioCatalog {
+export function studioCatalog(config: Pick<StudioConfig, "kind" | "ops" | "pickerOps" | "defaultModels" | "preset" | "extraModels">): StudioCatalog {
const list = modelsFor({ kind: config.kind, ops: config.pickerOps ?? config.ops });
const ids = new Set(list.map((m) => m.id));
- const extra = [config.defaultModels.cloud, config.defaultModels.open, config.preset?.cloud?.modelId, config.preset?.open?.modelId]
+ const extra = [config.defaultModels.cloud, config.defaultModels.open, config.preset?.cloud?.modelId, config.preset?.open?.modelId, ...(config.extraModels ?? [])]
.filter((id): id is string => !!id && !ids.has(id))
.map((id) => getModel(id))
.filter((m): m is ModelDef => !!m);
diff --git a/src/lib/studios.ts b/src/lib/studios.ts
index 70476e68..01cc373d 100644
--- a/src/lib/studios.ts
+++ b/src/lib/studios.ts
@@ -1,4 +1,5 @@
import { getModel } from "@/lib/catalog";
+import { SIGNATURE_MODELS } from "@/lib/catalog/palettes";
import type { Preset } from "@/lib/catalog/types";
import type { StudioConfig } from "@/components/studio/studio-context";
@@ -16,6 +17,9 @@ export const IMAGE_STUDIO: StudioConfig = {
slots: [],
multiRef: { label: "Add ref", max: 8 },
defaultModels: { cloud: "nano-banana-pro", open: "oss-z-image-turbo" },
+ // Color signature + Moodboard chips, and the models they can move a request to.
+ signature: true,
+ extraModels: Object.values(SIGNATURE_MODELS),
suggestions: [
"Editorial portrait of a woman in a yellow raincoat, Tokyo crosswalk at dusk, 35mm film",
"Isometric cozy reading nook with plants and warm lamp light, 3D render",
diff --git a/src/server/db.ts b/src/server/db.ts
index 73575c8d..76b1cb7e 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -175,6 +175,43 @@ const MIGRATIONS: string[] = [
edited_at INTEGER
);
CREATE INDEX IF NOT EXISTS canvases_updated ON canvases(updated_at DESC);`,
+ // Image studios: colour signatures (Soul HEX; the 50 Cinema Studio palettes are seeded on first use), moodboards
+ // (reference sets with their cover job, Recraft style id and optional style LoRA element) and Instadump user packs.
+ `CREATE TABLE IF NOT EXISTS palettes (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ colors_json TEXT NOT NULL,
+ background TEXT,
+ slug TEXT,
+ source TEXT NOT NULL DEFAULT 'manual',
+ thumb_url TEXT,
+ position INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS palettes_source ON palettes(source, created_at DESC);
+ CREATE TABLE IF NOT EXISTS moodboards (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ images_json TEXT NOT NULL,
+ collages_json TEXT NOT NULL DEFAULT '[]',
+ engine TEXT NOT NULL,
+ generation_id TEXT,
+ status TEXT NOT NULL DEFAULT 'queued',
+ cover_url TEXT,
+ style_id TEXT,
+ element_id TEXT,
+ error TEXT,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS moodboards_created ON moodboards(created_at DESC);
+ CREATE TABLE IF NOT EXISTS photodump_packs (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ refs_json TEXT NOT NULL,
+ created_at INTEGER NOT NULL
+ );`,
];
declare global {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index e5034312..ac8640fc 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -208,6 +208,10 @@ const ASSET_REFS: { table: string; cols: string[]; except?: string }[] = [
{ table: "cinema_projects", cols: ["cover_url", "palettes_json", "director_json", "chat_json", "brief_body"] },
{ table: "cinema_items", cols: ["meta_json"], except: "generation_id" },
{ table: "canvases", cols: ["graph_json"] },
+ // Image studios: a palette's thumbnail, a moodboard's images, collages and cover, an Instadump pack's photos.
+ { table: "palettes", cols: ["thumb_url"] },
+ { table: "moodboards", cols: ["images_json", "collages_json", "cover_url"] },
+ { table: "photodump_packs", cols: ["refs_json"] },
];
/** Whether anything still refers to this stored file (see ASSET_REFS). */
diff --git a/src/server/moodboards.ts b/src/server/moodboards.ts
new file mode 100644
index 00000000..a8c56433
--- /dev/null
+++ b/src/server/moodboards.ts
@@ -0,0 +1,202 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { CURATED_MOODBOARDS, hueOf } from "@/lib/catalog/packs";
+import type { Engine, Generation } from "@/lib/catalog/types";
+import { COVER_PROMPT, MOODBOARD_LIMITS, moodboardStatus, moodboardError, type Moodboard } from "@/components/moodboards/logic";
+import { db } from "./db";
+import { createElement, getElement } from "./elements";
+import { createGenerations, getGeneration } from "./generations";
+import { engineMode } from "./settings";
+import { startTraining } from "./training";
+
+/**
+ * Moodboards (Soul 2.0's "presets evolved"): a named set of 5–80 reference images in one style.
+ *
+ * Making one starts a cover job, which is also what makes the board usable on the cloud: Recraft V4
+ * Styles turns the 10 most representative images into a reusable style (its id comes back in
+ * meta.styleId) while drawing the cover; on the open engine Qwen-Image-Edit Style Reference draws
+ * the cover from the board's collages. The status follows that job: In queue → In progress →
+ * Preparing cover → Complete (or Failed, with Retry). A board can also train a Z-Image Turbo style
+ * LoRA through the existing AI-Toolkit path (a style element), which then wins on the open engine.
+ */
+
+interface Row {
+ id: string;
+ name: string;
+ images_json: string;
+ collages_json: string;
+ engine: Engine;
+ generation_id: string | null;
+ status: string;
+ cover_url: string | null;
+ style_id: string | null;
+ element_id: string | null;
+ error: string | null;
+ created_at: number;
+ updated_at: number;
+}
+
+/** The model that prepares a board (and draws its cover) on each engine. */
+export const PREP_MODEL: Record<Engine, string> = { cloud: "recraft-4-style", open: "oss-style-qwen-edit" };
+
+function toMoodboard(r: Row): Moodboard {
+ const images = JSON.parse(r.images_json) as string[];
+ const el = r.element_id ? getElement(r.element_id) : null;
+ const lora = el?.loras.find((l) => l.modelId === "oss-z-image-turbo" && l.engine === "open");
+ return {
+ id: r.id,
+ name: r.name,
+ images,
+ refs: images.slice(0, MOODBOARD_LIMITS.refs),
+ collages: JSON.parse(r.collages_json) as string[],
+ engine: r.engine,
+ status: r.status as Moodboard["status"],
+ cover: r.cover_url ?? images[0] ?? null,
+ styleId: r.style_id,
+ error: r.error,
+ generationId: r.generation_id,
+ lora: el ? { elementId: el.id, handle: el.handle, status: lora ? "ready" : el.status === "training" ? "training" : el.status === "failed" ? "failed" : "none" } : null,
+ createdAt: r.created_at,
+ };
+}
+
+function update(id: string, fields: Partial<Row>) {
+ const keys = Object.keys(fields);
+ if (!keys.length) return;
+ db()
+ .prepare(`UPDATE moodboards SET ${keys.map((k) => `${k} = @${k}`).join(", ")}, updated_at = @__now WHERE id = @__id`)
+ .run({ ...fields, __now: Date.now(), __id: id });
+}
+
+/** Follow the cover job: live status while it runs, and the cover + style id once it's done (saved then). */
+function settle(r: Row): Row {
+ if (r.status === "complete" || r.status === "failed") return r;
+ const g: Generation | null = r.generation_id ? getGeneration(r.generation_id, { includeDeleted: true }) : null;
+ const next = moodboardStatus(g);
+ if (next.status === "complete") {
+ const out = g?.outputs.find((o) => o.kind === "image");
+ // A demo run draws a placeholder and makes no real style: keep the first image as the cover then.
+ const real = g && g.provider !== "mock";
+ const styleId = real && typeof out?.meta?.styleId === "string" ? out.meta.styleId : null;
+ const fields = { status: "complete", cover_url: real && out ? out.url : null, style_id: styleId, error: null };
+ update(r.id, fields);
+ return { ...r, ...fields };
+ }
+ if (next.status === "failed") {
+ const fields = { status: "failed", error: next.error ?? "The cover job didn't finish" };
+ update(r.id, fields);
+ return { ...r, ...fields };
+ }
+ return { ...r, status: next.status };
+}
+
+export function listMoodboards(): Moodboard[] {
+ const rows = db().prepare("SELECT * FROM moodboards ORDER BY created_at DESC").all() as Row[];
+ return rows.map(settle).map(toMoodboard);
+}
+
+export function getMoodboard(id: string): Moodboard | null {
+ const r = db().prepare("SELECT * FROM moodboards WHERE id = ?").get(id) as Row | undefined;
+ return r ? toMoodboard(settle(r)) : null;
+}
+
+/** Soul 2.0's 33 built-in looks, for the Curated tab. */
+export function curatedMoodboards() {
+ return CURATED_MOODBOARDS.map((p) => ({ id: p.id, name: p.name, category: p.categories[0] ?? "All presets", description: p.description, hue: hueOf(p.id) }));
+}
+
+/** The engine a board is prepared on: the one asked for, unless Settings locks the other. */
+function prepEngine(asked: Engine): Engine {
+ const mode = engineMode();
+ return mode === "both" ? asked : mode;
+}
+
+/** Start (or restart) the cover job. Errors land on the board as Failed. */
+function startPrep(id: string, name: string, images: string[], collages: string[], engine: Engine): void {
+ const refs = images.slice(0, MOODBOARD_LIMITS.refs);
+ try {
+ const [g] = createGenerations({
+ feature: "moodboard",
+ modelId: PREP_MODEL[engine],
+ ...(engine === "cloud" ? { op: "edit" as const } : {}),
+ prompt: COVER_PROMPT(name),
+ inputs: { images: engine === "cloud" ? refs : (collages.length ? collages : refs).slice(0, 2) },
+ params: { aspectRatio: "1:1", numOutputs: 1 },
+ title: `Moodboard cover · ${name}`,
+ });
+ update(id, { generation_id: g.id, status: "queued", error: null, cover_url: null, style_id: null, engine });
+ } catch (e) {
+ update(id, { status: "failed", error: (e as Error).message });
+ }
+}
+
+export function createMoodboard(input: { name: string; images: string[]; collages?: string[]; engine: Engine }): Moodboard {
+ const images = [...new Set(input.images)];
+ const err = moodboardError({ name: input.name, images });
+ if (err) throw new Error(err);
+ const now = Date.now();
+ const engine = prepEngine(input.engine);
+ const row: Row = {
+ id: nanoid(10),
+ name: input.name.trim(),
+ images_json: JSON.stringify(images),
+ collages_json: JSON.stringify((input.collages ?? []).slice(0, 2)),
+ engine,
+ generation_id: null,
+ status: "queued",
+ cover_url: null,
+ style_id: null,
+ element_id: null,
+ error: null,
+ created_at: now,
+ updated_at: now,
+ };
+ db()
+ .prepare(`INSERT INTO moodboards (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
+ .run(row);
+ startPrep(row.id, row.name, images, JSON.parse(row.collages_json), engine);
+ return getMoodboard(row.id)!;
+}
+
+/** Retry a failed board (optionally on the other engine). */
+export function retryMoodboard(id: string, engine?: Engine): Moodboard {
+ const m = getMoodboard(id);
+ if (!m) throw new Error("Moodboard not found");
+ if (m.status !== "failed" && m.status !== "complete") throw new Error("This moodboard is still training. Try again once it is ready.");
+ startPrep(id, m.name, m.images, m.collages, prepEngine(engine ?? m.engine));
+ return getMoodboard(id)!;
+}
+
+export function renameMoodboard(id: string, name: string): Moodboard {
+ const m = getMoodboard(id);
+ if (!m) throw new Error("Moodboard not found");
+ const err = moodboardError({ name, images: m.images });
+ if (err) throw new Error(err);
+ update(id, { name: name.trim() });
+ return getMoodboard(id)!;
+}
+
+export function deleteMoodboard(id: string): boolean {
+ return db().prepare("DELETE FROM moodboards WHERE id = ?").run(id).changes > 0;
+}
+
+/**
+ * Train a persistent open-source style: a style element with the board's 20 most representative
+ * images, trained as a Z-Image Turbo LoRA on AI-Toolkit (the same path as character LoRAs).
+ */
+export function trainMoodboard(id: string): Moodboard {
+ const m = getMoodboard(id);
+ if (!m) throw new Error("Moodboard not found");
+ if (m.status !== "complete") throw new Error("This moodboard is still training. Try again once it is ready.");
+ let el = m.lora ? getElement(m.lora.elementId) : null;
+ if (!el) {
+ el = createElement({ name: m.name.slice(0, 60), kind: "style", description: `the visual style of the “${m.name}” moodboard`, references: m.images.slice(0, 20) });
+ update(id, { element_id: el.id });
+ }
+ try {
+ startTraining(el.id, "aitk-z-image");
+ } catch (e) {
+ throw new Error((e as Error).message);
+ }
+ return getMoodboard(id)!;
+}
diff --git a/src/server/palettes.ts b/src/server/palettes.ts
new file mode 100644
index 00000000..7040a62c
--- /dev/null
+++ b/src/server/palettes.ts
@@ -0,0 +1,171 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { MODELS } from "@/lib/catalog";
+import { PALETTES as CINEMA_PALETTES } from "@/lib/catalog/cinema";
+import { MAX_COLORS_RECRAFT, MAX_COLORS, normalizeHex, paletteError, type Palette, type PaletteSource, type SignatureCaps } from "@/lib/catalog/palettes";
+import type { GenerationRequest } from "@/lib/catalog/types";
+import { createPipeline } from "./chains";
+import { db } from "./db";
+
+/**
+ * Colour signatures: the user's palettes plus the 50 Cinema Studio 4.0 palettes (seeded once, so the
+ * library is shared with Cinema Studio's colour grades and its slugs stay valid for cinema-studio-4).
+ */
+
+interface Row {
+ id: string;
+ name: string;
+ colors_json: string;
+ background: string | null;
+ slug: string | null;
+ source: PaletteSource;
+ thumb_url: string | null;
+ position: number;
+ created_at: number;
+ updated_at: number;
+}
+
+const toPalette = (r: Row): Palette => ({
+ id: r.id,
+ name: r.name,
+ colors: JSON.parse(r.colors_json) as string[],
+ background: r.background,
+ slug: r.slug,
+ source: r.source,
+ thumb: r.thumb_url,
+ createdAt: r.created_at,
+});
+
+/** The built-ins as rows: Cinema Studio's 12 colours, the 12th also the background (Higgsfield's shape). */
+export function builtinPalettes(): Omit<Palette, "createdAt">[] {
+ return CINEMA_PALETTES.map((p) => {
+ const colors = p.hex.map((h) => normalizeHex(h)!);
+ return { id: `builtin-${p.slug}`, name: p.name, colors, background: colors[colors.length - 1], slug: p.slug, source: "builtin" as const, thumb: null };
+ });
+}
+
+declare global {
+ var __fuobePalettesSeeded: boolean | undefined;
+}
+
+/** Seed (or top up) the built-in palettes; cheap after the first call in a process. */
+function ensureBuiltins(): void {
+ if (globalThis.__fuobePalettesSeeded) return;
+ const now = Date.now();
+ const insert = db().prepare(
+ `INSERT OR IGNORE INTO palettes (id, name, colors_json, background, slug, source, thumb_url, position, created_at, updated_at)
+ VALUES (@id, @name, @colors_json, @background, @slug, 'builtin', NULL, @position, @now, @now)`,
+ );
+ db().transaction(() => {
+ builtinPalettes().forEach((p, i) => insert.run({ id: p.id, name: p.name, colors_json: JSON.stringify(p.colors), background: p.background, slug: p.slug, position: i, now }));
+ })();
+ globalThis.__fuobePalettesSeeded = true;
+}
+
+/** Your palettes (newest first), then the built-ins in Cinema Studio's order. */
+export function listPalettes(): Palette[] {
+ ensureBuiltins();
+ const rows = db().prepare("SELECT * FROM palettes ORDER BY CASE source WHEN 'builtin' THEN 1 ELSE 0 END, CASE source WHEN 'builtin' THEN position ELSE -created_at END").all() as Row[];
+ return rows.map(toPalette);
+}
+
+export function getPalette(id: string): Palette | null {
+ ensureBuiltins();
+ const r = db().prepare("SELECT * FROM palettes WHERE id = ?").get(id) as Row | undefined;
+ return r ? toPalette(r) : null;
+}
+
+export function createPalette(input: { name: string; colors: string[]; background?: string | null; source?: "manual" | "images"; thumb?: string | null }): Palette {
+ const colors = input.colors.map((c) => normalizeHex(c)).filter((c): c is string => !!c);
+ const background = input.background ? normalizeHex(input.background) : null;
+ if (colors.length !== input.colors.length) throw new Error(`${input.colors.find((c) => !normalizeHex(c))} isn't a colour — use #RRGGBB`);
+ const err = paletteError({ name: input.name, colors, background });
+ if (err) throw new Error(err);
+ const now = Date.now();
+ const row: Row = {
+ id: nanoid(10),
+ name: input.name.trim(),
+ colors_json: JSON.stringify(colors),
+ background,
+ slug: null,
+ source: input.source ?? "manual",
+ thumb_url: input.thumb ?? null,
+ position: 0,
+ created_at: now,
+ updated_at: now,
+ };
+ db()
+ .prepare(
+ `INSERT INTO palettes (id, name, colors_json, background, slug, source, thumb_url, position, created_at, updated_at)
+ VALUES (@id, @name, @colors_json, @background, @slug, @source, @thumb_url, @position, @created_at, @updated_at)`,
+ )
+ .run(row);
+ return toPalette(row);
+}
+
+export function renamePalette(id: string, name: string): Palette {
+ const cur = getPalette(id);
+ if (!cur) throw new Error("Palette not found");
+ if (cur.source === "builtin") throw new Error("Built-in palettes can't be renamed");
+ const err = paletteError({ name, colors: cur.colors });
+ if (err) throw new Error(err);
+ db().prepare("UPDATE palettes SET name = ?, updated_at = ? WHERE id = ?").run(name.trim(), Date.now(), id);
+ return getPalette(id)!;
+}
+
+/** Delete one of your palettes (built-ins stay). Returns false when there was none. */
+export function deletePalette(id: string): boolean {
+ const cur = getPalette(id);
+ if (!cur) return false;
+ if (cur.source === "builtin") throw new Error("Built-in palettes can't be deleted");
+ db().prepare("DELETE FROM palettes WHERE id = ?").run(id);
+ return true;
+}
+
+/** Which models take a palette natively, how many colours, and their background field (from the field maps). */
+export function signatureCaps(): SignatureCaps {
+ const native: SignatureCaps["native"] = {};
+ for (const m of MODELS) {
+ const maps = m.routes.map((r) => r.map?.palette).filter((p): p is NonNullable<typeof p> => !!p);
+ if (!maps.length) continue;
+ native[m.id] = { max: m.family === "recraft" ? MAX_COLORS_RECRAFT : MAX_COLORS, ...(maps.every((p) => p.background) && { background: maps[0].background }) };
+ }
+ return { native };
+}
+
+/**
+ * The open palette lock: each image the request makes is recoloured to the palette afterwards by
+ * oss-palette-image (a colour transfer to a swatch rendered from the hex list). One two-step chain
+ * per image, all in one batch.
+ */
+export function createLockedRun(request: GenerationRequest, colors: string[], strength = 0.8) {
+ const hex = colors.map((c) => normalizeHex(c)).filter((c): c is string => !!c);
+ if (!hex.length) throw new Error("Pick a palette first");
+ const n = Math.max(1, Math.min(4, request.params?.numOutputs ?? 1));
+ const batchId = nanoid(10);
+ const items = [];
+ for (let i = 0; i < n; i++) {
+ const step = n > 1 ? { label: `Image ${i + 1} of ${n}`, index: i, of: n } : undefined;
+ const { items: made } = createPipeline(
+ [
+ { key: "image", request: { ...request, params: { ...request.params, numOutputs: 1 }, ...(step && { step }) } },
+ {
+ key: "lock",
+ request: {
+ feature: request.feature,
+ modelId: "oss-palette-image",
+ op: "color-match",
+ prompt: "Palette lock",
+ params: { palette: hex, extra: { strength } },
+ step: { label: n > 1 ? `Palette lock ${i + 1} of ${n}` : "Palette lock", index: i, of: n },
+ },
+ after: "image",
+ chain: [{ slot: "images", position: "first" }],
+ },
+ ],
+ { batchId },
+ );
+ items.push(...made);
+ }
+ return { batchId, items };
+}
diff --git a/src/server/photodump.ts b/src/server/photodump.ts
new file mode 100644
index 00000000..73a6e9dc
--- /dev/null
+++ b/src/server/photodump.ts
@@ -0,0 +1,270 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { getModel } from "@/lib/catalog";
+import { castPrompt, type CastValues } from "@/lib/catalog/cinema";
+import {
+ castSheetModel,
+ customPack,
+ fashionBaseRequest,
+ fashionOutfitRequest,
+ fashionPhotosetRequests,
+ getPack,
+ getTemplate,
+ MAX_PACK_REFS,
+ planPhotodump,
+ sheetFromReference,
+ type Pack,
+ type PhotoSubject,
+ type PlanCaps,
+} from "@/lib/catalog/packs";
+import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
+import { createPipeline } from "./chains";
+import { db } from "./db";
+import { getElement } from "./elements";
+import { createGenerations, previewGeneration } from "./generations";
+import { higgsfieldKey } from "./providers/higgsfield";
+import { engineMode } from "./settings";
+
+/**
+ * Photodump / Instadump, Fashion Factory and Character Sheet runs: plan with the pure pack logic
+ * (src/lib/catalog/packs.ts), validate every request, then create them as one batch so the feed and
+ * the Library stack them under the run's name.
+ */
+
+// ---------------------------------------------------------------------------
+// User packs (Instadump "Create pack")
+
+interface PackRow {
+ id: string;
+ name: string;
+ refs_json: string;
+ created_at: number;
+}
+
+export interface UserPack {
+ id: string;
+ name: string;
+ refs: string[];
+ createdAt: number;
+}
+
+const toPack = (r: PackRow): UserPack => ({ id: r.id, name: r.name, refs: JSON.parse(r.refs_json) as string[], createdAt: r.created_at });
+
+export function listUserPacks(): UserPack[] {
+ return (db().prepare("SELECT * FROM photodump_packs ORDER BY created_at DESC").all() as PackRow[]).map(toPack);
+}
+
+export function getUserPack(id: string): UserPack | null {
+ const r = db().prepare("SELECT * FROM photodump_packs WHERE id = ?").get(id) as PackRow | undefined;
+ return r ? toPack(r) : null;
+}
+
+export function createUserPack(input: { name: string; refs: string[] }): UserPack {
+ const name = input.name.trim();
+ if (!name) throw new Error("Give the pack a name");
+ if (name.length > 60) throw new Error("Keep the pack name under 60 characters");
+ const refs = [...new Set(input.refs)];
+ if (!refs.length) throw new Error("Upload your reference set up to 15 photos");
+ if (refs.length > MAX_PACK_REFS) throw new Error(`A pack holds up to ${MAX_PACK_REFS} photos`);
+ const row: PackRow = { id: `user-${nanoid(8)}`, name, refs_json: JSON.stringify(refs), created_at: Date.now() };
+ db().prepare("INSERT INTO photodump_packs (id, name, refs_json, created_at) VALUES (@id, @name, @refs_json, @created_at)").run(row);
+ return toPack(row);
+}
+
+export function deleteUserPack(id: string): boolean {
+ return db().prepare("DELETE FROM photodump_packs WHERE id = ?").run(id).changes > 0;
+}
+
+// ---------------------------------------------------------------------------
+// Planning helpers
+
+/** What this install can do, for the pure planners. */
+export function planCaps(): PlanCaps {
+ return { higgsfield: !!higgsfieldKey() && engineMode() !== "open", has: (id) => !!getModel(id) };
+}
+
+/** The engine a run uses: the one asked for, unless Settings locks the other. */
+export function runEngine(asked: Engine): Engine {
+ const mode = engineMode();
+ return mode === "both" ? asked : mode;
+}
+
+export function subjectFor(input: { elementId?: string; selfie?: string }): PhotoSubject {
+ if (input.elementId) {
+ const el = getElement(input.elementId);
+ if (!el) throw new Error("That character no longer exists");
+ if (el.kind !== "character") throw new Error(`${el.name} isn't a character`);
+ return { kind: "element", handle: el.handle, name: el.name, references: el.references.filter((r) => !/\.(wav|mp3|ogg|flac|m4a|webm)$/i.test(r)), loras: el.loras };
+ }
+ if (input.selfie) return { kind: "selfie", url: input.selfie };
+ throw new Error("Pick a character or add a selfie");
+}
+
+export function packFor(id: string): Pack {
+ const builtIn = getPack(id);
+ if (builtIn) return builtIn;
+ const user = getUserPack(id);
+ if (user) return customPack(user);
+ throw new Error("That pack no longer exists");
+}
+
+/** The closest aspect ratio the model offers (by value), or the request's own when the model doesn't list any. */
+export function fitAspect(modelId: string, aspect: string | undefined): string | undefined {
+ const opts = getModel(modelId)?.options.aspectRatios;
+ if (!aspect || !opts?.length || opts.includes(aspect)) return aspect;
+ const val = (a: string) => {
+ const [w, h] = a.split(":").map(Number);
+ return w && h ? Math.log(w / h) : NaN;
+ };
+ const want = val(aspect);
+ const best = opts.filter((o) => Number.isFinite(val(o))).sort((a, b) => Math.abs(val(a) - want) - Math.abs(val(b) - want))[0];
+ return best ?? undefined;
+}
+
+const fitted = (r: GenerationRequest): GenerationRequest => ({ ...r, params: { ...r.params, aspectRatio: fitAspect(r.modelId, r.params?.aspectRatio) } });
+
+/** Price a set of requests without starting them (the first error is returned, not thrown). */
+export function previewRun(requests: GenerationRequest[], notes: string[] = []) {
+ try {
+ const previews = requests.map((r) => previewGeneration(fitted(r)));
+ const first = previews[0];
+ const costs = previews.map((p) => p.costUsd);
+ return {
+ modelId: first.model.id,
+ modelName: first.model.name,
+ count: previews.reduce((n, p) => n + p.outputs, 0),
+ costUsd: costs.some((c) => c === null) ? null : Math.round(costs.reduce((a, b) => a! + b!, 0)! * 1000) / 1000,
+ demo: previews.some((p) => p.demo),
+ notes,
+ };
+ } catch (e) {
+ return { error: (e as Error).message, notes };
+ }
+}
+
+/**
+ * Independent requests created as one batch (validated together first, so a bad one starts nothing,
+ * and a demo/real mix is refused), stacked in the Library under `title`.
+ */
+export function createBatch(requests: GenerationRequest[], title: string): { batchId: string; items: Generation[] } {
+ if (!requests.length) throw new Error("Nothing to make");
+ const { batchId, items } = createPipeline(requests.map((r, i) => ({ key: `p${i}`, request: { ...fitted(r), batchTitle: title } })));
+ return { batchId, items };
+}
+
+// ---------------------------------------------------------------------------
+// Photodump
+
+export interface PhotodumpRun {
+ packId: string;
+ engine: Engine;
+ elementId?: string;
+ selfie?: string;
+ aspectRatio?: string;
+ modelId?: string;
+}
+
+function photodumpPlan(input: PhotodumpRun) {
+ const pack = packFor(input.packId);
+ const subject = subjectFor(input);
+ return { pack, subject, plan: planPhotodump({ pack, subject, engine: runEngine(input.engine), aspectRatio: input.aspectRatio, modelId: input.modelId }, planCaps()) };
+}
+
+export function previewPhotodump(input: PhotodumpRun) {
+ try {
+ const { plan } = photodumpPlan(input);
+ return previewRun(plan.requests, plan.notes);
+ } catch (e) {
+ return { error: (e as Error).message, notes: [] };
+ }
+}
+
+export function createPhotodump(input: PhotodumpRun) {
+ const { pack, subject, plan } = photodumpPlan(input);
+ const who = subject.kind === "element" ? subject.name : "Selfie";
+ const { batchId, items } = createBatch(plan.requests, `${pack.name} · ${who}`);
+ return { batchId, items, notes: plan.notes, modelId: plan.modelId };
+}
+
+// ---------------------------------------------------------------------------
+// Fashion Factory
+
+export type FashionRun =
+ | { step: "base"; templateId: string; elementId: string; engine: Engine }
+ | { step: "outfit"; templateId: string; base: string; garment: string; engine: Engine; modelId?: string }
+ | { step: "photoset"; templateId: string; dressed: string; engine: Engine };
+
+function fashionRequests(input: FashionRun): { requests: GenerationRequest[]; title: string } {
+ const t = getTemplate(input.templateId);
+ if (!t) throw new Error("Template required");
+ const engine = runEngine(input.engine);
+ if (input.step === "base") {
+ const subject = subjectFor({ elementId: input.elementId });
+ if (subject.kind !== "element") throw new Error("Pick or create a character first");
+ return { requests: [fashionBaseRequest(t, subject, engine, planCaps())], title: `${t.name} · ${subject.name}` };
+ }
+ if (input.step === "outfit") return { requests: [fashionOutfitRequest(t, input.base, input.garment, engine, input.modelId)], title: `${t.name} · outfit` };
+ return { requests: fashionPhotosetRequests(t, input.dressed, engine), title: `${t.name} · photoset` };
+}
+
+export function previewFashion(input: FashionRun) {
+ try {
+ return previewRun(fashionRequests(input).requests);
+ } catch (e) {
+ return { error: (e as Error).message, notes: [] };
+ }
+}
+
+export function createFashion(input: FashionRun) {
+ const { requests, title } = fashionRequests(input);
+ if (requests.length === 1) {
+ // One request (base shots ×4, outfit ×2): the generations share a batch on their own.
+ const items = createGenerations({ ...fitted(requests[0]), batchTitle: title });
+ return { batchId: items[0]?.batchId ?? items[0]?.id, items };
+ }
+ return createBatch(requests, title);
+}
+
+// ---------------------------------------------------------------------------
+// Character Sheet
+
+export type SheetRun =
+ | { mode: "reference"; engine: Engine; images: string[]; details?: string }
+ | { mode: "cast"; engine: Engine; cast: CastValues; details?: string }
+ | { mode: "describe"; engine: Engine; prompt: string };
+
+function sheetRequest(input: SheetRun): { request: GenerationRequest; notes: string[] } {
+ const engine = runEngine(input.engine);
+ if (input.mode === "reference") return sheetFromReference(input.images, engine, input.details);
+ if (input.mode === "cast") {
+ const modelId = castSheetModel(engine, planCaps());
+ const m = getModel(modelId);
+ const aspect = m?.options.aspectRatios?.includes("16:9") ? "16:9" : undefined;
+ const resolution = m?.options.resolutions?.includes("2K") ? "2K" : m?.options.resolutions?.includes("1080p") ? "1080p" : undefined;
+ return {
+ request: { feature: "character-sheet", modelId, prompt: castPrompt(input.cast, input.details), params: { numOutputs: 1, ...(aspect && { aspectRatio: aspect }), ...(resolution && { resolution }) } },
+ notes: modelId === "nano-banana-pro" ? ["Soul 2.0 needs a Higgsfield key — Nano Banana Pro draws the sheet"] : [],
+ };
+ }
+ // A description: the AI Influencer app (Higgsfield's character-sheet model, or Z-Image Turbo).
+ if (!input.prompt.trim()) throw new Error("Describe your character first");
+ return {
+ request: { feature: "app:app-ai-influencer", presetId: "app-ai-influencer", modelId: engine === "open" ? "oss-z-image-turbo" : "ai-influencer", prompt: input.prompt.trim() },
+ notes: [],
+ };
+}
+
+export function previewSheet(input: SheetRun) {
+ try {
+ const { request, notes } = sheetRequest(input);
+ return previewRun([request], notes);
+ } catch (e) {
+ return { error: (e as Error).message, notes: [] };
+ }
+}
+
+export function createSheet(input: SheetRun) {
+ const { request, notes } = sheetRequest(input);
+ const items = createGenerations(fitted({ ...request, title: "Character sheet" }));
+ return { items, notes };
+}