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.

Originals O3: Fuobe Soul ID targets on open weights, a LoRA per family on both engines

Claude135f32cc04a8
diff --git a/package.json b/package.json
index a2642a59..cbb49b56 100644
--- a/package.json
+++ b/package.json
@@ -16,7 +16,7 @@
"test:e2e:library": "node tests/e2e/library-flows.mjs",
"test:e2e:mobile": "node tests/e2e/no-horizontal-scroll.mjs",
"test:e2e:shell": "node tests/e2e/shell.mjs",
- "gen:catalog": "python3 scripts/gen-cloud-models.py && python3 scripts/gen-higgsfield-models.py && python3 scripts/gen-higgsfield-presets.py && python3 scripts/gen-oss-loras.py && python3 scripts/gen-lora-library.py && python3 scripts/gen-influencer-options.py && python3 scripts/gen-soul-originals.py && node scripts/gen-icon-map.mjs",
+ "gen:catalog": "python3 scripts/gen-cloud-models.py && python3 scripts/gen-higgsfield-models.py && python3 scripts/gen-higgsfield-presets.py && python3 scripts/gen-oss-loras.py && python3 scripts/gen-lora-library.py && python3 scripts/gen-influencer-options.py && python3 scripts/gen-soul-originals.py && python3 scripts/gen-trainers.py && node scripts/gen-icon-map.mjs",
"typecheck": "tsc --noEmit",
"eval:run": "node scripts/eval/eval.mjs run",
"eval:report": "node scripts/eval/eval.mjs report",
diff --git a/scripts/gen-trainers.py b/scripts/gen-trainers.py
new file mode 100644
index 00000000..25ca9dee
--- /dev/null
+++ b/scripts/gen-trainers.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python3
+"""
+Generate src/lib/catalog/trainers.generated.ts: the hosted LoRA trainers Fuobe Soul ID and personal moodboards
+can run in the cloud (build plan O3), with each one's request fields, its price per step and the licence of the
+weights it trains on.
+Source: docs/research/fuobe-originals-recipes-5.json → trainers[] (read from fal's OpenAPI and llms.txt).
+
+Only fal's image trainers are generated (their data is a zip of 001.jpg + 001.txt caption pairs in
+`image_data_url`): video trainers (Wan, LTX) and Replicate's GPU-time trainers aren't Soul ID routes.
+src/lib/catalog/training.ts turns a training target into a request with these fields, so nothing about a
+trainer's API is typed by hand.
+
+Fails (exit 1) when a trainer Fuobe's targets use (USED below):
+- trains on weights that aren't commercial (a default must be commercial-safe), or isn't active / served;
+- lacks a field its request sends (steps, default_caption, learning_rate; training_type for a style trainer);
+- has a price this script can't read (the spend shown before a run, and the eval harness's cap, need it).
+
+Run: python3 scripts/gen-trainers.py
+"""
+import json
+import re
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+DATA = json.loads((ROOT / "docs/research/fuobe-originals-recipes-5.json").read_text(encoding="utf-8"))
+OUT = ROOT / "src/lib/catalog/trainers.generated.ts"
+
+# The trainers src/lib/catalog/training.ts uses, and the fields each request sends.
+USED = {
+ "fal-ai/z-image-turbo-trainer-v2": ["steps", "default_caption", "learning_rate"],
+ "fal-ai/z-image-trainer": ["steps", "default_caption", "learning_rate", "training_type"],
+ "fal-ai/qwen-image-2512-trainer": ["steps", "default_caption", "learning_rate"],
+}
+errors = []
+
+
+def slug(s):
+ """'Z-Image Turbo' → 'z-image-turbo', 'Z-Image (base)' → 'z-image', 'Qwen-Image 2512' → 'qwen-image-2512'."""
+ s = re.sub(r"\(base\)", "", s, flags=re.I)
+ return re.sub(r"^-|-$", "", re.sub(r"[^a-z0-9]+", "-", s.lower()))
+
+
+def num(s):
+ v = float(s.replace(",", ""))
+ return int(v) if v.is_integer() else v
+
+
+def field(spec):
+ """'integer default=2000 minimum=10 maximum=40000' → {type, default, min, max}; enums kept."""
+ parts = spec.split(" ", 1)
+ out = {"type": parts[0]}
+ rest = parts[1] if len(parts) > 1 else ""
+ m = re.search(r"enum=(\[.*?\])", rest)
+ if m:
+ out["enum"] = json.loads(m.group(1))
+ rest = rest.replace(m.group(0), "")
+ m = re.search(r'default=("[^"]*"|\S+)', rest)
+ if m:
+ raw = m.group(1)
+ out["default"] = json.loads(raw) if raw.startswith('"') else (raw == "true" if raw in ("true", "false") else num(raw))
+ for key, name in (("minimum", "min"), ("maximum", "max")):
+ m = re.search(rf"{key}=(\S+)", rest)
+ if m:
+ out[name] = num(m.group(1))
+ return out
+
+
+def pricing(text):
+ """The price per step and the fewest steps billed, from fal's own sentence (None when it names neither)."""
+ t = text or ""
+ per = None
+ for pat, div in (
+ (r"\$([\d.,]+) per 1000-step", 1000),
+ (r"\$([\d.,]+) for 1,000 requested steps", 1000),
+ (r"\$([\d.,]+) per steps?\b", 1),
+ (r"([\d.]+) \* steps", 1),
+ ):
+ m = re.search(pat, t)
+ if m:
+ per = float(m.group(1).replace(",", "")) / div
+ break
+ if per is None:
+ return None
+ floor = 1
+ for pat in (r"(\d[\d,]*) step floor", r"minimum of (\d[\d,]*) steps", r"(\d[\d,]*) steps is the minimum"):
+ m = re.search(pat, t)
+ if m:
+ floor = int(m.group(1).replace(",", ""))
+ break
+ m = re.search(r"minimum charge of \$([\d.,]+)", t)
+ if m and floor == 1:
+ floor = round(float(m.group(1).replace(",", "")) / per)
+ return {"usdPerStep": round(per, 8), "minBilledSteps": floor}
+
+
+trainers = []
+for raw in DATA["trainers"]:
+ if raw.get("provider") != "fal" or "image_data_url" not in (raw.get("required") or []):
+ continue
+ tid = raw["id"]
+ price = pricing(raw.get("price"))
+ fields = {k: field(v) for k, v in sorted((raw.get("fields") or {}).items())}
+ status = raw.get("status") or ""
+ entry = {
+ "id": tid,
+ "provider": "fal",
+ "family": raw.get("family") or "",
+ "base": slug(raw.get("family") or ""),
+ "role": raw.get("role") or "",
+ "dataField": "image_data_url",
+ "fields": fields,
+ "licence": raw.get("baseLicence") or "",
+ "commercial": bool(raw.get("commercialWeights")),
+ "status": "active" if status == "active" else "unlisted" if status.startswith("unlisted") else status or "unknown",
+ "checked": raw.get("checked") or "",
+ "schemaUrl": raw.get("schemaUrl") or "",
+ "priceText": raw.get("price") or "",
+ }
+ if price:
+ entry.update(price)
+ if tid in USED:
+ if not entry["commercial"]:
+ errors.append(f"{tid}: trains on non-commercial weights ({entry['licence']}), so no Fuobe Soul ID target may use it")
+ if entry["status"] not in ("active", "unlisted"):
+ errors.append(f"{tid}: status {status!r}")
+ for f in USED[tid]:
+ if f not in fields:
+ errors.append(f"{tid}: has no {f} field")
+ if not price:
+ errors.append(f"{tid}: can't read its price from {raw.get('price')!r}")
+ elif not price:
+ # Not used by a target: kept without a price (the UI never offers it).
+ pass
+ trainers.append(entry)
+
+missing = sorted(set(USED) - {t["id"] for t in trainers})
+for tid in missing:
+ errors.append(f"{tid}: not in the research's trainers[]")
+
+if errors:
+ print("gen-trainers: the research breaks the Soul ID rules:", file=sys.stderr)
+ for e in errors:
+ print(f" - {e}", file=sys.stderr)
+ sys.exit(1)
+
+ts = (
+ "// Generated by scripts/gen-trainers.py from docs/research/fuobe-originals-recipes-5.json — do not edit by hand.\n"
+ 'import type { HostedTrainer } from "./training";\n\n'
+ "/** When the trainers' schemas and prices were read. */\n"
+ f"export const TRAINERS_AS_OF = {json.dumps(DATA['asOf'])};\n\n"
+ "/** fal's image LoRA trainers (a zip of 001.jpg + 001.txt pairs in image_data_url), with their fields and prices. */\n"
+ f"export const HOSTED_TRAINERS: HostedTrainer[] = {json.dumps(trainers, indent=2, ensure_ascii=False)};\n"
+)
+OUT.write_text(ts, encoding="utf-8")
+print(f"wrote {OUT.relative_to(ROOT)}: {len(trainers)} trainers ({len(USED)} used by Soul ID)")
diff --git a/src/app/api/elements/[id]/lora/route.ts b/src/app/api/elements/[id]/lora/route.ts
index 4d775374..85591b44 100644
--- a/src/app/api/elements/[id]/lora/route.ts
+++ b/src/app/api/elements/[id]/lora/route.ts
@@ -2,15 +2,20 @@ import { z } from "zod";
import { attachLora } from "@/server/training";
import { getElement } from "@/server/elements";
-const Body = z.object({ file: z.string().min(1).max(300), trigger: z.string().max(80).default(""), modelId: z.string().default("oss-z-image-turbo") });
+const Body = z.object({
+ file: z.string().min(1).max(300),
+ trigger: z.string().max(80).default(""),
+ family: z.enum(["z-image-turbo", "qwen-image-2512"]).default("z-image-turbo"),
+});
-/** Attach a LoRA you trained yourself (already in ComfyUI/models/loras). */
+/** Attach a LoRA you trained yourself (already in ComfyUI/models/loras): Z-Image Turbo unless it says Qwen-Image 2512. */
export async function POST(request: Request, ctx: RouteContext<"/api/elements/[id]/lora">) {
const { id } = await ctx.params;
const parsed = Body.safeParse(await request.json().catch(() => null));
if (!parsed.success) return Response.json({ error: "Enter the LoRA file name" }, { status: 400 });
+ if (!getElement(id)) return Response.json({ error: "Not found" }, { status: 404 });
try {
- attachLora(id, parsed.data);
+ await attachLora(id, parsed.data);
return Response.json(getElement(id));
} catch (e) {
return Response.json({ error: (e as Error).message }, { status: 422 });
diff --git a/src/app/api/elements/[id]/route.ts b/src/app/api/elements/[id]/route.ts
index 285ec325..4f8555ad 100644
--- a/src/app/api/elements/[id]/route.ts
+++ b/src/app/api/elements/[id]/route.ts
@@ -1,12 +1,14 @@
import { connection } from "next/server";
import { z } from "zod";
+import { MAX_ELEMENT_PHOTOS } from "@/lib/catalog/elements";
+import { identityKey } from "@/lib/catalog/training";
import { deleteElement, getElement, updateElement } from "@/server/elements";
const Patch = z.object({
name: z.string().trim().min(1).max(60).optional(),
description: z.string().max(500).nullable().optional(),
- references: z.array(z.string().startsWith("/api/files/")).max(20).optional(),
- // Only removal is allowed from the client: the identities kept must already be on the element.
+ references: z.array(z.string().startsWith("/api/files/")).max(MAX_ELEMENT_PHOTOS).optional(),
+ // Only removal is allowed from the client: the identities kept must already be on the element (by identityKey).
removeIdentities: z.array(z.string()).optional(),
});
@@ -23,7 +25,7 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/elements/[
if (!parsed.success) return Response.json({ error: "Invalid element" }, { status: 400 });
const { removeIdentities, ...patch } = parsed.data;
const current = getElement(id);
- const loras = removeIdentities && current ? current.loras.filter((l) => !removeIdentities.includes(l.modelId)) : undefined;
+ const loras = removeIdentities && current ? current.loras.filter((l) => !removeIdentities.includes(identityKey(l))) : undefined;
const el = updateElement(id, { ...patch, ...(loras ? { loras } : {}) });
return el ? Response.json(el) : Response.json({ error: "Not found" }, { status: 404 });
}
diff --git a/src/app/api/elements/[id]/trainings/route.ts b/src/app/api/elements/[id]/trainings/route.ts
index bf9daa95..5abbcf10 100644
--- a/src/app/api/elements/[id]/trainings/route.ts
+++ b/src/app/api/elements/[id]/trainings/route.ts
@@ -1,20 +1,24 @@
import { connection } from "next/server";
import { z } from "zod";
-import { TRAINING_TARGETS } from "@/lib/catalog/training";
+import { targetsFor, TRAINING_TARGETS } from "@/lib/catalog/training";
+import { getElement } from "@/server/elements";
import { ensureRunner } from "@/server/generations";
-import { listTrainings, startTraining, trainingBlocker } from "@/server/training";
+import { describeTargets, listTrainings, startTraining } from "@/server/training";
+/** The targets this element can train on (each with what stops it, its price and whether it's a demo), and its trainings. */
export async function GET(_req: Request, ctx: RouteContext<"/api/elements/[id]/trainings">) {
await connection();
const { id } = await ctx.params;
ensureRunner(); // the background poller also checks training jobs
+ const el = getElement(id);
return Response.json({
- targets: TRAINING_TARGETS.map((t) => ({ ...t, blocker: trainingBlocker(t) })),
+ targets: describeTargets(el ? targetsFor(el.kind) : TRAINING_TARGETS),
items: listTrainings(id),
});
}
-const Body = z.object({ target: z.string().min(1) });
+// consent: the person in the photos agreed (required for a character; SOUL_ID_COPY.consent is the line they confirm).
+const Body = z.object({ target: z.string().min(1), consent: z.boolean().optional() });
export async function POST(request: Request, ctx: RouteContext<"/api/elements/[id]/trainings">) {
const { id } = await ctx.params;
@@ -22,7 +26,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/elements/[i
if (!parsed.success) return Response.json({ error: "Pick what to train" }, { status: 400 });
try {
ensureRunner();
- return Response.json(startTraining(id, parsed.data.target), { status: 201 });
+ return Response.json(startTraining(id, parsed.data.target, { consent: parsed.data.consent }), { status: 201 });
} catch (e) {
return Response.json({ error: (e as Error).message }, { status: 422 });
}
diff --git a/src/app/api/elements/route.ts b/src/app/api/elements/route.ts
index b9ae7249..38a77b51 100644
--- a/src/app/api/elements/route.ts
+++ b/src/app/api/elements/route.ts
@@ -1,5 +1,6 @@
import { connection } from "next/server";
import { z } from "zod";
+import { MAX_ELEMENT_PHOTOS } from "@/lib/catalog/elements";
import { createElement, listElements } from "@/server/elements";
const Kind = z.enum(["character", "location", "prop", "style", "voice"]);
@@ -8,7 +9,7 @@ const Body = z.object({
name: z.string().trim().min(1).max(60),
kind: Kind.default("character"),
description: z.string().max(500).optional(),
- references: z.array(z.string().startsWith("/api/files/")).max(20),
+ references: z.array(z.string().startsWith("/api/files/")).max(MAX_ELEMENT_PHOTOS),
});
export async function GET(request: Request) {
diff --git a/src/lib/catalog/elements.ts b/src/lib/catalog/elements.ts
index 70cb80f2..4f1a6875 100644
--- a/src/lib/catalog/elements.ts
+++ b/src/lib/catalog/elements.ts
@@ -3,6 +3,7 @@
* any prompt with `@handle` (Higgsfield's "Elements" / Soul ID). Resolution is pure so the
* server (authoritative), the composer (live preview + cost) and the agent share it.
*/
+import { identityFor, type TrainingFamily } from "./training";
import type { Engine, GenerationRequest, LoraRef, ModelDef, Operation } from "./types";
export type ElementKind = "character" | "location" | "prop" | "style" | "voice";
@@ -17,17 +18,34 @@ export const ELEMENT_KINDS: { kind: ElementKind; label: string; plural: string;
export const elementKindInfo = (k: ElementKind) => ELEMENT_KINDS.find((x) => x.kind === k) ?? ELEMENT_KINDS[0];
-/** A trained identity LoRA for an element (Soul ID parity). */
+/** Photos an element keeps: a Soul ID trains on up to 80 (Higgsfield's web limit). */
+export const MAX_ELEMENT_PHOTOS = 80;
+
+/**
+ * A trained LoRA for an element (Fuobe Soul ID, src/lib/catalog/training.ts). Since O3 it belongs to a family (its
+ * base) and runs on every model of it, on both engines; before, to one model (`modelId`).
+ */
export interface ElementLora {
+ /** The engine it was trained on (it runs on both when usableOn says so). */
engine: Engine;
- /** Model the LoRA was trained for; it's only applied when that model runs. */
+ /** The model it was trained for: the family's lead model since O3 (fuobe-soul, fuobe-soul-hd). */
modelId: string;
- /** ComfyUI models/loras file name (open) or a URL the cloud LoRA endpoint accepts. */
+ /** Its base: the LoRA runs on every model of this family. Unset on LoRAs from before O3 (read from modelId). */
+ family?: TrainingFamily;
+ /** The training target that made it. */
+ target?: string;
+ /** ComfyUI models/loras file name (unique per training: fuobe/<handle>-<id>.safetensors). */
file: string;
+ /** A URL the cloud LoRA endpoints fetch (fal's copy of a cloud training). */
url?: string;
+ /** Fuobe keeps its own copy of the file (src/server/loras.ts TRAINED_DIR): it can go to ComfyUI or the cloud. */
+ own?: true;
trigger: string;
strength?: number;
- /** Higgsfield Soul ID: a trained character reference passed as `custom_reference_id` instead of a LoRA. */
+ trainedAt?: number;
+ /** A demo training's stand-in (no key, no GPU): nothing was trained, so no run uses it. */
+ demo?: true;
+ /** A Higgsfield Soul ID (before O3): a `custom_reference_id` only Higgsfield's Soul models take. Retrain for Fuobe Soul. */
referenceId?: string;
}
@@ -117,15 +135,17 @@ export function applyMentions(req: GenerationRequest, model: ModelDef, elements:
const viaLora = new Set<string>();
let extra = req.params?.extra;
for (const el of mentioned) {
- const l = el.loras.find((x) => x.modelId === model.id && x.engine === model.engine);
- if (!l) continue;
- if (l.referenceId) {
- // Soul ID takes one character per generation.
- if (extra?.custom_reference_id) continue;
- extra = { ...extra, custom_reference_id: l.referenceId, custom_reference_strength: l.strength ?? 1 };
- } else {
- loras.push({ file: l.file, url: l.url, strength: l.strength ?? 1, trigger: l.trigger });
+ // A Higgsfield Soul ID on Higgsfield's own Soul models (until build plan O7 removes them): one character per run.
+ const legacy = el.loras.find((x) => x.referenceId && x.modelId === model.id && x.engine === model.engine);
+ if (legacy?.referenceId && !extra?.custom_reference_id) {
+ extra = { ...extra, custom_reference_id: legacy.referenceId, custom_reference_strength: legacy.strength ?? 1 };
+ viaLora.add(el.id);
+ continue;
}
+ // A trained LoRA of this model's family, on the engine it runs on (Fuobe Soul ID).
+ const l = identityFor(el.loras, model);
+ if (!l) continue;
+ loras.push({ file: l.file, ...(l.url && { url: l.url }), strength: l.strength ?? 1, trigger: l.trigger, ...(l.own && { own: true as const }) });
viaLora.add(el.id);
}
diff --git a/src/lib/catalog/loras.ts b/src/lib/catalog/loras.ts
index 6f603a5b..b90818e1 100644
--- a/src/lib/catalog/loras.ts
+++ b/src/lib/catalog/loras.ts
@@ -88,7 +88,7 @@ export const needsToken = (url: string | undefined): boolean => !!url && /^https
export function loraName(l: Pick<LoraRef, "file" | "url">): string {
const e = libraryEntry(l);
if (e) return e.name;
- const base = (l.file || l.url?.split("?")[0].split("/").pop() || "").replace(/\.safetensors$/i, "");
+ const base = (l.file.split("/").pop() || l.url?.split("?")[0].split("/").pop() || "").replace(/\.safetensors$/i, "");
return base ? `the ${base} LoRA` : "a trained LoRA";
}
@@ -99,6 +99,8 @@ export function loraName(l: Pick<LoraRef, "file" | "url">): string {
*/
export function cloudPath(l: LoraRef): string | undefined {
if (l.hostedUrl) return l.hostedUrl;
+ // The user's own trained LoRA: the server picks the copy to send (fal's while it lives, else Fuobe's, sent once).
+ if (l.own) return undefined;
if (!l.url || needsToken(l.url) || gated(l)) return undefined;
return l.url;
}
@@ -163,11 +165,11 @@ function fitSlots(field: LoraField, loras: LoraRef[]): { kept: LoraRef[]; over:
}
/**
- * A cloud API can be sent this LoRA: not local-only, and with a URL it can fetch (a mirror or a public file)
- * or a civitai file Fuobe mirrors before the run. Not a gated Hugging Face file (no HF token here) nor a file
- * that exists only on the user's ComfyUI.
+ * A cloud API can be sent this LoRA: not local-only, and with a URL it can fetch (a mirror or a public file),
+ * a civitai file Fuobe mirrors before the run, or the user's own trained LoRA (Fuobe sends its copy). Not a gated
+ * Hugging Face file (no HF token here) nor a file that exists only on the user's ComfyUI.
*/
-const sendable = (l: LoraRef) => !localOnly(l) && (!!cloudPath(l) || (!!l.url && needsToken(l.url)));
+const sendable = (l: LoraRef) => !localOnly(l) && (!!cloudPath(l) || (!!l.url && needsToken(l.url)) || (!!l.own && (!!l.url || !!l.file)));
const sendableToCloud = (loras: LoraRef[]) => loras.filter(sendable);
/** fal's `/lora` endpoints before FieldMap.loras was generated: loras [{path, scale}]. */
diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.ts
index 4af517ac..14e6d12c 100644
--- a/src/lib/catalog/plan.ts
+++ b/src/lib/catalog/plan.ts
@@ -583,7 +583,7 @@ export function routeLoras(route: Pick<ModelRoute, "provider" | "map" | "loraEnd
const why = (l: LoraRef) => {
if (localOnly(l)) return "its licence doesn't allow hosting, so it runs only on your GPU";
if (gated(l) && !l.hostedUrl) return "it is in a gated Hugging Face repo, so it runs only on your GPU";
- if (!cloudPath(l) && !needsToken(l.url)) return "no URL to send to the LoRA endpoint";
+ if (!cloudPath(l) && !needsToken(l.url) && !l.own) return "no URL to send to the LoRA endpoint";
if (!field) return "this route takes no LoRAs";
return field.shape === "experts" ? "this API takes one LoRA per expert" : `this API takes up to ${loraCapacity(field)} LoRAs`;
};
diff --git a/src/lib/catalog/trainers.generated.ts b/src/lib/catalog/trainers.generated.ts
new file mode 100644
index 00000000..727322cf
--- /dev/null
+++ b/src/lib/catalog/trainers.generated.ts
@@ -0,0 +1,351 @@
+// Generated by scripts/gen-trainers.py from docs/research/fuobe-originals-recipes-5.json — do not edit by hand.
+import type { HostedTrainer } from "./training";
+
+/** When the trainers' schemas and prices were read. */
+export const TRAINERS_AS_OF = "2026-10-23";
+
+/** fal's image LoRA trainers (a zip of 001.jpg + 001.txt pairs in image_data_url), with their fields and prices. */
+export const HOSTED_TRAINERS: HostedTrainer[] = [
+ {
+ "id": "fal-ai/z-image-turbo-trainer-v2",
+ "provider": "fal",
+ "family": "Z-Image Turbo",
+ "base": "z-image-turbo",
+ "role": "Soul ID, preset LoRAs (fast, cheapest)",
+ "dataField": "image_data_url",
+ "fields": {
+ "default_caption": {
+ "type": "string"
+ },
+ "image_data_url": {
+ "type": "string"
+ },
+ "learning_rate": {
+ "type": "number",
+ "default": 0.0005
+ },
+ "steps": {
+ "type": "integer",
+ "default": 2000,
+ "min": 10,
+ "max": 40000
+ }
+ },
+ "licence": "Apache-2.0",
+ "commercial": true,
+ "status": "active",
+ "checked": "2026-10-23",
+ "schemaUrl": "https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=fal-ai/z-image-turbo-trainer-v2",
+ "priceText": "Your request will cost $0.85 per 1000-step training run. It scales per step, so a 2000-step training run will cost $1.70. A 500 step floor is applied to the steps for billing purposes. If 100 steps are used you will be billed for the 500 step minimum.",
+ "usdPerStep": 0.00085,
+ "minBilledSteps": 500
+ },
+ {
+ "id": "fal-ai/z-image-trainer",
+ "provider": "fal",
+ "family": "Z-Image (base)",
+ "base": "z-image",
+ "role": "style LoRAs (training_type content | style | balanced)",
+ "dataField": "image_data_url",
+ "fields": {
+ "default_caption": {
+ "type": "string"
+ },
+ "image_data_url": {
+ "type": "string"
+ },
+ "learning_rate": {
+ "type": "number",
+ "default": 0.0001
+ },
+ "steps": {
+ "type": "integer",
+ "default": 1000,
+ "min": 100,
+ "max": 10000
+ },
+ "training_type": {
+ "type": "string",
+ "enum": [
+ "content",
+ "style",
+ "balanced"
+ ],
+ "default": "balanced"
+ }
+ },
+ "licence": "Apache-2.0",
+ "commercial": true,
+ "status": "active",
+ "checked": "2026-10-23",
+ "schemaUrl": "https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=fal-ai/z-image-trainer",
+ "priceText": "Your request will cost $2.26 per 1000-step training run. It scales per step, so a 2000-step training run costs $4.52. Note: 100 steps is the minimum step count, which will cost $0.226.",
+ "usdPerStep": 0.00226,
+ "minBilledSteps": 100
+ },
+ {
+ "id": "fal-ai/qwen-image-2512-trainer",
+ "provider": "fal",
+ "family": "Qwen-Image 2512",
+ "base": "qwen-image-2512",
+ "role": "typography / HD preset LoRAs",
+ "dataField": "image_data_url",
+ "fields": {
+ "default_caption": {
+ "type": "string"
+ },
+ "image_data_url": {
+ "type": "string"
+ },
+ "learning_rate": {
+ "type": "number",
+ "default": 0.0005
+ },
+ "steps": {
+ "type": "integer",
+ "default": 1000,
+ "min": 1,
+ "max": 30000
+ }
+ },
+ "licence": "Apache-2.0",
+ "commercial": true,
+ "status": "active",
+ "checked": "2026-10-23",
+ "schemaUrl": "https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=fal-ai/qwen-image-2512-trainer",
+ "priceText": "Your request will cost $0.0015 per step (minimum of 500 steps is charged). For $1.5 you can fine-tune a LoRA for 1000 steps.",
+ "usdPerStep": 0.0015,
+ "minBilledSteps": 500
+ },
+ {
+ "id": "fal-ai/qwen-image-trainer",
+ "provider": "fal",
+ "family": "Qwen-Image",
+ "base": "qwen-image",
+ "role": "",
+ "dataField": "image_data_url",
+ "fields": {
+ "image_data_url": {
+ "type": "string"
+ },
+ "learning_rate": {
+ "type": "number",
+ "default": 0.0005,
+ "min": 1e-06,
+ "max": 0.01
+ },
+ "steps": {
+ "type": "integer",
+ "default": 1000,
+ "min": 1,
+ "max": 8000
+ },
+ "trigger_phrase": {
+ "type": "string",
+ "default": ""
+ }
+ },
+ "licence": "Apache-2.0",
+ "commercial": true,
+ "status": "unlisted",
+ "checked": "2026-10-23",
+ "schemaUrl": "https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=fal-ai/qwen-image-trainer",
+ "priceText": "Your request will cost $0.002 per step (minimum of 250 steps is charged). For $2 you can fine-tune a LoRA for 1000 steps.",
+ "usdPerStep": 0.002,
+ "minBilledSteps": 250
+ },
+ {
+ "id": "fal-ai/qwen-image-edit-2511-trainer",
+ "provider": "fal",
+ "family": "Qwen-Image-Edit 2511",
+ "base": "qwen-image-edit-2511",
+ "role": "edit LoRAs (image pairs)",
+ "dataField": "image_data_url",
+ "fields": {
+ "default_caption": {
+ "type": "string"
+ },
+ "image_data_url": {
+ "type": "string"
+ },
+ "learning_rate": {
+ "type": "number",
+ "default": 0.0001
+ },
+ "steps": {
+ "type": "integer",
+ "default": 1000,
+ "min": 1,
+ "max": 30000
+ }
+ },
+ "licence": "Apache-2.0",
+ "commercial": true,
+ "status": "unlisted",
+ "checked": "2026-10-23",
+ "schemaUrl": "https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=fal-ai/qwen-image-edit-2511-trainer",
+ "priceText": "Your request will cost $4.0 per 1000-step training run. It scales per step, so a 2000-step training run costs $8. Note: 100 steps is the minimum step count, which will cost $0.40.",
+ "usdPerStep": 0.004,
+ "minBilledSteps": 100
+ },
+ {
+ "id": "fal-ai/qwen-image-edit-2509-trainer",
+ "provider": "fal",
+ "family": "Qwen-Image-Edit 2509",
+ "base": "qwen-image-edit-2509",
+ "role": "",
+ "dataField": "image_data_url",
+ "fields": {
+ "default_caption": {
+ "type": "string"
+ },
+ "image_data_url": {
+ "type": "string"
+ },
+ "learning_rate": {
+ "type": "number",
+ "default": 0.0001
+ },
+ "steps": {
+ "type": "integer",
+ "default": 1000,
+ "min": 1,
+ "max": 30000
+ }
+ },
+ "licence": "Apache-2.0",
+ "commercial": true,
+ "status": "active",
+ "checked": "2026-10-23",
+ "schemaUrl": "https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=fal-ai/qwen-image-edit-2509-trainer",
+ "priceText": "Your request will cost $4.0 per 1000-step training run. It scales per step, so a 2000-step training run costs $8. Note: 100 steps is the minimum step count, which will cost $0.40.",
+ "usdPerStep": 0.004,
+ "minBilledSteps": 100
+ },
+ {
+ "id": "fal-ai/flux-2-klein-4b-base-trainer",
+ "provider": "fal",
+ "family": "FLUX.2 [klein] 4B base",
+ "base": "flux-2-klein-4b-base",
+ "role": "Apache image LoRAs",
+ "dataField": "image_data_url",
+ "fields": {
+ "default_caption": {
+ "type": "string"
+ },
+ "image_data_url": {
+ "type": "string"
+ },
+ "learning_rate": {
+ "type": "number",
+ "default": 5e-05
+ },
+ "output_lora_format": {
+ "type": "string",
+ "enum": [
+ "fal",
+ "comfy"
+ ],
+ "default": "fal"
+ },
+ "steps": {
+ "type": "integer",
+ "default": 1000,
+ "min": 100,
+ "max": 20000
+ }
+ },
+ "licence": "Apache-2.0",
+ "commercial": true,
+ "status": "unlisted",
+ "checked": "2026-10-23",
+ "schemaUrl": "https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=fal-ai/flux-2-klein-4b-base-trainer",
+ "priceText": "The cost of training depends on the number of steps. The formula is: 0.005 * steps. With 1000 steps, your request will cost $5.00.",
+ "usdPerStep": 0.005,
+ "minBilledSteps": 1
+ },
+ {
+ "id": "fal-ai/flux-2-klein-9b-base-trainer",
+ "provider": "fal",
+ "family": "FLUX.2 [klein] 9B base",
+ "base": "flux-2-klein-9b-base",
+ "role": "not for Originals",
+ "dataField": "image_data_url",
+ "fields": {
+ "default_caption": {
+ "type": "string"
+ },
+ "image_data_url": {
+ "type": "string"
+ },
+ "learning_rate": {
+ "type": "number",
+ "default": 5e-05
+ },
+ "output_lora_format": {
+ "type": "string",
+ "enum": [
+ "fal",
+ "comfy"
+ ],
+ "default": "fal"
+ },
+ "steps": {
+ "type": "integer",
+ "default": 1000,
+ "min": 100,
+ "max": 20000
+ }
+ },
+ "licence": "FLUX Non-Commercial License",
+ "commercial": false,
+ "status": "active",
+ "checked": "2026-10-23",
+ "schemaUrl": "https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=fal-ai/flux-2-klein-9b-base-trainer",
+ "priceText": "The cost of training depends on the number of steps. The formula is: 0.0043 * steps. With 1000 steps, your request will cost $4.30.",
+ "usdPerStep": 0.0043,
+ "minBilledSteps": 1
+ },
+ {
+ "id": "fal-ai/flux-2-trainer-v2",
+ "provider": "fal",
+ "family": "FLUX.2 [dev]",
+ "base": "flux-2-dev",
+ "role": "not for Originals",
+ "dataField": "image_data_url",
+ "fields": {
+ "default_caption": {
+ "type": "string"
+ },
+ "image_data_url": {
+ "type": "string"
+ },
+ "learning_rate": {
+ "type": "number",
+ "default": 5e-05
+ },
+ "output_lora_format": {
+ "type": "string",
+ "enum": [
+ "fal",
+ "comfy"
+ ],
+ "default": "fal"
+ },
+ "steps": {
+ "type": "integer",
+ "default": 1000,
+ "min": 100,
+ "max": 20000
+ }
+ },
+ "licence": "FLUX [dev] Non-Commercial License",
+ "commercial": false,
+ "status": "active",
+ "checked": "2026-10-23",
+ "schemaUrl": "https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=fal-ai/flux-2-trainer-v2",
+ "priceText": "The cost of training depends on the number of steps. The formula is: 0.0064 * steps. With 1000 steps, your request will cost $6.40.",
+ "usdPerStep": 0.0064,
+ "minBilledSteps": 1
+ }
+];
diff --git a/src/lib/catalog/training.ts b/src/lib/catalog/training.ts
index 466851c9..47774f25 100644
--- a/src/lib/catalog/training.ts
+++ b/src/lib/catalog/training.ts
@@ -1,75 +1,293 @@
/**
- * Identity training targets (Higgsfield's Soul ID). A trained element is used automatically
- * whenever it's @mentioned on one of the target's models — as a Soul ID reference or a LoRA
- * plus trigger word — instead of reference photos.
+ * Fuobe Soul ID (build plan O3): a character or a style trained as a LoRA on open weights, on either engine
+ * (AI-Toolkit on the user's GPU, or fal's hosted trainers), then used whenever the element is @mentioned on a
+ * model of the family it was trained for: Fuobe Soul and Soul Cinema (Z-Image Turbo), Fuobe Soul HD
+ * (Qwen-Image 2512), and the plain open-weight models of the same base. Pure logic, no I/O.
+ *
+ * - A LoRA belongs to a family (its base), not to one model, and works on both engines: a LoRA trained on fal is
+ * downloaded into ComfyUI for open runs, one trained on the user's GPU is copied to the cloud provider for cloud
+ * runs (src/server/loras.ts). Another family means training again on the same photos ("Upgrade character"), as
+ * Higgsfield retrains a Soul ID per model family.
+ * - The hosted trainers' fields and prices are generated from the research (trainers.generated.ts by
+ * scripts/gen-trainers.py); every one a target uses trains on commercial weights (Apache-2.0).
+ * - Photo rules and the consent line follow Higgsfield's character flow (docs/research/higgsfield-originals-5.md
+ * §3.4, higgsfield-delta-4.md G18): 20+ photos recommended, 80 at most, one person, a full-body shot, consent
+ * before a person's photos are trained.
*/
-import type { Engine } from "./types";
+import type { ElementKind, ElementLora } from "./elements";
+import { HOSTED_TRAINERS } from "./trainers.generated";
+import type { Engine, ModelDef } from "./types";
-export type TrainingProvider = "higgsfield" | "fal" | "ai-toolkit";
+export type TrainingProvider = "fal" | "ai-toolkit";
+
+/** The base a LoRA is trained on. A trained LoRA works on every model of its family. */
+export type TrainingFamily = "z-image-turbo" | "qwen-image-2512";
+
+/** What a training learns: a subject (a person, a place, an object) or a style (a moodboard). */
+export type TrainingKind = "subject" | "style";
+
+/** A field of a hosted trainer's request (from its OpenAPI schema). */
+export interface TrainerField {
+ type: string;
+ default?: string | number | boolean;
+ min?: number;
+ max?: number;
+ enum?: string[];
+}
+
+/** A hosted LoRA trainer (generated from the research by scripts/gen-trainers.py). */
+export interface HostedTrainer {
+ /** The fal endpoint, e.g. "fal-ai/z-image-turbo-trainer-v2". */
+ id: string;
+ provider: "fal";
+ /** The base model as the research names it ("Z-Image Turbo"). */
+ family: string;
+ /** The base as a slug ("z-image-turbo", "z-image", "qwen-image-2512"). */
+ base: string;
+ role: string;
+ /** Where the zip of 001.jpg + 001.txt pairs goes. */
+ dataField: string;
+ fields: Record<string, TrainerField>;
+ licence: string;
+ /** The weights it trains on allow selling outputs. */
+ commercial: boolean;
+ status: string;
+ checked: string;
+ schemaUrl: string;
+ priceText: string;
+ usdPerStep?: number;
+ /** fal bills at least this many steps. */
+ minBilledSteps?: number;
+}
export interface TrainingTarget {
id: string;
+ /** Short: where it trains ("Your GPU", "Cloud"). The family says what for. */
name: string;
+ /** The engine the training runs on (the LoRA then works on both). */
engine: Engine;
provider: TrainingProvider;
- /** Models the trained identity applies to. */
+ family: TrainingFamily;
+ kinds: TrainingKind[];
+ /** fal: the hosted trainer's endpoint (HOSTED_TRAINERS). */
+ trainer?: string;
+ steps: number;
+ learningRate?: number;
+ /** Other fields sent to the trainer (fal's training_type). */
+ extra?: Record<string, string>;
+ /** Models the trained LoRA applies to (the family's, on both engines). */
modelIds: string[];
minImages: number;
description: string;
+ /** "Free" on the user's GPU, else the price fal charges for this many steps. */
price: string;
+ /** The same price as a number (0 when free). */
+ costUsd: number;
/** Rough wall-clock time. */
eta: string;
}
-export const TRAINING_TARGETS: TrainingTarget[] = [
- {
- id: "soul-id-v2",
- name: "Soul ID · Soul 2.0",
- engine: "cloud",
- provider: "higgsfield",
- modelIds: ["soul-2"],
- minImages: 5,
- description: "Higgsfield's own character training for Soul 2.0 — the most faithful faces, used across Soul styles.",
- price: "Higgsfield balance",
- eta: "~5–10 min",
+/** The families, in the order the Train dialog shows them; `lead` is the model a trained element is shown for. */
+export const TRAINING_FAMILIES: Record<TrainingFamily, { name: string; base: string; lead: string; models: string[] }> = {
+ "z-image-turbo": {
+ name: "Fuobe Soul and Soul Cinema",
+ base: "Z-Image Turbo",
+ lead: "fuobe-soul",
+ models: ["fuobe-soul", "fuobe-soul-cinema", "oss-z-image-turbo", "z-image-turbo-cloud"],
},
- {
- id: "soul-id-cinema",
- name: "Soul ID · Soul Cinema",
- engine: "cloud",
- provider: "higgsfield",
- modelIds: ["soul-cinema"],
- minImages: 5,
- description: "The same character trained for Soul Cinema's film stills.",
- price: "Higgsfield balance",
- eta: "~5–10 min",
- },
- {
- id: "fal-z-image",
- name: "Z-Image Turbo LoRA (fal)",
- engine: "cloud",
- provider: "fal",
- modelIds: ["z-image-turbo-cloud"],
- minImages: 5,
- description: "A character LoRA for hosted Z-Image Turbo: photoreal, sub-second images of your character.",
- price: "≈ $0.85 (1,000 steps)",
- eta: "~5 min",
+ "qwen-image-2512": {
+ name: "Fuobe Soul HD",
+ base: "Qwen-Image 2512",
+ lead: "fuobe-soul-hd",
+ models: ["fuobe-soul-hd", "oss-qwen-image", "oss-qwen-image-lightning", "qwen-image-2512-cloud"],
},
- {
+};
+
+/** Higgsfield's character flow, as limits (research §3.4): 20+ photos recommended, 80 at most on the web. */
+export const SOUL_ID_PHOTOS = { min: 5, recommended: 20, max: 80, minSide: 512 } as const;
+
+/**
+ * The photo rules and the consent line (Higgsfield's character-creation copy, docs/research/higgsfield-image-studios.md
+ * §2 and higgsfield-delta-4.md G18), shared by every place that makes or trains a character.
+ */
+export const SOUL_ID_COPY = {
+ moreTitle: "More Photos, Better Results",
+ more: "Upload 20+ photos for best results",
+ avoidTitle: "Avoid These Types of Photos",
+ avoid: "No duplicates, group shots, pets, nudes, filters, face-covering accessories, or masks",
+ rules: [
+ "One person in every photo, the face fully in frame",
+ "Different angles, expressions and light, and at least one full-body shot",
+ "Recent photos: no sunglasses, heavy shadows, filters or group shots",
+ ],
+ consent:
+ "I consent to this biometric data processing and confirm these photos are of me or of a person at least 18 years old who gave written permission.",
+ needsConsent: "Confirm the consent line first: a character is only trained with the person's permission",
+} as const;
+
+const trainers = new Map(HOSTED_TRAINERS.map((t) => [t.id, t]));
+export const getTrainer = (id: string | undefined): HostedTrainer | undefined => (id ? trainers.get(id) : undefined);
+
+/** What fal bills for this many steps on this trainer (its per-step price above its minimum), in US dollars. */
+export function trainerCost(trainer: Pick<HostedTrainer, "usdPerStep" | "minBilledSteps"> | undefined, steps: number): number | null {
+ if (!trainer?.usdPerStep) return null;
+ return Math.round(Math.max(steps, trainer.minBilledSteps ?? 1) * trainer.usdPerStep * 100) / 100;
+}
+
+const usd = (n: number) => `$${n.toFixed(2)}`;
+const thousands = (n: number) => n.toLocaleString("en-US");
+
+function target(t: Omit<TrainingTarget, "modelIds" | "price" | "costUsd" | "minImages">): TrainingTarget {
+ const cost = t.provider === "fal" ? trainerCost(getTrainer(t.trainer), t.steps) : 0;
+ if (cost === null) throw new Error(`${t.id}: its trainer ${t.trainer} has no price (run pnpm gen:catalog)`);
+ return {
+ ...t,
+ modelIds: TRAINING_FAMILIES[t.family].models,
+ minImages: SOUL_ID_PHOTOS.min,
+ costUsd: cost,
+ price: cost === 0 ? "Free" : `≈ ${usd(cost)} (${thousands(t.steps)} steps)`,
+ };
+}
+
+/**
+ * Where a Soul ID trains (research §3.3, §4.5, plan O3). Z-Image Turbo: AI-Toolkit with ostris's training adapter v2 on
+ * the user's GPU, or fal's Z-Image Turbo trainer v2 (2,000 steps at 5e-4). A style (a moodboard) on the cloud trains on
+ * fal's Z-Image trainer with training_type style. Fuobe Soul HD: fal's Qwen-Image 2512 trainer.
+ */
+export const TRAINING_TARGETS: TrainingTarget[] = [
+ target({
id: "aitk-z-image",
- name: "Z-Image Turbo LoRA (your GPU)",
+ name: "Your GPU",
engine: "open",
provider: "ai-toolkit",
- modelIds: ["oss-z-image-turbo"],
- minImages: 5,
- description: "Train on your own GPU with AI-Toolkit (24 GB). The LoRA is used by the open-source Z-Image Turbo workflow.",
- price: "Free",
- eta: "~30–60 min on a 4090",
- },
+ family: "z-image-turbo",
+ kinds: ["subject", "style"],
+ steps: 2000,
+ description: "AI-Toolkit on your own GPU (24 GB), with ostris's Z-Image Turbo training adapter. Nothing leaves your machine.",
+ eta: "~30–60 min on a 24 GB GPU",
+ }),
+ target({
+ id: "fal-z-image",
+ name: "Cloud",
+ engine: "cloud",
+ provider: "fal",
+ family: "z-image-turbo",
+ kinds: ["subject"],
+ trainer: "fal-ai/z-image-turbo-trainer-v2",
+ steps: 2000,
+ learningRate: 0.0005,
+ description: "fal's Z-Image Turbo trainer. Your photos go to fal for the training.",
+ eta: "~10 min",
+ }),
+ target({
+ id: "fal-z-image-style",
+ name: "Cloud",
+ engine: "cloud",
+ provider: "fal",
+ family: "z-image-turbo",
+ kinds: ["style"],
+ trainer: "fal-ai/z-image-trainer",
+ steps: 1500,
+ extra: { training_type: "style" },
+ description: "fal's Z-Image trainer in style mode: the look, not the subjects. Your images go to fal for the training.",
+ eta: "~15–30 min",
+ }),
+ target({
+ id: "fal-qwen-2512",
+ name: "Cloud",
+ engine: "cloud",
+ provider: "fal",
+ family: "qwen-image-2512",
+ kinds: ["subject"],
+ trainer: "fal-ai/qwen-image-2512-trainer",
+ steps: 1000,
+ learningRate: 0.0005,
+ description: "fal's Qwen-Image 2512 trainer, for Fuobe Soul HD (clean lettering). Your photos go to fal for the training.",
+ eta: "~10–20 min",
+ }),
];
export const getTrainingTarget = (id: string) => TRAINING_TARGETS.find((t) => t.id === id);
+/** A style element trains as a style; characters, places and objects as subjects. */
+export const trainingKind = (kind: ElementKind): TrainingKind => (kind === "style" ? "style" : "subject");
+
+/** The targets an element of this kind can train on, in the dialog's order. */
+export const targetsFor = (kind: ElementKind): TrainingTarget[] => (kind === "voice" ? [] : TRAINING_TARGETS.filter((t) => t.kinds.includes(trainingKind(kind))));
+
+/** Only a person needs the consent line (biometric data). */
+export const needsConsent = (kind: ElementKind): boolean => kind === "character";
+
+/** What stops a training from starting with this many photos (null when it can start). */
+export function photosBlocker(count: number, name = "them"): string | null {
+ if (count < SOUL_ID_PHOTOS.min) return `Add at least ${SOUL_ID_PHOTOS.min} photos of ${name} first (you have ${count})`;
+ if (count > SOUL_ID_PHOTOS.max) return `A training takes up to ${SOUL_ID_PHOTOS.max} photos (you have ${count})`;
+ return null;
+}
+
+/**
+ * Tips on a set of photos before training (shown, never blocking): fewer than 20, photos smaller than 512 px on a
+ * side (the trainers learn at 512–1024), and duplicates. `photos` carry their size when the browser knows it.
+ */
+export function photoTips(photos: { key: string; width?: number; height?: number }[]): string[] {
+ const tips: string[] = [];
+ if (photos.length >= SOUL_ID_PHOTOS.min && photos.length < SOUL_ID_PHOTOS.recommended) tips.push(`${SOUL_ID_COPY.more}: you have ${photos.length}`);
+ const small = photos.filter((p) => p.width && p.height && Math.min(p.width, p.height) < SOUL_ID_PHOTOS.minSide).length;
+ if (small) tips.push(`${small} photo${small > 1 ? "s are" : " is"} smaller than ${SOUL_ID_PHOTOS.minSide} px on a side: larger ones train better`);
+ const dupes = photos.length - new Set(photos.map((p) => p.key)).size;
+ if (dupes) tips.push(`${dupes} duplicate photo${dupes > 1 ? "s" : ""}: each adds nothing`);
+ return tips;
+}
+
+// ---------------------------------------------------------------------------
+// Which trained LoRA a run uses
+
+/** The family a model's LoRAs belong to (undefined for a model no Soul ID applies to). */
+export function familyOfModel(modelId: string): TrainingFamily | undefined {
+ return (Object.keys(TRAINING_FAMILIES) as TrainingFamily[]).find((f) => TRAINING_FAMILIES[f].models.includes(modelId));
+}
+
+/** A trained LoRA's family: recorded since O3; read from the model it was trained for before that. */
+export function loraFamily(l: Pick<ElementLora, "family" | "modelId" | "referenceId">): TrainingFamily | undefined {
+ if (l.referenceId) return undefined;
+ return l.family ?? familyOfModel(l.modelId);
+}
+
+/**
+ * A trained LoRA can run on this engine: the open engine needs a file name for ComfyUI's loras folder (downloaded
+ * from its URL or copied from Fuobe's own copy when ComfyUI lacks it); the cloud needs a URL the provider can fetch,
+ * or Fuobe's own copy of the file to send it.
+ */
+export function usableOn(l: Pick<ElementLora, "file" | "url" | "own" | "referenceId" | "demo">, engine: Engine): boolean {
+ if (l.referenceId || l.demo) return false;
+ return engine === "open" ? !!l.file : !!l.url || (!!l.own && !!l.file);
+}
+
+/** A Higgsfield Soul ID (from before O3): it can't be exported, so the element is retrained on its photos. */
+export const isLegacySoulId = (l: Pick<ElementLora, "referenceId">): boolean => !!l.referenceId;
+
+/**
+ * The trained LoRA an @mention uses on this model: one attached for this exact model (a LoRA trained elsewhere),
+ * else the newest one of the model's family that runs on its engine (the one trained on that engine first).
+ */
+export function identityFor(loras: ElementLora[], model: Pick<ModelDef, "id" | "engine">): ElementLora | undefined {
+ const exact = loras.find((l) => !l.referenceId && l.modelId === model.id && l.engine === model.engine && usableOn(l, model.engine));
+ if (exact) return exact;
+ const fam = familyOfModel(model.id);
+ if (!fam) return undefined;
+ const fits = loras.filter((l) => loraFamily(l) === fam && usableOn(l, model.engine));
+ return fits.sort((a, b) => Number(b.engine === model.engine) - Number(a.engine === model.engine) || (b.trainedAt ?? 0) - (a.trainedAt ?? 0))[0];
+}
+
+/** How the Train dialog names one of an element's LoRAs to remove it: its file, its Soul ID, or its model. */
+export const identityKey = (l: Pick<ElementLora, "file" | "referenceId" | "modelId">): string => l.file || l.referenceId || l.modelId;
+
+/** The families an element has a trained LoRA for. */
+export const trainedFamilies = (loras: ElementLora[]): TrainingFamily[] => [...new Set(loras.map(loraFamily).filter((f): f is TrainingFamily => !!f))];
+
+// ---------------------------------------------------------------------------
+// The dataset and the requests
+
/** A short, rare trigger token for an element, e.g. "mayalpz". */
export function triggerFor(handle: string): string {
const base = handle.toLowerCase().replace(/[^a-z0-9]/g, "");
@@ -83,13 +301,35 @@ export function trainingCaption(kind: "character" | "style", trigger: string, de
return `${kind === "style" ? `${trigger} style` : `photo of ${trigger}`}${extra ? `, ${extra}` : ""}`;
}
+/** The dataset's file names: 001.jpg with its caption 001.txt (what fal's image trainers read). */
+export const datasetName = (index: number, ext: string): string => `${String(index + 1).padStart(3, "0")}.${ext}`;
+
+const clampField = (f: TrainerField | undefined, v: number) => (f ? Math.min(f.max ?? v, Math.max(f.min ?? v, v)) : v);
+
+/**
+ * The request a hosted trainer gets: the dataset zip in its data field, then only the fields its schema has (steps
+ * within its limits, the caption every photo shares, the learning rate, training_type for a style).
+ */
+export function falTrainingInput(t: TrainingTarget, zipUrl: string, caption: string): Record<string, unknown> {
+ const tr = getTrainer(t.trainer);
+ if (!tr) throw new Error(`${t.id} has no hosted trainer`);
+ const f = tr.fields;
+ const body: Record<string, unknown> = { [tr.dataField]: zipUrl };
+ if (f.steps) body.steps = clampField(f.steps, t.steps);
+ if (f.default_caption) body.default_caption = caption;
+ if (f.learning_rate && t.learningRate !== undefined) body.learning_rate = t.learningRate;
+ for (const [k, v] of Object.entries(t.extra ?? {})) if (f[k] && (!f[k].enum || f[k].enum.includes(v))) body[k] = v;
+ return body;
+}
+
/**
- * AI-Toolkit job config for a Z-Image Turbo LoRA (docs/research/comfyui-oss-2.json → character-lora).
- * `kind: "style"` is the style preset (a moodboard): fewer steps and samples of new scenes in the
- * look, instead of portraits of the person.
+ * AI-Toolkit job config for a Z-Image Turbo LoRA (research §4.5: ostris's training adapter v2, rank 16–32,
+ * 1,500–2,500 steps). A larger photo set gets rank 32 (more to learn); a style (a moodboard) gets fewer steps and
+ * samples of new scenes in the look, instead of portraits of the person.
*/
-export function aiToolkitJob(opts: { name: string; trigger: string; datasetFolder: string; outputFolder: string; steps?: number; kind?: "character" | "style" }) {
+export function aiToolkitJob(opts: { name: string; trigger: string; datasetFolder: string; outputFolder: string; steps?: number; kind?: "character" | "style"; photos?: number }) {
const style = opts.kind === "style";
+ const rank = !style && (opts.photos ?? 0) >= SOUL_ID_PHOTOS.recommended ? 32 : 16;
return {
job: "extension",
config: {
@@ -100,7 +340,7 @@ export function aiToolkitJob(opts: { name: string; trigger: string; datasetFolde
training_folder: opts.outputFolder,
device: "cuda",
trigger_word: opts.trigger,
- network: { type: "lora", linear: 16, linear_alpha: 16 },
+ network: { type: "lora", linear: rank, linear_alpha: rank },
save: { dtype: "bf16", save_every: 500, max_step_saves_to_keep: 3, save_format: "safetensors" },
datasets: [
{ folder_path: opts.datasetFolder, caption_ext: "txt", caption_dropout_rate: 0.05, cache_latents_to_disk: true, resolution: [512, 768, 1024], num_repeats: 1 },
@@ -118,7 +358,7 @@ export function aiToolkitJob(opts: { name: string; trigger: string; datasetFolde
dtype: "bf16",
cache_text_embeddings: true,
ema_config: { use_ema: false },
- steps: opts.steps ?? (style ? 1500 : 2500),
+ steps: opts.steps ?? (style ? 1500 : 2000),
timestep_type: "weighted",
},
model: {
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 340e22cc..d0e42545 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -741,6 +741,11 @@ export interface LoraRef {
*/
version?: string;
licence?: LoraLicence;
+ /**
+ * The user's own trained LoRA (Fuobe Soul ID): Fuobe keeps the file, so a run copies it into ComfyUI's folder or
+ * sends it to the cloud provider itself (src/server/loras.ts), whichever engine trained it.
+ */
+ own?: true;
}
/** Scale limits of a LoRA field. */
diff --git a/src/server/elements.ts b/src/server/elements.ts
index 4cce20a5..c5d2da2a 100644
--- a/src/server/elements.ts
+++ b/src/server/elements.ts
@@ -1,6 +1,6 @@
import "server-only";
import { nanoid } from "nanoid";
-import { handleFor, type ElementKind, type ElementLora, type StudioElement } from "@/lib/catalog/elements";
+import { handleFor, MAX_ELEMENT_PHOTOS, type ElementKind, type ElementLora, type StudioElement } from "@/lib/catalog/elements";
import { db } from "./db";
interface Row {
@@ -60,7 +60,7 @@ export function createElement(input: { name: string; kind: ElementKind; descript
handle: uniqueHandle(name),
kind: input.kind,
description: input.description?.trim() || null,
- reference_asset_ids_json: JSON.stringify(input.references.slice(0, 20)),
+ reference_asset_ids_json: JSON.stringify(input.references.slice(0, MAX_ELEMENT_PHOTOS)),
loras_json: null,
status: "ready" as const,
created_at: now,
@@ -91,7 +91,7 @@ export function updateElement(
name,
handle: name === cur.name ? cur.handle : uniqueHandle(name, id),
description: patch.description === undefined ? cur.description : patch.description?.trim() || null,
- refs: JSON.stringify((patch.references ?? cur.references).slice(0, 20)),
+ refs: JSON.stringify((patch.references ?? cur.references).slice(0, MAX_ELEMENT_PHOTOS)),
loras: JSON.stringify(patch.loras ?? cur.loras),
status: patch.status ?? cur.status,
now: Date.now(),
diff --git a/src/server/loras.ts b/src/server/loras.ts
index 5fa4906a..a6f9e681 100644
--- a/src/server/loras.ts
+++ b/src/server/loras.ts
@@ -302,6 +302,17 @@ export async function ensureLorasOnComfy(loras: LoraRef[] | undefined, listed: s
for (const l of missing) {
const entry = libraryEntry(l);
const name = loraName(l);
+ // The user's own trained LoRA: Fuobe's copy goes into the folder (no download), else fal's copy is fetched.
+ const own = l.own ? ownCopy(l.file) : null;
+ if (own && dir) {
+ const dest = lorasPath(dir, l.file);
+ onProgress?.(`Copying ${name} into ComfyUI's LoRA folder`);
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
+ fs.copyFileSync(own, dest);
+ recordCopy({ file: l.file, target: "comfyui", sourceUrl: `fuobe:${l.file}`, version: null, hostedUrl: null, sha256: sha256File(dest), sizeBytes: fs.statSync(dest).size, licence: null });
+ continue;
+ }
+ if (l.own && !l.url && !own) throw new LoraError(`${name} isn't on this machine any more: train the element again, or put ${l.file} in ComfyUI/models/loras`);
if (!l.url && !entry) throw new LoraError(`ComfyUI doesn't have ${l.file}: put it in ComfyUI/models/loras`);
if (!dir) {
const where = entry?.page ?? (l.url ? redact(l.url) : "");
@@ -334,6 +345,10 @@ export async function prepareCloudLoras(
const name = loraName(l);
// The library's licence counts even when the ref carries none: a GPU-only file never reaches a provider.
if (localOnly(l)) throw new LoraError(`${name} runs only on your GPU (its licence doesn't allow hosting it)`);
+ if (l.own && !l.hostedUrl) {
+ out.push(await sendOwnLora(l, target, upload, onProgress));
+ continue;
+ }
if (cloudPath(l)) {
out.push(l);
continue;
@@ -389,6 +404,83 @@ export async function prepareCloudLoras(
return out;
}
+// ---------------------------------------------------------------------------
+// The user's own trained LoRAs (Fuobe Soul ID)
+
+/** Where Fuobe keeps the LoRAs its trainings made (fuobe/<handle>-<id>.safetensors under it). */
+export const TRAINED_DIR = LORA_CACHE_DIR;
+
+/** Fuobe's own copy of a trained LoRA, when it has one. */
+export function ownCopy(file: string): string | null {
+ try {
+ const p = lorasPath(TRAINED_DIR, file);
+ return fs.existsSync(p) ? p : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Keep a trained LoRA in Fuobe's own folder: copied from a file on this machine (AI-Toolkit's output, ComfyUI's
+ * folder) or downloaded from the trainer's URL (fal storage, which states no hash: the length must match).
+ */
+export async function keepTrainedLora(file: string, from: { path?: string; url?: string }): Promise<string> {
+ const dest = lorasPath(TRAINED_DIR, file);
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
+ if (from.path) {
+ if (path.resolve(from.path) !== dest) fs.copyFileSync(from.path, dest);
+ return dest;
+ }
+ if (!from.url) throw new LoraError(`Nowhere to copy ${file} from`);
+ return (await downloadLora({ file, url: from.url }, TRAINED_DIR)).path;
+}
+
+/** Record the URL a trainer left a LoRA at (fal's own storage), so cloud runs use it while it lives. */
+export function recordTrainedMirror(file: string, target: "fal" | "replicate", url: string): void {
+ const own = ownCopy(file);
+ recordCopy({
+ file,
+ target,
+ sourceUrl: url,
+ version: null,
+ hostedUrl: url,
+ sha256: own ? sha256File(own) : null,
+ sizeBytes: own ? fs.statSync(own).size : null,
+ licence: { own: true },
+ });
+}
+
+/**
+ * A trained LoRA on its way to fal or Replicate: the copy already there while it lives (fal's from the training, or
+ * one Fuobe sent), else Fuobe's copy sent once (the user's own LoRA, trained on their photos: no licence stops it),
+ * else the trainer's URL as a last try. A LoRA only ComfyUI has can't go.
+ */
+async function sendOwnLora(l: LoraRef, target: "fal" | "replicate", upload: (data: Buffer, name: string) => Promise<string>, onProgress?: (m: string) => void): Promise<LoraRef> {
+ const name = loraName(l);
+ const cached = getCopy(l.file, target);
+ if (cached?.hostedUrl && Date.now() - cached.createdAt < MIRROR_TTL_MS[target]) return { ...l, hostedUrl: cached.hostedUrl };
+ const comfyDir = getSetting("comfyLorasDir");
+ const inComfy = (() => {
+ if (!comfyDir) return null;
+ try {
+ const p = lorasPath(comfyDir, l.file);
+ return fs.existsSync(p) ? p : null;
+ } catch {
+ return null;
+ }
+ })();
+ const local = ownCopy(l.file) ?? inComfy;
+ if (local) {
+ onProgress?.(`Sending ${name} to ${target === "fal" ? "fal.ai" : "Replicate"} (once)`);
+ const data = fs.readFileSync(local);
+ const hostedUrl = await upload(data, path.basename(l.file));
+ recordCopy({ file: l.file, target, sourceUrl: `fuobe:${l.file}`, version: null, hostedUrl, sha256: crypto.createHash("sha256").update(data).digest("hex"), sizeBytes: data.length, licence: { own: true } });
+ return { ...l, hostedUrl };
+ }
+ if (l.url) return { ...l, hostedUrl: l.url };
+ throw new LoraError(`${name} exists only on your GPU's machine, so it can't run in the cloud: run it on your GPU, or train it in the cloud`);
+}
+
/**
* Download a library LoRA into the LoRA folder ahead of a run (Settings → LoRAs). Returns the copy recorded.
*/
diff --git a/src/server/training.ts b/src/server/training.ts
index 9681c062..2f2f9530 100644
--- a/src/server/training.ts
+++ b/src/server/training.ts
@@ -3,30 +3,54 @@ import fs from "node:fs";
import path from "node:path";
import { nanoid } from "nanoid";
import type { ElementLora, StudioElement } from "@/lib/catalog/elements";
-import { aiToolkitJob, getTrainingTarget, trainingCaption, triggerFor, type TrainingTarget } from "@/lib/catalog/training";
+import {
+ aiToolkitJob,
+ datasetName,
+ falTrainingInput,
+ familyOfModel,
+ getTrainer,
+ getTrainingTarget,
+ needsConsent,
+ photosBlocker,
+ SOUL_ID_COPY,
+ SOUL_ID_PHOTOS,
+ TRAINING_FAMILIES,
+ trainingCaption,
+ trainingKind,
+ triggerFor,
+ type TrainingFamily,
+ type TrainingTarget,
+} from "@/lib/catalog/training";
import { DATA_DIR, db } from "./db";
import { getElement, updateElement } from "./elements";
+import { keepTrainedLora, lorasPath, ownCopy, recordTrainedMirror } from "./loras";
import { falFetch, falProvider } from "./providers/fal";
-import { hfFetch, hfUpload, higgsfieldKey } from "./providers/higgsfield";
import { ProviderError } from "./providers/types";
-import { getSetting } from "./settings";
+import { engineMode, getSetting } from "./settings";
import { readRef } from "./storage";
import { zip } from "./zip";
/**
- * Identity training (Soul ID parity): Higgsfield custom references, fal's Z-Image LoRA trainer,
- * or AI-Toolkit on your own GPU. Jobs are polled by the same background runner as generations.
+ * Fuobe Soul ID (build plan O3): an element's photos trained as a LoRA on fal's hosted trainers or AI-Toolkit on
+ * the user's GPU (src/lib/catalog/training.ts has the targets). Jobs are polled by the same background runner as
+ * generations. Every LoRA a training makes is kept by Fuobe (src/server/loras.ts) so it runs on both engines.
+ * With no key or trainer set (and demo mode not off), a training is a demo: it runs its course in a few seconds
+ * and attaches nothing real.
*/
export interface Training {
id: string;
elementId: string;
target: string;
- provider: TrainingTarget["provider"];
+ provider: TrainingTarget["provider"] | "demo" | "higgsfield";
+ family: TrainingFamily | null;
status: "queued" | "running" | "succeeded" | "failed";
progress: number | null;
message: string | null;
trigger: string | null;
error: string | null;
+ /** What it cost (fal's price for the steps), null when free or unknown. */
+ costUsd: number | null;
+ photos: number | null;
createdAt: number;
completedAt: number | null;
}
@@ -49,19 +73,38 @@ interface Row {
completed_at: number | null;
}
-const toTraining = (r: Row): Training => ({
- id: r.id,
- elementId: r.element_id,
- target: r.target,
- provider: r.provider,
- status: r.status,
- progress: r.progress,
- message: r.message,
- trigger: r.trigger_word,
- error: r.error,
- createdAt: r.created_at,
- completedAt: r.completed_at,
-});
+/** What a training row keeps in meta_json. */
+interface Meta {
+ statusUrl?: string;
+ responseUrl?: string;
+ name?: string;
+ family?: TrainingFamily;
+ photos?: number;
+ /** When the person's consent was confirmed (characters only). */
+ consentAt?: number;
+}
+
+const metaOf = (r: Pick<Row, "meta_json">): Meta => JSON.parse(r.meta_json ?? "{}") as Meta;
+
+const toTraining = (r: Row): Training => {
+ const meta = metaOf(r);
+ return {
+ id: r.id,
+ elementId: r.element_id,
+ target: r.target,
+ provider: r.provider,
+ family: meta.family ?? getTrainingTarget(r.target)?.family ?? null,
+ status: r.status,
+ progress: r.progress,
+ message: r.message,
+ trigger: r.trigger_word,
+ error: r.error,
+ costUsd: r.cost_usd,
+ photos: meta.photos ?? null,
+ createdAt: r.created_at,
+ completedAt: r.completed_at,
+ };
+};
function update(id: string, fields: Partial<Row>) {
const keys = Object.keys(fields);
@@ -78,39 +121,75 @@ export function listTrainings(elementId?: string): Training[] {
return (rows as Row[]).map(toTraining);
}
-/** Can this target run here right now? Returns the reason it can't, or null. */
+const ENGINE_MODE = "Engine mode";
+
+/** Why this target can't train for real here right now (a key, a trainer, the engine mode), or null. */
export function trainingBlocker(t: TrainingTarget): string | null {
- if (t.provider === "higgsfield" && !higgsfieldKey()) return "Add a Higgsfield API key in Settings";
+ const mode = engineMode();
+ if (mode !== "both" && mode !== t.engine) {
+ return mode === "open"
+ ? `This install is set to open source only (Settings → ${ENGINE_MODE}): train on your GPU`
+ : `This install is set to paid cloud APIs only (Settings → ${ENGINE_MODE}): train in the cloud`;
+ }
if (t.provider === "fal" && !getSetting("falKey")) return "Add a fal.ai key in Settings";
if (t.provider === "ai-toolkit" && !getSetting("aiToolkitUrl")) return "Set your AI-Toolkit URL in Settings (or download the training kit)";
return null;
}
-export function startTraining(elementId: string, targetId: string): Training {
+/**
+ * Whether a training runs as a demo: demo mode is on, or its key or trainer is missing and demo mode isn't off
+ * (Settings → Demo mode). The engine mode still rules: a demo never stands in for an engine this install turned off.
+ */
+export function demoTraining(t: TrainingTarget): boolean {
+ const why = trainingBlocker(t);
+ if (why?.includes(ENGINE_MODE)) return false;
+ const demo = getSetting("demoMode");
+ return demo === "on" || (!!why && demo !== "off");
+}
+
+/** The targets as the API lists them: each with what stops it and whether it would run as a demo. */
+export const describeTargets = (targets: TrainingTarget[]) =>
+ targets.map((t) => {
+ const demo = demoTraining(t);
+ return { ...t, blocker: demo ? null : trainingBlocker(t), demo, licence: getTrainer(t.trainer)?.licence ?? "Apache-2.0" };
+ });
+
+const isAudio = (r: string) => /\.(wav|mp3|ogg|flac|m4a|webm)$/i.test(r);
+/** The photos a training uses: the element's images, up to Soul ID's 80. */
+const photosOf = (el: StudioElement) => el.references.filter((r) => !isAudio(r)).slice(0, SOUL_ID_PHOTOS.max);
+
+export function startTraining(elementId: string, targetId: string, opts: { consent?: boolean } = {}): Training {
const el = getElement(elementId);
const target = getTrainingTarget(targetId);
if (!el) throw new Error("Element not found");
if (!target) throw new Error("Unknown training target");
if (el.kind === "voice") throw new Error("Voices don't need training — they're cloned from the sample");
- const images = el.references.filter((r) => !/\.(wav|mp3|ogg|flac|m4a|webm)$/i.test(r));
- if (images.length < target.minImages) throw new Error(`Add at least ${target.minImages} photos of ${el.name} first (you have ${images.length})`);
+ if (!target.kinds.includes(trainingKind(el.kind))) {
+ throw new Error(trainingKind(el.kind) === "style" ? `${el.name} is a style: pick a style training` : `That training is for styles: pick a character training for ${el.name}`);
+ }
+ if (needsConsent(el.kind) && !opts.consent) throw new Error(SOUL_ID_COPY.needsConsent);
+ const images = photosOf(el);
+ const few = photosBlocker(images.length, el.name);
+ if (few) throw new Error(few);
+ const demo = demoTraining(target);
const blocker = trainingBlocker(target);
- if (blocker) throw new Error(blocker);
+ if (blocker && !demo) throw new Error(blocker);
if (db().prepare("SELECT 1 FROM trainings WHERE element_id = ? AND target = ? AND status IN ('queued','running')").get(elementId, targetId)) {
- throw new Error(`${el.name} is already training for ${target.name}`);
+ throw new Error(`${el.name} is already training here`);
}
const now = Date.now();
+ const meta: Meta = { family: target.family, photos: images.length, ...(needsConsent(el.kind) && { consentAt: now }) };
const row: Row = {
id: nanoid(12),
element_id: elementId,
target: targetId,
- provider: target.provider,
- status: "queued",
- progress: null,
- message: "Preparing photos",
- external_id: null,
- meta_json: null,
- trigger_word: target.provider === "higgsfield" ? null : triggerFor(el.handle),
+ provider: demo ? "demo" : target.provider,
+ status: demo ? "running" : "queued",
+ progress: demo ? 0 : null,
+ message: demo ? "Demo training" : "Preparing photos",
+ external_id: demo ? "demo" : null,
+ meta_json: JSON.stringify(meta),
+ trigger_word: triggerFor(el.handle),
error: null,
cost_usd: null,
created_at: now,
@@ -121,10 +200,12 @@ export function startTraining(elementId: string, targetId: string): Training {
.prepare(`INSERT INTO trainings (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
.run(row);
updateElement(elementId, { status: "training" });
- submittingTrainings().add(row.id);
- void submit(row.id, el, target, row.trigger_word ?? "", images)
- .catch((e) => fail(row.id, el.id, (e as Error).message))
- .finally(() => submittingTrainings().delete(row.id));
+ if (!demo) {
+ submittingTrainings().add(row.id);
+ void submit(row.id, el, target, row.trigger_word ?? "", images)
+ .catch((e) => fail(row.id, el.id, (e as Error).message))
+ .finally(() => submittingTrainings().delete(row.id));
+ }
return toTraining(row);
}
@@ -138,6 +219,8 @@ const submittingTrainings = (): Set<string> => (globalThis.__fuobeTrainingSubmit
const MAX_TRAINING_MS = 8 * 3_600_000;
/** A queued training this old that nothing is uploading was cut off by a restart. */
const STALE_TRAINING_MS = 2 * 60 * 1000;
+/** How long a demo training takes. */
+export const DEMO_TRAINING_MS = 8_000;
function fail(id: string, elementId: string, error: string) {
update(id, { status: "failed", error, message: null, completed_at: Date.now() });
@@ -150,23 +233,32 @@ function settleElement(elementId: string) {
updateElement(elementId, { status: busy ? "training" : "ready" });
}
-function addIdentity(elementId: string, loras: ElementLora[]) {
+/**
+ * Put a trained LoRA on the element. A retrain replaces the earlier LoRA of the same family (and the per-model LoRAs
+ * from before O3 that family covers); another family's LoRA stays (Fuobe Soul and Fuobe Soul HD side by side).
+ */
+function addIdentity(elementId: string, lora: ElementLora) {
const el = getElement(elementId);
if (!el) return;
- // A retrain replaces the previous identity for the same model.
- const kept = el.loras.filter((l) => !loras.some((n) => n.modelId === l.modelId));
- updateElement(elementId, { loras: [...kept, ...loras] });
+ const fam = lora.family;
+ const covered = (l: ElementLora) => !l.referenceId && (fam ? (l.family ?? familyOfModel(l.modelId)) === fam : l.modelId === lora.modelId);
+ updateElement(elementId, { loras: [...el.loras.filter((l) => !covered(l)), lora] });
}
-/** Photos + one caption per photo: "photo of <trigger>, <description>". */
+/** A trained LoRA's file in ComfyUI's loras folder (and Fuobe's copy): one name per training, so a retrain never reuses a cached one. */
+export function trainedFileName(handle: string, trainingId: string): string {
+ const base = handle.toLowerCase().replace(/[^a-z0-9_-]/g, "") || "element";
+ return `fuobe/${base}-${trainingId.slice(0, 6).toLowerCase().replace(/[^a-z0-9]/g, "x")}.safetensors`;
+}
+
+/** Photos + one caption per photo ("photo of <trigger>, <description>"), named 001.jpg + 001.txt. */
async function dataset(el: StudioElement, trigger: string, images: string[]) {
const caption = trainingCaption(el.kind === "style" ? "style" : "character", trigger, el.description);
const files: { name: string; data: Buffer }[] = [];
for (const [i, ref] of images.entries()) {
const f = await readRef(ref);
const ext = f.contentType === "image/png" ? "png" : f.contentType === "image/webp" ? "webp" : "jpg";
- const base = `${String(i + 1).padStart(2, "0")}`;
- files.push({ name: `${base}.${ext}`, data: f.data }, { name: `${base}.txt`, data: Buffer.from(caption) });
+ files.push({ name: datasetName(i, ext), data: f.data }, { name: datasetName(i, "txt"), data: Buffer.from(caption) });
}
return { files, caption };
}
@@ -183,40 +275,26 @@ async function aitk(pathname: string, init: RequestInit = {}) {
return body as Record<string, unknown>;
}
-async function submit(id: string, el: StudioElement, t: TrainingTarget, trigger: string, images: string[]) {
- if (t.provider === "higgsfield") {
- update(id, { message: `Uploading ${images.length} photos` });
- const urls: string[] = [];
- for (const ref of images) {
- const f = await readRef(ref);
- urls.push(await hfUpload(f.data, f.contentType));
- }
- const res = (await hfFetch("v1/custom-references", {
- method: "POST",
- body: JSON.stringify({
- name: el.name.slice(0, 100),
- model_version: t.id === "soul-id-cinema" ? "cinema" : "v2",
- input_images: urls.map((u) => ({ type: "image_url", image_url: u })),
- }),
- })) as { id: string; status?: string };
- update(id, { external_id: res.id, status: "running", message: "Training on Higgsfield" });
- return;
- }
+/** The fal queue URL of a trainer endpoint. */
+export const falQueueUrl = (endpoint: string) => `https://queue.fal.run/${endpoint}`;
+async function submit(id: string, el: StudioElement, t: TrainingTarget, trigger: string, images: string[]) {
+ const meta = metaOf((db().prepare("SELECT meta_json FROM trainings WHERE id = ?").get(id) as Pick<Row, "meta_json"> | undefined) ?? { meta_json: null });
if (t.provider === "fal") {
const { files, caption } = await dataset(el, trigger, images);
- update(id, { message: "Uploading the dataset" });
+ update(id, { message: `Uploading ${images.length} photos` });
const zipUrl = await falProvider.prepareFile(zip(files), "application/zip", "dataset.zip");
- const res = (await falFetch("https://queue.fal.run/fal-ai/z-image-turbo-trainer-v2", {
- method: "POST",
- body: JSON.stringify({ image_data_url: zipUrl, steps: 1000, default_caption: caption }),
- })) as { request_id: string; status_url: string; response_url: string };
+ const res = (await falFetch(falQueueUrl(t.trainer!), { method: "POST", body: JSON.stringify(falTrainingInput(t, zipUrl, caption)) })) as {
+ request_id: string;
+ status_url: string;
+ response_url: string;
+ };
update(id, {
external_id: res.request_id,
- meta_json: JSON.stringify({ statusUrl: res.status_url, responseUrl: res.response_url }),
+ meta_json: JSON.stringify({ ...meta, statusUrl: res.status_url, responseUrl: res.response_url }),
status: "running",
message: "Queued on fal",
- cost_usd: 0.85,
+ cost_usd: t.costUsd,
});
return;
}
@@ -228,11 +306,11 @@ async function submit(id: string, el: StudioElement, t: TrainingTarget, trigger:
fs.mkdirSync(folder, { recursive: true });
for (const f of files) fs.writeFileSync(path.join(folder, f.name), f.data);
const name = `fuobe_${el.handle.toLowerCase()}_${id.slice(0, 6)}`.replace(/[^a-z0-9_]/g, "_");
- const job = aiToolkitJob({ name, trigger, datasetFolder: folder, outputFolder: path.join(root, "output"), kind: el.kind === "style" ? "style" : "character" });
+ const job = aiToolkitJob({ name, trigger, datasetFolder: folder, outputFolder: path.join(root, "output"), kind: el.kind === "style" ? "style" : "character", steps: t.steps, photos: images.length });
const created = await aitk("/api/jobs", { method: "POST", body: JSON.stringify({ name, gpu_ids: "0", job_config: job }) });
const jobId = String(created.id);
await aitk(`/api/jobs/${jobId}/start`);
- update(id, { external_id: jobId, meta_json: JSON.stringify({ name }), status: "running", message: "Queued on AI-Toolkit" });
+ update(id, { external_id: jobId, meta_json: JSON.stringify({ ...meta, name }), status: "running", message: "Queued on AI-Toolkit" });
}
// ---------------------------------------------------------------------------
@@ -241,12 +319,16 @@ async function submit(id: string, el: StudioElement, t: TrainingTarget, trigger:
/** A provider answer that won't change by asking again: the job failed or is gone (not auth, timeouts or rate limits). */
const permanent = (e: unknown) => e instanceof ProviderError && e.status !== undefined && e.status >= 400 && e.status < 500 && ![401, 403, 408, 429].includes(e.status);
+/** Higgsfield's Soul ID training ended with build plan O3. */
+export const RETIRED_SOUL_ID = "Higgsfield Soul ID training was retired: train this character for Fuobe Soul instead (same photos)";
+
export async function pollTrainings(): Promise<void> {
// Trainings a restart cut off mid-upload never reach the trainer: fail them so the element can retrain.
const stale = db()
.prepare("SELECT * FROM trainings WHERE status = 'queued' AND external_id IS NULL AND created_at < ?")
.all(Date.now() - STALE_TRAINING_MS) as Row[];
for (const r of stale) if (!submittingTrainings().has(r.id)) fail(r.id, r.element_id, "Interrupted before it reached the trainer — start it again");
+ for (const r of db().prepare("SELECT * FROM trainings WHERE provider = 'higgsfield' AND status IN ('queued','running')").all() as Row[]) fail(r.id, r.element_id, RETIRED_SOUL_ID);
const rows = db().prepare("SELECT * FROM trainings WHERE status = 'running' AND external_id IS NOT NULL").all() as Row[];
await Promise.all(
rows.map((r) =>
@@ -258,21 +340,37 @@ export async function pollTrainings(): Promise<void> {
);
}
+/** The LoRA a finished training puts on the element. */
+function trainedLora(r: Row, t: TrainingTarget, file: string, fields: Partial<ElementLora>): ElementLora {
+ return {
+ engine: t.engine,
+ modelId: TRAINING_FAMILIES[t.family].lead,
+ family: t.family,
+ target: t.id,
+ file,
+ trigger: r.trigger_word ?? "",
+ strength: 1,
+ trainedAt: Date.now(),
+ ...fields,
+ };
+}
+
async function pollOne(r: Row) {
const t = getTrainingTarget(r.target);
if (!t) return fail(r.id, r.element_id, `Unknown training target ${r.target}`);
if (Date.now() - r.created_at > MAX_TRAINING_MS) return fail(r.id, r.element_id, `Training didn't finish within ${MAX_TRAINING_MS / 3_600_000} hours`);
- const meta = JSON.parse(r.meta_json ?? "{}") as Record<string, string>;
- if (r.provider === "higgsfield") {
- const ref = (await hfFetch(`v1/custom-references/${r.external_id}`)) as { status: string; fail_reason?: string };
- if (ref.status === "completed") {
- addIdentity(r.element_id, t.modelIds.map((modelId) => ({ engine: "cloud", modelId, file: "", trigger: "", referenceId: r.external_id!, strength: 0.9 })));
- return done(r);
- }
- if (ref.status === "failed") return fail(r.id, r.element_id, ref.fail_reason || "Higgsfield couldn't train this character");
- update(r.id, { message: ref.status === "in_progress" ? "Training on Higgsfield" : "In Higgsfield's queue" });
- return;
+ const meta = metaOf(r);
+ const el = getElement(r.element_id);
+ const file = trainedFileName(el?.handle ?? r.element_id, r.id);
+
+ if (r.provider === "demo") {
+ const p = Math.min(1, (Date.now() - r.created_at) / DEMO_TRAINING_MS);
+ if (p < 1) return update(r.id, { progress: p, message: `Demo training · step ${Math.round(p * t.steps)}/${t.steps}` });
+ // Nothing real was trained: the element keeps working from its photos.
+ addIdentity(r.element_id, trainedLora(r, t, file, { demo: true }));
+ return done(r, "Demo: no LoRA was trained. Add a fal.ai key or your AI-Toolkit in Settings, then train again");
}
+
if (r.provider === "fal") {
const s = (await falFetch(`${meta.statusUrl}?logs=1`)) as { status: string; logs?: { message: string }[]; error?: string };
if (s.error) return fail(r.id, r.element_id, `fal couldn't train this: ${s.error}`);
@@ -283,12 +381,25 @@ async function pollOne(r: Row) {
update(r.id, { progress: step ? Number(step[1]) / Number(step[2]) : r.progress, message: s.status === "IN_QUEUE" ? "In fal's queue" : (last ?? "Training") });
return;
}
- const out = (await falFetch(meta.responseUrl)) as { diffusers_lora_file?: { url: string }; lora_file?: { url: string } };
+ const out = (await falFetch(meta.responseUrl!)) as { diffusers_lora_file?: { url: string }; lora_file?: { url: string } };
const url = out.diffusers_lora_file?.url ?? out.lora_file?.url;
if (!url) return fail(r.id, r.element_id, `No LoRA in fal's response: ${JSON.stringify(out).slice(0, 200)}`);
- addIdentity(r.element_id, t.modelIds.map((modelId) => ({ engine: "cloud", modelId, file: "", url, trigger: r.trigger_word!, strength: 1 })));
- return done(r);
+ // Fuobe keeps its own copy (fal's storage isn't forever): open runs copy it into ComfyUI, cloud runs send it again
+ // once fal's copy is old. fal's URL serves cloud runs until then.
+ update(r.id, { message: "Saving the LoRA" });
+ let message: string | null = null;
+ let own = false;
+ try {
+ await keepTrainedLora(file, { url });
+ own = true;
+ } catch (e) {
+ message = `The LoRA is on fal, but Fuobe couldn't keep a copy (${(e as Error).message}): your GPU downloads it from fal when a run needs it`;
+ }
+ recordTrainedMirror(file, "fal", url);
+ addIdentity(r.element_id, trainedLora(r, t, file, { url, ...(own && { own: true as const }) }));
+ return done(r, message);
}
+
// AI-Toolkit
const res = await aitk(`/api/jobs?id=${encodeURIComponent(r.external_id!)}`);
const job = ((res.job ?? res) as Record<string, unknown>) ?? {};
@@ -304,17 +415,23 @@ async function pollOne(r: Row) {
const files = ((filesRes.files ?? []) as { path: string }[]).map((f) => f.path).filter((p) => p.endsWith(".safetensors")).sort();
const latest = files.at(-1);
if (!latest) return fail(r.id, r.element_id, "AI-Toolkit finished but saved no .safetensors file");
- const el = getElement(r.element_id);
- const file = `fuobe/${(el?.handle ?? r.element_id).toLowerCase()}.safetensors`;
const lorasDir = getSetting("comfyLorasDir");
let message: string | null = null;
- if (lorasDir && fs.existsSync(latest)) {
- fs.mkdirSync(path.join(lorasDir, "fuobe"), { recursive: true });
- fs.copyFileSync(latest, path.join(lorasDir, file));
+ let own = false;
+ if (fs.existsSync(latest)) {
+ // Fuobe's copy (for cloud runs and safe keeping), then ComfyUI's.
+ await keepTrainedLora(file, { path: latest });
+ own = true;
+ if (lorasDir) {
+ const dest = lorasPath(lorasDir, file);
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
+ fs.copyFileSync(latest, dest);
+ }
} else {
+ // AI-Toolkit runs on another machine: the file has to be copied by hand.
message = `Copy ${latest} to ComfyUI/models/loras/${file}`;
}
- addIdentity(r.element_id, t.modelIds.map((modelId) => ({ engine: "open", modelId, file, trigger: r.trigger_word!, strength: 1 })));
+ addIdentity(r.element_id, trainedLora(r, t, file, own ? { own: true } : {}));
return done(r, message);
}
@@ -329,12 +446,13 @@ function done(r: Row, message: string | null = null) {
export async function trainingKit(elementId: string): Promise<{ name: string; data: Buffer }> {
const el = getElement(elementId);
if (!el) throw new Error("Element not found");
- const images = el.references.filter((r) => !/\.(wav|mp3|ogg|flac|m4a|webm)$/i.test(r));
+ const images = photosOf(el);
if (!images.length) throw new Error("Add photos first");
const trigger = triggerFor(el.handle);
const { files } = await dataset(el, trigger, images);
const name = `fuobe_${el.handle.toLowerCase()}`.replace(/[^a-z0-9_]/g, "_");
- const job = aiToolkitJob({ name, trigger, datasetFolder: "./dataset", outputFolder: "./output", kind: el.kind === "style" ? "style" : "character" });
+ const job = aiToolkitJob({ name, trigger, datasetFolder: "./dataset", outputFolder: "./output", kind: el.kind === "style" ? "style" : "character", photos: images.length });
+ const file = `fuobe/${el.handle.toLowerCase().replace(/[^a-z0-9_-]/g, "") || "element"}.safetensors`;
const readme = `# Train ${el.name} with AI-Toolkit
1. Install AI-Toolkit: https://github.com/ostris/ai-toolkit (24 GB GPU recommended)
@@ -342,10 +460,11 @@ export async function trainingKit(elementId: string): Promise<{ name: string; da
python run.py ${name}.yaml
-3. Copy the newest file from ./output/${name}/*.safetensors to ComfyUI/models/loras/fuobe/${el.handle.toLowerCase()}.safetensors
-4. In Fuobe, open ${el.name} → Train → "I trained it myself" and enter that file name.
+3. Copy the newest file from ./output/${name}/*.safetensors to ComfyUI/models/loras/${file}
+4. In Fuobe, open ${el.name} → Train → "Train anywhere" and attach that file name.
-Trigger word: ${trigger} — Fuobe adds it to the prompt whenever you @${el.handle} on Z-Image Turbo (open source).
+Trigger word: ${trigger} — Fuobe adds it to the prompt whenever you @${el.handle} on Fuobe Soul, Soul Cinema or
+Z-Image Turbo. Train only on photos you have the right to use${el.kind === "character" ? ", of a person who agreed to it" : ""}.
`;
return {
name: `${name}-training-kit.zip`,
@@ -358,9 +477,36 @@ Trigger word: ${trigger} — Fuobe adds it to the prompt whenever you @${el.hand
};
}
-/** Register a LoRA trained elsewhere (already in ComfyUI/models/loras). */
-export function attachLora(elementId: string, input: { file: string; trigger: string; modelId: string }) {
+/**
+ * Register a Z-Image Turbo LoRA trained elsewhere (already in ComfyUI/models/loras). When the LoRA folder is on this
+ * machine, Fuobe keeps a copy too, so cloud runs can use it.
+ */
+export async function attachLora(elementId: string, input: { file: string; trigger: string; family?: TrainingFamily }) {
const file = input.file.trim().replace(/^\/+/, "");
if (!/\.safetensors$/.test(file) || file.includes("..")) throw new Error("Enter the LoRA's file name inside ComfyUI/models/loras, ending in .safetensors");
- addIdentity(elementId, [{ engine: "open", modelId: input.modelId, file, trigger: input.trigger.trim(), strength: 1 }]);
+ const family = input.family ?? "z-image-turbo";
+ const dir = getSetting("comfyLorasDir");
+ let own = !!ownCopy(file);
+ if (!own && dir) {
+ let src = "";
+ try {
+ src = lorasPath(dir, file);
+ } catch {
+ src = "";
+ }
+ if (src && fs.existsSync(src)) {
+ await keepTrainedLora(file, { path: src });
+ own = true;
+ }
+ }
+ addIdentity(elementId, {
+ engine: "open",
+ modelId: TRAINING_FAMILIES[family].lead,
+ family,
+ file,
+ trigger: input.trigger.trim(),
+ strength: 1,
+ trainedAt: Date.now(),
+ ...(own && { own: true as const }),
+ });
}
diff --git a/tests/training.test.ts b/tests/training.test.ts
index c34ecdf9..e3e99cd8 100644
--- a/tests/training.test.ts
+++ b/tests/training.test.ts
@@ -3,28 +3,120 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
-import { getModel } from "@/lib/catalog";
-import { aiToolkitJob, TRAINING_TARGETS, triggerFor } from "@/lib/catalog/training";
+import { getModel, getPreset } from "@/lib/catalog";
+import { applyMentions, type ElementLora, type StudioElement } from "@/lib/catalog/elements";
+import { onEngine, runsOn } from "@/lib/catalog/engines";
+import { planGeneration } from "@/lib/catalog/plan";
+import { HOSTED_TRAINERS } from "@/lib/catalog/trainers.generated";
+import {
+ aiToolkitJob,
+ datasetName,
+ falTrainingInput,
+ getTrainer,
+ getTrainingTarget,
+ identityFor,
+ loraFamily,
+ needsConsent,
+ photosBlocker,
+ photoTips,
+ targetsFor,
+ trainerCost,
+ TRAINING_FAMILIES,
+ TRAINING_TARGETS,
+ triggerFor,
+ usableOn,
+} from "@/lib/catalog/training";
import { buildPayload } from "@/lib/catalog/payload";
import { zip } from "@/server/zip";
-describe("identity training", () => {
+const ROOT = path.resolve(__dirname, "..");
+
+describe("Fuobe Soul ID targets (build plan O3)", () => {
it("makes short, rare trigger words", () => {
expect(triggerFor("Nova_Reyes")).toBe("nvrysfz");
expect(triggerFor("Al")).toBe("alfz");
});
- it("only targets models that exist, with the open target on the open engine", () => {
- for (const t of TRAINING_TARGETS) for (const id of t.modelIds) expect(getModel(id)?.engine, `${t.id} → ${id}`).toBe(t.engine);
+ it("has no Higgsfield target: every one trains on fal or the user's GPU", () => {
+ expect(TRAINING_TARGETS.map((t) => t.provider).every((p) => p === "fal" || p === "ai-toolkit")).toBe(true);
+ expect(TRAINING_TARGETS.map((t) => t.id)).not.toContain("soul-id-v2");
+ expect(TRAINING_TARGETS.map((t) => t.id)).not.toContain("soul-id-cinema");
+ });
+
+ it("retargets training to the Fuobe Soul models, whose LoRAs run on both engines", () => {
+ for (const t of TRAINING_TARGETS) {
+ expect(t.modelIds.length).toBeGreaterThan(0);
+ for (const id of t.modelIds) expect(getModel(id), `${t.id} → ${id}`).toBeDefined();
+ }
+ expect(getTrainingTarget("fal-z-image")!.modelIds).toEqual(expect.arrayContaining(["fuobe-soul", "fuobe-soul-cinema"]));
+ expect(getTrainingTarget("aitk-z-image")!.modelIds).toEqual(expect.arrayContaining(["fuobe-soul", "fuobe-soul-cinema"]));
+ expect(getTrainingTarget("fal-qwen-2512")!.modelIds).toContain("fuobe-soul-hd");
+ // The family's lead model is an Original on both engines.
+ for (const f of Object.values(TRAINING_FAMILIES)) {
+ const lead = getModel(f.lead)!;
+ expect(runsOn(lead, "open") && runsOn(lead, "cloud")).toBe(true);
+ }
+ });
+
+ it("trains only on commercial weights, at fal's price for the steps (research §3.3)", () => {
+ for (const t of TRAINING_TARGETS.filter((x) => x.provider === "fal")) {
+ const tr = getTrainer(t.trainer)!;
+ expect(tr, t.id).toBeDefined();
+ expect(tr.commercial).toBe(true);
+ expect(tr.licence).toBe("Apache-2.0");
+ }
+ // $0.85 per 1,000 steps: the default 2,000-step run is $1.70 (research §4.5).
+ expect(getTrainingTarget("fal-z-image")).toMatchObject({ steps: 2000, learningRate: 0.0005, costUsd: 1.7, price: "≈ $1.70 (2,000 steps)" });
+ expect(getTrainingTarget("fal-qwen-2512")).toMatchObject({ steps: 1000, costUsd: 1.5 });
+ expect(getTrainingTarget("fal-z-image-style")).toMatchObject({ steps: 1500, costUsd: 3.39, extra: { training_type: "style" } });
+ expect(getTrainingTarget("aitk-z-image")).toMatchObject({ price: "Free", costUsd: 0 });
+ // fal's floors: 500 billed steps on Z-Image Turbo v2.
+ expect(trainerCost(getTrainer("fal-ai/z-image-turbo-trainer-v2"), 100)).toBe(0.43);
+ });
+
+ it("offers subject trainings to characters and style trainings to styles, consent for people only", () => {
+ expect(targetsFor("character").map((t) => t.id)).toEqual(["aitk-z-image", "fal-z-image", "fal-qwen-2512"]);
+ expect(targetsFor("style").map((t) => t.id)).toEqual(["aitk-z-image", "fal-z-image-style"]);
+ expect(targetsFor("voice")).toEqual([]);
+ expect(needsConsent("character")).toBe(true);
+ expect(needsConsent("style")).toBe(false);
+ });
+
+ it("follows Higgsfield's photo rules: 5 to start, 20+ recommended, 80 at most", () => {
+ expect(photosBlocker(4, "Maya")).toMatch(/at least 5 photos of Maya/);
+ expect(photosBlocker(5)).toBeNull();
+ expect(photosBlocker(81)).toMatch(/up to 80/);
+ const photos = Array.from({ length: 8 }, (_, i) => ({ key: `p${i % 7}`, width: i === 0 ? 400 : 1024, height: 1024 }));
+ const tips = photoTips(photos);
+ expect(tips[0]).toMatch(/20\+ photos.*you have 8/);
+ expect(tips.join(" ")).toMatch(/1 photo is smaller than 512 px/);
+ expect(tips.join(" ")).toMatch(/1 duplicate photo/);
+ expect(photoTips(Array.from({ length: 20 }, (_, i) => ({ key: String(i) })))).toEqual([]);
});
- it("writes AI-Toolkit jobs for Z-Image Turbo with the training adapter", () => {
+ it("writes fal's request from the trainer's own fields: zip, steps, caption, learning rate, training type", () => {
+ expect(falTrainingInput(getTrainingTarget("fal-z-image")!, "https://fal/zip", "photo of mayafz")).toEqual({
+ image_data_url: "https://fal/zip",
+ steps: 2000,
+ default_caption: "photo of mayafz",
+ learning_rate: 0.0005,
+ });
+ expect(falTrainingInput(getTrainingTarget("fal-z-image-style")!, "z", "mayafz style")).toEqual({ image_data_url: "z", steps: 1500, default_caption: "mayafz style", training_type: "style" });
+ expect(datasetName(0, "jpg")).toBe("001.jpg");
+ expect(datasetName(11, "txt")).toBe("012.txt");
+ });
+
+ it("writes AI-Toolkit jobs for Z-Image Turbo with the training adapter, rank 16–32", () => {
const job = aiToolkitJob({ name: "x", trigger: "nvrysfz", datasetFolder: "/d", outputFolder: "/o" });
const p = job.config.process[0];
expect(p.trigger_word).toBe("nvrysfz");
expect(p.model.arch).toBe("zimage:turbo");
- expect(p.model.assistant_lora_path).toMatch(/training_adapter/);
+ expect(p.model.assistant_lora_path).toMatch(/training_adapter_v2/);
expect(p.datasets[0].folder_path).toBe("/d");
+ expect(p.train.steps).toBe(2000);
+ expect(p.network.linear).toBe(16);
+ expect(aiToolkitJob({ name: "x", trigger: "t", datasetFolder: "/d", outputFolder: "/o", photos: 30 }).config.process[0].network.linear).toBe(32);
+ expect(aiToolkitJob({ name: "x", trigger: "t", datasetFolder: "/d", outputFolder: "/o", kind: "style", photos: 30 }).config.process[0]).toMatchObject({ network: { linear: 16 }, train: { steps: 1500 } });
});
it("switches hosted Z-Image to its LoRA endpoint only when a LoRA URL is present", () => {
@@ -36,8 +128,95 @@ describe("identity training", () => {
it("writes zips other tools can read", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-zip-"));
const file = path.join(dir, "kit.zip");
- fs.writeFileSync(file, zip([{ name: "dataset/01.txt", data: Buffer.from("photo of nvrysfz") }, { name: "a.yaml", data: Buffer.from("{}") }]));
- const out = execFileSync("python3", ["-I", "-c", "import sys,zipfile;z=zipfile.ZipFile(sys.argv[1]);print(z.testzip(), z.read('dataset/01.txt').decode())", file]).toString();
+ fs.writeFileSync(file, zip([{ name: "dataset/001.txt", data: Buffer.from("photo of nvrysfz") }, { name: "a.yaml", data: Buffer.from("{}") }]));
+ const out = execFileSync("python3", ["-I", "-c", "import sys,zipfile;z=zipfile.ZipFile(sys.argv[1]);print(z.testzip(), z.read('dataset/001.txt').decode())", file]).toString();
expect(out.trim()).toBe("None photo of nvrysfz");
});
});
+
+describe("gen-trainers.py", () => {
+ it("writes what is committed (the trainers match the research)", () => {
+ const file = path.join(ROOT, "src/lib/catalog/trainers.generated.ts");
+ const before = fs.readFileSync(file, "utf8");
+ execFileSync("python3", ["scripts/gen-trainers.py"], { cwd: ROOT });
+ expect(fs.readFileSync(file, "utf8")).toBe(before);
+ });
+ it("keeps the non-commercial trainers flagged (never a Soul ID route)", () => {
+ expect(HOSTED_TRAINERS.find((t) => t.id === "fal-ai/flux-2-klein-9b-base-trainer")?.commercial).toBe(false);
+ const used = new Set(TRAINING_TARGETS.map((t) => t.trainer).filter(Boolean));
+ expect(HOSTED_TRAINERS.filter((t) => used.has(t.id)).every((t) => t.commercial)).toBe(true);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// The trained LoRA on a run
+
+const lora = (o: Partial<ElementLora>): ElementLora => ({ engine: "cloud", modelId: "fuobe-soul", family: "z-image-turbo", file: "fuobe/maya-abc123.safetensors", trigger: "myfz", strength: 1, ...o });
+const maya = (loras: ElementLora[]): StudioElement => ({
+ id: "m1",
+ name: "Maya",
+ handle: "Maya",
+ kind: "character",
+ description: null,
+ references: ["/api/files/a.png", "/api/files/b.png"],
+ loras,
+ status: "ready",
+ createdAt: 0,
+});
+
+describe("a Soul ID on every model of its family, on both engines", () => {
+ const soul = getModel("fuobe-soul")!;
+ const openSoul = onEngine(soul, "open");
+ const cloudSoul = onEngine(soul, "cloud");
+
+ it("reads the family of LoRAs from before O3 from the model they were trained for", () => {
+ expect(loraFamily({ modelId: "oss-z-image-turbo" })).toBe("z-image-turbo");
+ expect(loraFamily({ modelId: "z-image-turbo-cloud" })).toBe("z-image-turbo");
+ expect(loraFamily({ modelId: "soul-2", referenceId: "ref" })).toBeUndefined();
+ });
+
+ it("runs a fal-trained LoRA on the cloud by URL and on the open engine from Fuobe's copy", () => {
+ const fal = lora({ url: "https://v3.fal.media/maya.safetensors", own: true });
+ expect(usableOn(fal, "cloud") && usableOn(fal, "open")).toBe(true);
+ expect(identityFor([fal], cloudSoul)).toBe(fal);
+ expect(identityFor([fal], openSoul)).toBe(fal);
+ expect(identityFor([fal], onEngine(getModel("fuobe-soul-cinema")!, "cloud"))).toBe(fal);
+ // Another family needs its own training.
+ expect(identityFor([fal], onEngine(getModel("fuobe-soul-hd")!, "cloud"))).toBeUndefined();
+ });
+
+ it("runs a GPU-trained LoRA in the cloud only when Fuobe keeps its file", () => {
+ const gpu = lora({ engine: "open" });
+ expect(usableOn(gpu, "open")).toBe(true);
+ expect(usableOn(gpu, "cloud")).toBe(false);
+ expect(usableOn({ ...gpu, own: true }, "cloud")).toBe(true);
+ });
+
+ it("prefers the LoRA trained on the run's engine, then the newest", () => {
+ const gpu = lora({ engine: "open", own: true, trainedAt: 2, file: "fuobe/gpu.safetensors" });
+ const cloud = lora({ url: "https://x/c.safetensors", trainedAt: 1, file: "fuobe/cloud.safetensors" });
+ expect(identityFor([gpu, cloud], openSoul)).toBe(gpu);
+ expect(identityFor([gpu, cloud], cloudSoul)).toBe(cloud);
+ });
+
+ it("never uses a demo training or a Higgsfield Soul ID", () => {
+ expect(identityFor([lora({ demo: true, url: "x" })], cloudSoul)).toBeUndefined();
+ expect(identityFor([{ engine: "cloud", modelId: "fuobe-soul", file: "", trigger: "", referenceId: "ref" }], cloudSoul)).toBeUndefined();
+ });
+
+ it("puts the @character's LoRA first on Fuobe Soul, at the character strength's scale", () => {
+ const el = maya([lora({ url: "https://v3.fal.media/maya.safetensors", own: true })]);
+ const { request } = applyMentions({ feature: "image", modelId: soul.id, engine: "cloud", prompt: "@Maya on a beach" }, cloudSoul, [el]);
+ expect(request.loras).toEqual([{ file: "fuobe/maya-abc123.safetensors", url: "https://v3.fal.media/maya.safetensors", strength: 1, trigger: "myfz", own: true }]);
+ expect(request.inputs?.images).toBeUndefined();
+ const plan = planGeneration({ ...request, params: { extra: { characterStrength: 0.5 } } }, (id) => (id === soul.id ? cloudSoul : getModel(id)), getPreset);
+ expect(plan.loras[0]).toMatchObject({ file: "fuobe/maya-abc123.safetensors", strength: 0.8 });
+ expect(plan.prompt).toMatch(/myfz Maya on a beach/);
+ });
+
+ it("falls back to reference photos when no LoRA runs there", () => {
+ const el = maya([lora({ engine: "open" })]);
+ const nb = getModel("nano-banana-pro")!;
+ expect(applyMentions({ feature: "image", modelId: nb.id, prompt: "@Maya" }, nb, [el]).request.inputs?.images).toEqual(["/api/files/a.png", "/api/files/b.png"]);
+ });
+});