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.

Soul ID training: Higgsfield Soul ID, fal Z-Image LoRA, AI-Toolkit on your GPU

Claude81a90020d34d
diff --git a/scripts/gen-cloud-models.py b/scripts/gen-cloud-models.py
index 0d119687..1b8a3e4c 100644
--- a/scripts/gen-cloud-models.py
+++ b/scripts/gen-cloud-models.py
@@ -121,7 +121,7 @@ model("wan-2-7-image", "Wan 2.7 Image", "Alibaba Wan", "wan", "image",
[("t2i", "fal-ai/wan/v2.7/pro/text-to-image"), ("edit", "fal-ai/wan/v2.7/pro/edit")], defaults={"aspectRatio": "16:9"})
model("z-image-turbo-cloud", "Z-Image Turbo (hosted)", "Alibaba Tongyi", "z-image", "image",
"Sub-second photoreal images",
- [("t2i", "fal-ai/z-image/turbo")], badges=["fast"], defaults={"aspectRatio": "1:1"})
+ [("t2i", "fal-ai/z-image/turbo", "fal", {"loraEndpoint": "fal-ai/z-image/turbo/lora"})], badges=["fast"], defaults={"aspectRatio": "1:1"})
model("imagen-4", "Imagen 4", "Google", "imagen", "image", "Google's photoreal text-to-image",
[("t2i", "google/imagen-4", "replicate")], defaults={"aspectRatio": "1:1"})
@@ -492,6 +492,10 @@ def build_route(op, ep, provider, m, opts, ropts=None):
route = {"op": op, "provider": provider, "endpoint": ep, "map": fmap}
if ropts.get("note"):
route["note"] = ropts["note"]
+ if ropts.get("loraEndpoint"):
+ if (provider, ropts["loraEndpoint"]) not in EPS:
+ warn(f"{m['id']}: LoRA endpoint {ropts['loraEndpoint']} not in research")
+ route["loraEndpoint"] = ropts["loraEndpoint"]
return route, e
diff --git a/src/app/api/elements/[id]/lora/route.ts b/src/app/api/elements/[id]/lora/route.ts
new file mode 100644
index 00000000..4d775374
--- /dev/null
+++ b/src/app/api/elements/[id]/lora/route.ts
@@ -0,0 +1,18 @@
+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") });
+
+/** Attach a LoRA you trained yourself (already in ComfyUI/models/loras). */
+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 });
+ try {
+ 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 f0aa6033..285ec325 100644
--- a/src/app/api/elements/[id]/route.ts
+++ b/src/app/api/elements/[id]/route.ts
@@ -6,6 +6,8 @@ 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.
+ removeIdentities: z.array(z.string()).optional(),
});
export async function GET(_req: Request, ctx: RouteContext<"/api/elements/[id]">) {
@@ -19,7 +21,10 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/elements/[
const { id } = await ctx.params;
const parsed = Patch.safeParse(await request.json().catch(() => null));
if (!parsed.success) return Response.json({ error: "Invalid element" }, { status: 400 });
- const el = updateElement(id, parsed.data);
+ const { removeIdentities, ...patch } = parsed.data;
+ const current = getElement(id);
+ const loras = removeIdentities && current ? current.loras.filter((l) => !removeIdentities.includes(l.modelId)) : 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]/training-kit/route.ts b/src/app/api/elements/[id]/training-kit/route.ts
new file mode 100644
index 00000000..ef796955
--- /dev/null
+++ b/src/app/api/elements/[id]/training-kit/route.ts
@@ -0,0 +1,14 @@
+import { trainingKit } from "@/server/training";
+
+/** Dataset + AI-Toolkit config + README, to train the element's LoRA on any GPU. */
+export async function GET(_req: Request, ctx: RouteContext<"/api/elements/[id]/training-kit">) {
+ const { id } = await ctx.params;
+ try {
+ const kit = await trainingKit(id);
+ return new Response(new Uint8Array(kit.data), {
+ headers: { "Content-Type": "application/zip", "Content-Disposition": `attachment; filename="${kit.name}"` },
+ });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 422 });
+ }
+}
diff --git a/src/app/api/elements/[id]/trainings/route.ts b/src/app/api/elements/[id]/trainings/route.ts
new file mode 100644
index 00000000..bf9daa95
--- /dev/null
+++ b/src/app/api/elements/[id]/trainings/route.ts
@@ -0,0 +1,29 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { TRAINING_TARGETS } from "@/lib/catalog/training";
+import { ensureRunner } from "@/server/generations";
+import { listTrainings, startTraining, trainingBlocker } from "@/server/training";
+
+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
+ return Response.json({
+ targets: TRAINING_TARGETS.map((t) => ({ ...t, blocker: trainingBlocker(t) })),
+ items: listTrainings(id),
+ });
+}
+
+const Body = z.object({ target: z.string().min(1) });
+
+export async function POST(request: Request, ctx: RouteContext<"/api/elements/[id]/trainings">) {
+ const { id } = await ctx.params;
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ 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 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 422 });
+ }
+}
diff --git a/src/components/elements-view.tsx b/src/components/elements-view.tsx
index 1d2328f7..d417f148 100644
--- a/src/components/elements-view.tsx
+++ b/src/components/elements-view.tsx
@@ -1,6 +1,6 @@
"use client";
-import { AtSign, AudioLines, Check, Copy, Loader2, Pencil, Plus, Trash2, X } from "lucide-react";
+import { AtSign, AudioLines, Check, Copy, GraduationCap, Loader2, Pencil, Plus, Trash2, X } from "lucide-react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useMemo, useState } from "react";
@@ -17,6 +17,7 @@ import { StudioPage } from "@/components/studio/studio-page";
import { fileToSlot, MediaSlot, type SlotValue } from "@/components/studio/media-slot";
import { ELEMENT_ICONS } from "@/components/studio/prompt-input";
import { VoiceRecorder } from "@/components/studio/voice-recorder";
+import { TrainDialog } from "@/components/train-dialog";
import type { StudioConfig } from "@/components/studio/studio-context";
import { useDeleteElement, useElement, useElements, useSaveElement } from "@/lib/api";
import { ELEMENT_KINDS, elementKindInfo, handleFor, type ElementKind, type StudioElement } from "@/lib/catalog/elements";
@@ -267,6 +268,12 @@ function ElementCard({ el }: { el: StudioElement }) {
</div>
</Link>
)}
+ {(el.loras.length > 0 || el.status === "training") && (
+ <span className="pointer-events-none absolute top-2 left-2 inline-flex items-center gap-1 rounded-full bg-background/90 px-2 py-0.5 text-[11px] font-medium text-success shadow-soft backdrop-blur">
+ {el.status === "training" ? <Loader2 className="size-3 animate-spin" /> : <GraduationCap className="size-3" />}
+ {el.status === "training" ? "Training" : "Trained"}
+ </span>
+ )}
<div className="flex items-start justify-between gap-2 p-3">
<div className="min-w-0">
<p className="truncate font-medium">{el.name}</p>
@@ -370,6 +377,7 @@ export function ElementsView() {
export function ElementStudio({ id }: { id: string }) {
const q = useElement(id);
const [editing, setEditing] = useState(false);
+ const [training, setTraining] = useState(false);
const el = q.data;
const config = useMemo<StudioConfig | null>(() => {
if (!el) return null;
@@ -412,12 +420,21 @@ export function ElementStudio({ id }: { id: string }) {
config={config}
initialPrompt={`@${el.handle} `}
header={
- <Button variant="ghost" size="sm" onClick={() => setEditing(true)}>
- <Pencil /> Edit
- </Button>
+ <>
+ {el.kind !== "voice" && (
+ <Button variant={el.loras.length ? "ghost" : "secondary"} size="sm" onClick={() => setTraining(true)}>
+ {el.status === "training" ? <Loader2 className="animate-spin" /> : <GraduationCap />}
+ {el.status === "training" ? "Training…" : el.loras.length ? `Trained · ${el.loras.length}` : "Train"}
+ </Button>
+ )}
+ <Button variant="ghost" size="sm" onClick={() => setEditing(true)}>
+ <Pencil /> Edit
+ </Button>
+ </>
}
/>
<ElementDialog open={editing} onOpenChange={setEditing} element={el} />
+ <TrainDialog open={training} onOpenChange={setTraining} element={el} />
</>
);
}
diff --git a/src/components/train-dialog.tsx b/src/components/train-dialog.tsx
new file mode 100644
index 00000000..316539fe
--- /dev/null
+++ b/src/components/train-dialog.tsx
@@ -0,0 +1,181 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Check, Cloud, Cpu, Download, GraduationCap, Loader2, Trash2 } from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Progress } from "@/components/ui/progress";
+import { getModel } from "@/lib/catalog";
+import type { StudioElement } from "@/lib/catalog/elements";
+import { triggerFor, type TrainingTarget } from "@/lib/catalog/training";
+import { cn } from "@/lib/utils";
+
+interface Training {
+ id: string;
+ target: string;
+ status: "queued" | "running" | "succeeded" | "failed";
+ progress: number | null;
+ message: string | null;
+ error: string | null;
+ createdAt: number;
+}
+
+type Target = TrainingTarget & { blocker: string | null };
+
+function useTrainings(id: string) {
+ return useQuery({
+ queryKey: ["trainings", id],
+ queryFn: async () => (await (await fetch(`/api/elements/${id}/trainings`)).json()) as { targets: Target[]; items: Training[] },
+ refetchInterval: (q) => (q.state.data?.items.some((t) => t.status === "queued" || t.status === "running") ? 3000 : false),
+ });
+}
+
+/** Soul ID: train the element once, then every @mention on that model uses the trained identity. */
+export function TrainDialog({ element, open, onOpenChange }: { element: StudioElement; open: boolean; onOpenChange: (o: boolean) => void }) {
+ const qc = useQueryClient();
+ const q = useTrainings(element.id);
+ const [file, setFile] = useState("");
+ const photos = element.references.length;
+ const refresh = () => {
+ void qc.invalidateQueries({ queryKey: ["trainings", element.id] });
+ void qc.invalidateQueries({ queryKey: ["elements"] });
+ };
+ const start = useMutation({
+ mutationFn: async (target: string) => {
+ const res = await fetch(`/api/elements/${element.id}/trainings`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ target }) });
+ const body = await res.json();
+ if (!res.ok) throw new Error(body.error);
+ return body;
+ },
+ onSuccess: () => {
+ toast.success(`Training ${element.name} — you can keep working`);
+ refresh();
+ },
+ onError: (e) => toast.error((e as Error).message),
+ });
+ const attach = useMutation({
+ mutationFn: async () => {
+ const res = await fetch(`/api/elements/${element.id}/lora`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ file, trigger: triggerFor(element.handle) }),
+ });
+ const body = await res.json();
+ if (!res.ok) throw new Error(body.error);
+ },
+ onSuccess: () => {
+ toast.success("LoRA attached");
+ setFile("");
+ refresh();
+ },
+ onError: (e) => toast.error((e as Error).message),
+ });
+ const remove = async (modelId: string) => {
+ await fetch(`/api/elements/${element.id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ removeIdentities: [modelId] }) });
+ refresh();
+ };
+
+ const latest = (target: string) => q.data?.items.find((t) => t.target === target);
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-[620px]">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <GraduationCap className="size-5" /> Train {element.name}
+ </DialogTitle>
+ <DialogDescription>
+ Train once and {element.name} looks right every time — @{element.handle} then uses the trained identity on that model instead of reference photos. Uses all{" "}
+ {photos} photos; 15–30 varied ones work best.
+ </DialogDescription>
+ </DialogHeader>
+
+ {element.loras.length > 0 && (
+ <div className="space-y-1.5">
+ <p className="text-[12px] font-medium tracking-wide text-muted-foreground uppercase">Trained</p>
+ {element.loras.map((l) => (
+ <div key={l.modelId} className="flex items-center gap-2 rounded-lg border px-3 py-2 text-[13px]">
+ <Check className="size-4 text-success" />
+ <span className="font-medium">{getModel(l.modelId)?.name ?? l.modelId}</span>
+ <span className="truncate text-muted-foreground">{l.referenceId ? "Soul ID" : l.trigger ? `trigger “${l.trigger}”` : l.file}</span>
+ <button onClick={() => void remove(l.modelId)} className="ml-auto text-muted-foreground hover:text-destructive" aria-label="Remove">
+ <Trash2 className="size-3.5" />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ <div className="space-y-2">
+ {(q.data?.targets ?? []).map((t) => {
+ const job = latest(t.id);
+ const busy = job && (job.status === "queued" || job.status === "running");
+ const tooFew = photos < t.minImages;
+ return (
+ <div key={t.id} className={cn("rounded-xl border p-3", busy && "border-primary")}>
+ <div className="flex items-start gap-3">
+ <span className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-lg bg-muted text-muted-foreground">
+ {t.engine === "open" ? <Cpu className="size-4" /> : <Cloud className="size-4" />}
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className="text-[14px] font-medium">{t.name}</p>
+ <p className="text-[12px] text-muted-foreground">{t.description}</p>
+ <p className="mt-1 text-[11px] text-subtle-foreground">
+ {t.price} · {t.eta}
+ </p>
+ </div>
+ <Button size="sm" variant={busy ? "secondary" : "default"} disabled={!!t.blocker || tooFew || !!busy || start.isPending} onClick={() => start.mutate(t.id)}>
+ {busy ? <Loader2 className="animate-spin" /> : null}
+ {busy ? "Training" : job?.status === "succeeded" ? "Retrain" : "Train"}
+ </Button>
+ </div>
+ {(t.blocker || tooFew) && !busy && (
+ <p className="mt-2 text-[12px] text-muted-foreground">
+ {tooFew ? `Needs at least ${t.minImages} photos.` : t.blocker}{" "}
+ {t.blocker && !tooFew && (
+ <Link href="/settings" className="text-brand-text hover:underline">
+ Open Settings
+ </Link>
+ )}
+ </p>
+ )}
+ {busy && (
+ <div className="mt-3 space-y-1">
+ <Progress value={(job.progress ?? 0.05) * 100} className="h-1.5" />
+ <p className="text-[12px] text-muted-foreground">{job.message}</p>
+ </div>
+ )}
+ {job?.status === "failed" && <p className="mt-2 text-[12px] text-destructive">{job.error}</p>}
+ {job?.status === "succeeded" && job.message && <p className="mt-2 text-[12px] text-warning">{job.message}</p>}
+ </div>
+ );
+ })}
+ </div>
+
+ <div className="space-y-2 rounded-xl bg-muted/50 p-3">
+ <p className="text-[13px] font-medium">Train anywhere</p>
+ <p className="text-[12px] text-muted-foreground">
+ Download a ready-to-run AI-Toolkit kit (photos, captions, config), train on any GPU, then attach the LoRA file you copied into ComfyUI/models/loras.
+ </p>
+ <div className="flex flex-wrap gap-2">
+ <Button asChild variant="outline" size="sm">
+ <a href={`/api/elements/${element.id}/training-kit`}>
+ <Download /> Training kit
+ </a>
+ </Button>
+ <div className="flex min-w-60 flex-1 gap-2">
+ <Input value={file} onChange={(e) => setFile(e.target.value)} placeholder={`fuobe/${element.handle.toLowerCase()}.safetensors`} className="h-8" />
+ <Button size="sm" variant="secondary" disabled={!file.trim() || attach.isPending} onClick={() => attach.mutate()}>
+ Attach
+ </Button>
+ </div>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 57dea3ff..caa1ef4a 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -137,6 +137,8 @@ export function useElement(id: string) {
return useQuery({
queryKey: ["elements", id],
queryFn: async () => json<StudioElement>(await fetch(`/api/elements/${id}`)),
+ // Pick up the trained identity as soon as a training job finishes.
+ refetchInterval: (q) => (q.state.data?.status === "training" ? 3000 : false),
});
}
diff --git a/src/lib/catalog/cloud-models.generated.ts b/src/lib/catalog/cloud-models.generated.ts
index a0b685e7..02f0097c 100644
--- a/src/lib/catalog/cloud-models.generated.ts
+++ b/src/lib/catalog/cloud-models.generated.ts
@@ -1683,7 +1683,8 @@ export const CLOUD_MODELS: ModelDef[] = [
"4:5": "portrait_4_3"
}
}
- }
+ },
+ "loraEndpoint": "fal-ai/z-image/turbo/lora"
}
],
"options": {
diff --git a/src/lib/catalog/training.ts b/src/lib/catalog/training.ts
new file mode 100644
index 00000000..d0478d02
--- /dev/null
+++ b/src/lib/catalog/training.ts
@@ -0,0 +1,140 @@
+/**
+ * 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.
+ */
+import type { Engine } from "./types";
+
+export type TrainingProvider = "higgsfield" | "fal" | "ai-toolkit";
+
+export interface TrainingTarget {
+ id: string;
+ name: string;
+ engine: Engine;
+ provider: TrainingProvider;
+ /** Models the trained identity applies to. */
+ modelIds: string[];
+ minImages: number;
+ description: string;
+ price: string;
+ /** 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",
+ },
+ {
+ 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",
+ },
+ {
+ id: "aitk-z-image",
+ name: "Z-Image Turbo LoRA (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",
+ },
+];
+
+export const getTrainingTarget = (id: string) => TRAINING_TARGETS.find((t) => t.id === id);
+
+/** 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, "");
+ const consonants = base.replace(/[aeiou]/g, "");
+ return `${(consonants.length >= 3 ? consonants : base).slice(0, 6) || "elem"}fz`;
+}
+
+/** AI-Toolkit job config for a Z-Image Turbo character LoRA (docs/research/comfyui-oss-2.json → character-lora). */
+export function aiToolkitJob(opts: { name: string; trigger: string; datasetFolder: string; outputFolder: string; steps?: number }) {
+ return {
+ job: "extension",
+ config: {
+ name: opts.name,
+ process: [
+ {
+ type: "diffusion_trainer",
+ training_folder: opts.outputFolder,
+ device: "cuda",
+ trigger_word: opts.trigger,
+ network: { type: "lora", linear: 16, linear_alpha: 16 },
+ 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 },
+ ],
+ train: {
+ batch_size: 1,
+ gradient_accumulation: 1,
+ train_unet: true,
+ train_text_encoder: false,
+ gradient_checkpointing: true,
+ noise_scheduler: "flowmatch",
+ optimizer: "adamw8bit",
+ lr: 0.0001,
+ optimizer_params: { weight_decay: 0.0001 },
+ dtype: "bf16",
+ cache_text_embeddings: true,
+ ema_config: { use_ema: false },
+ steps: opts.steps ?? 2500,
+ timestep_type: "weighted",
+ },
+ model: {
+ name_or_path: "Tongyi-MAI/Z-Image-Turbo",
+ arch: "zimage:turbo",
+ assistant_lora_path: "ostris/zimage_turbo_training_adapter/zimage_turbo_training_adapter_v2.safetensors",
+ quantize: true,
+ qtype: "qfloat8",
+ quantize_te: true,
+ qtype_te: "qfloat8",
+ low_vram: true,
+ },
+ sample: {
+ sampler: "flowmatch",
+ sample_every: 500,
+ width: 1024,
+ height: 1024,
+ seed: 42,
+ walk_seed: true,
+ prompts: [`photo of ${opts.trigger}, close-up portrait, natural window light`, `${opts.trigger} walking in a neon-lit street at night, full body`],
+ neg: "",
+ guidance_scale: 1,
+ sample_steps: 9,
+ },
+ },
+ ],
+ },
+ meta: { name: opts.name, version: "1.0" },
+ };
+}
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index b3745616..3349f892 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -175,6 +175,8 @@ export interface ModelRoute {
map?: FieldMap;
/** Optional note shown in the UI (e.g. "uses Lightx2v 4-step LoRA"). */
note?: string;
+ /** Same model with LoRA support (fal's `/lora` variants): used when a trained identity is mentioned. */
+ loraEndpoint?: string;
}
export type Badge = "new" | "top" | "fast" | "audio" | "4k" | "hd" | "pro" | "open" | "uncensored" | "beta";
diff --git a/src/server/db.ts b/src/server/db.ts
index df013d9d..bc12c252 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -65,6 +65,25 @@ const MIGRATIONS: string[] = [
`ALTER TABLE characters ADD COLUMN kind TEXT NOT NULL DEFAULT 'character';
ALTER TABLE characters ADD COLUMN handle TEXT;
ALTER TABLE characters ADD COLUMN loras_json TEXT;`,
+ // Identity training jobs (Soul ID, fal LoRA trainers, AI-Toolkit).
+ `CREATE TABLE IF NOT EXISTS trainings (
+ id TEXT PRIMARY KEY,
+ element_id TEXT NOT NULL,
+ target TEXT NOT NULL,
+ provider TEXT NOT NULL,
+ status TEXT NOT NULL,
+ progress REAL,
+ message TEXT,
+ external_id TEXT,
+ meta_json TEXT,
+ trigger_word TEXT,
+ error TEXT,
+ cost_usd REAL,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL,
+ completed_at INTEGER
+ );
+ CREATE INDEX IF NOT EXISTS trainings_element ON trainings(element_id);`,
];
declare global {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 43b5b87f..05743797 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -17,6 +17,7 @@ import {
} from "@/lib/catalog/types";
import { db } from "./db";
import { listElements } from "./elements";
+import { pollTrainings } from "./training";
import { enhancePrompt } from "./enhance";
import { provider } from "./providers";
import type { RemoteOutput } from "./providers/types";
@@ -314,7 +315,10 @@ async function tick(): Promise<void> {
const active = db()
.prepare("SELECT * FROM generations WHERE status IN ('queued','running') AND external_id IS NOT NULL ORDER BY created_at ASC LIMIT 50")
.all() as Row[];
- await Promise.all(active.map((r) => pollOne(r).catch((e) => update(r.id, { message: `Poll error: ${(e as Error).message}` }))));
+ await Promise.all([
+ ...active.map((r) => pollOne(r).catch((e) => update(r.id, { message: `Poll error: ${(e as Error).message}` }))),
+ pollTrainings().catch(() => {}),
+ ]);
} finally {
state.busy = false;
}
diff --git a/src/server/png.ts b/src/server/png.ts
index c2f48887..456b6d65 100644
--- a/src/server/png.ts
+++ b/src/server/png.ts
@@ -90,7 +90,7 @@ const CRC_TABLE = (() => {
return t;
})();
-function crc32(b: Buffer): number {
+export function crc32(b: Buffer): number {
let c = 0xffffffff;
for (const x of b) c = CRC_TABLE[(c ^ x) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
diff --git a/src/server/providers/fal.ts b/src/server/providers/fal.ts
index 708d379e..3554c41a 100644
--- a/src/server/providers/fal.ts
+++ b/src/server/providers/fal.ts
@@ -19,7 +19,7 @@ function key(): string {
return getSetting("falKey");
}
-async function falFetch(url: string, init: RequestInit = {}): Promise<unknown> {
+export async function falFetch(url: string, init: RequestInit = {}): Promise<unknown> {
const res = await fetch(url, {
...init,
headers: { Authorization: `Key ${key()}`, "Content-Type": "application/json", ...(init.headers ?? {}) },
@@ -59,7 +59,11 @@ export const falProvider: ProviderAdapter = {
async submit({ route, input }) {
const payload = buildPayload(route.map ?? {}, input);
- const res = (await falFetch(`${QUEUE}/${route.endpoint}`, {
+ // Trained identities (fal LoRA URLs) switch to the model's LoRA endpoint.
+ const loras = (input.loras ?? []).filter((l) => l.url);
+ const endpoint = loras.length && route.loraEndpoint ? route.loraEndpoint : route.endpoint;
+ if (endpoint !== route.endpoint) payload.loras = loras.map((l) => ({ path: l.url, scale: l.strength ?? 1 }));
+ const res = (await falFetch(`${QUEUE}/${endpoint}`, {
method: "POST",
body: JSON.stringify(payload),
})) as { request_id: string; status_url: string; response_url: string; cancel_url: string };
diff --git a/src/server/settings.ts b/src/server/settings.ts
index 12408757..ce2e58d6 100644
--- a/src/server/settings.ts
+++ b/src/server/settings.ts
@@ -29,6 +29,13 @@ export const SETTINGS = {
anthropicKey: { key: "anthropic.key", env: "ANTHROPIC_API_KEY", secret: true },
comfyUrl: { key: "comfyui.url", env: "COMFYUI_URL", default: "http://127.0.0.1:8188" },
comfyToken: { key: "comfyui.token", env: "COMFYUI_TOKEN", secret: true },
+ /** ComfyUI's models/loras folder, when it's on this machine: trained LoRAs are copied there. */
+ comfyLorasDir: { key: "comfyui.lorasDir", env: "COMFYUI_LORAS_DIR" },
+ /** AI-Toolkit UI (ostris/ai-toolkit, port 8675) for open-source character LoRA training. */
+ aiToolkitUrl: { key: "aitk.url", env: "AI_TOOLKIT_URL" },
+ aiToolkitToken: { key: "aitk.token", env: "AI_TOOLKIT_AUTH", secret: true },
+ /** Where AI-Toolkit can read datasets Fuobe writes (defaults to Fuobe's data folder — same machine). */
+ aiToolkitDatasetDir: { key: "aitk.datasetDir", env: "AI_TOOLKIT_DATASET_DIR" },
/** "auto" = demo outputs only when the chosen provider is not configured. */
demoMode: { key: "demo.mode", env: "FUOBE_DEMO_MODE", default: "auto", options: ["auto", "on", "off"] },
enhanceProvider: { key: "enhance.provider", env: "FUOBE_ENHANCE_PROVIDER", default: "auto", options: ["auto", "anthropic", "ollama", "none"] },
diff --git a/src/server/training.ts b/src/server/training.ts
new file mode 100644
index 00000000..9f34ac8f
--- /dev/null
+++ b/src/server/training.ts
@@ -0,0 +1,332 @@
+import "server-only";
+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, triggerFor, type TrainingTarget } from "@/lib/catalog/training";
+import { DATA_DIR, db } from "./db";
+import { getElement, updateElement } from "./elements";
+import { falFetch, falProvider } from "./providers/fal";
+import { hfFetch, hfUpload, higgsfieldKey } from "./providers/higgsfield";
+import { 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.
+ */
+export interface Training {
+ id: string;
+ elementId: string;
+ target: string;
+ provider: TrainingTarget["provider"];
+ status: "queued" | "running" | "succeeded" | "failed";
+ progress: number | null;
+ message: string | null;
+ trigger: string | null;
+ error: string | null;
+ createdAt: number;
+ completedAt: number | null;
+}
+
+interface Row {
+ id: string;
+ element_id: string;
+ target: string;
+ provider: Training["provider"];
+ status: Training["status"];
+ progress: number | null;
+ message: string | null;
+ external_id: string | null;
+ meta_json: string | null;
+ trigger_word: string | null;
+ error: string | null;
+ cost_usd: number | null;
+ created_at: number;
+ updated_at: number;
+ 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,
+});
+
+function update(id: string, fields: Partial<Row>) {
+ const keys = Object.keys(fields);
+ if (!keys.length) return;
+ db()
+ .prepare(`UPDATE trainings SET ${keys.map((k) => `${k} = @${k}`).join(", ")}, updated_at = @__now WHERE id = @__id`)
+ .run({ ...fields, __now: Date.now(), __id: id });
+}
+
+export function listTrainings(elementId?: string): Training[] {
+ const rows = elementId
+ ? db().prepare("SELECT * FROM trainings WHERE element_id = ? ORDER BY created_at DESC").all(elementId)
+ : db().prepare("SELECT * FROM trainings ORDER BY created_at DESC LIMIT 100").all();
+ return (rows as Row[]).map(toTraining);
+}
+
+/** Can this target run here right now? Returns the reason it can't, or null. */
+export function trainingBlocker(t: TrainingTarget): string | null {
+ if (t.provider === "higgsfield" && !higgsfieldKey()) return "Add a Higgsfield API key in Settings";
+ 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 {
+ 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})`);
+ const blocker = trainingBlocker(target);
+ if (blocker) 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}`);
+ }
+ const now = Date.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),
+ error: null,
+ cost_usd: null,
+ created_at: now,
+ updated_at: now,
+ completed_at: null,
+ };
+ db()
+ .prepare(`INSERT INTO trainings (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
+ .run(row);
+ updateElement(elementId, { status: "training" });
+ void submit(row.id, el, target, row.trigger_word ?? "", images).catch((e) => fail(row.id, el.id, (e as Error).message));
+ return toTraining(row);
+}
+
+function fail(id: string, elementId: string, error: string) {
+ update(id, { status: "failed", error, message: null, completed_at: Date.now() });
+ settleElement(elementId);
+}
+
+/** The element is "training" while any job runs, else "ready". */
+function settleElement(elementId: string) {
+ const busy = db().prepare("SELECT 1 FROM trainings WHERE element_id = ? AND status IN ('queued','running')").get(elementId);
+ updateElement(elementId, { status: busy ? "training" : "ready" });
+}
+
+function addIdentity(elementId: string, loras: 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] });
+}
+
+/** Photos + one caption per photo: "photo of <trigger>, <description>". */
+async function dataset(el: StudioElement, trigger: string, images: string[]) {
+ const caption = `photo of ${trigger}${el.description ? `, ${el.description.replace(/[.\s]+$/, "")}` : ""}`;
+ 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) });
+ }
+ return { files, caption };
+}
+
+async function aitk(pathname: string, init: RequestInit = {}) {
+ const base = getSetting("aiToolkitUrl").replace(/\/$/, "");
+ const token = getSetting("aiToolkitToken");
+ const res = await fetch(`${base}${pathname}`, {
+ ...init,
+ headers: { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(init.headers ?? {}) },
+ });
+ const body = await res.json().catch(() => null);
+ if (!res.ok) throw new Error(`AI-Toolkit ${res.status}: ${JSON.stringify(body).slice(0, 300)}`);
+ 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;
+ }
+
+ if (t.provider === "fal") {
+ const { files, caption } = await dataset(el, trigger, images);
+ update(id, { message: "Uploading the dataset" });
+ 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 };
+ update(id, {
+ external_id: res.request_id,
+ meta_json: JSON.stringify({ statusUrl: res.status_url, responseUrl: res.response_url }),
+ status: "running",
+ message: "Queued on fal",
+ cost_usd: 0.85,
+ });
+ return;
+ }
+
+ // AI-Toolkit: write the dataset where the trainer can read it, then create and start a job.
+ const root = getSetting("aiToolkitDatasetDir") || path.join(DATA_DIR, "datasets");
+ const folder = path.join(root, `fuobe-${el.id}-${id}`);
+ const { files } = await dataset(el, trigger, images);
+ 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") });
+ 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" });
+}
+
+// ---------------------------------------------------------------------------
+// Polling (called from the generation runner's tick)
+
+export async function pollTrainings(): Promise<void> {
+ 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) => pollOne(r).catch((e) => update(r.id, { message: `Checking status failed: ${(e as Error).message}` }))));
+}
+
+async function pollOne(r: Row) {
+ const t = getTrainingTarget(r.target)!;
+ 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;
+ }
+ if (r.provider === "fal") {
+ const s = (await falFetch(`${meta.statusUrl}?logs=1`)) as { status: string; logs?: { message: string }[] };
+ if (s.status !== "COMPLETED") {
+ const last = s.logs?.at(-1)?.message;
+ const step = last && /(\d+)\s*\/\s*(\d+)/.exec(last);
+ 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 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);
+ }
+ // AI-Toolkit
+ const res = await aitk(`/api/jobs?id=${encodeURIComponent(r.external_id!)}`);
+ const job = ((res.job ?? res) as Record<string, unknown>) ?? {};
+ const status = String(job.status ?? "");
+ if (status === "error" || status === "stopped") return fail(r.id, r.element_id, String(job.info ?? `AI-Toolkit job ${status}`));
+ if (status !== "completed") {
+ const step = Number(job.step ?? 0);
+ const total = Number(job.total_steps ?? 0);
+ update(r.id, { progress: total ? step / total : null, message: status === "running" ? `Training · step ${step}/${total || "?"}` : "Waiting for the GPU" });
+ return;
+ }
+ const filesRes = await aitk(`/api/jobs/${r.external_id}/files`);
+ 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));
+ } else {
+ 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 })));
+ return done(r, message);
+}
+
+function done(r: Row, message: string | null = null) {
+ update(r.id, { status: "succeeded", progress: 1, message, completed_at: Date.now() });
+ settleElement(r.element_id);
+}
+
+// ---------------------------------------------------------------------------
+// Download kit for training anywhere (AI-Toolkit CLI)
+
+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));
+ 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" });
+ const readme = `# Train ${el.name} with AI-Toolkit
+
+1. Install AI-Toolkit: https://github.com/ostris/ai-toolkit (24 GB GPU recommended)
+2. Unzip this kit next to it and run:
+
+ 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.
+
+Trigger word: ${trigger} — Fuobe adds it to the prompt whenever you @${el.handle} on Z-Image Turbo (open source).
+`;
+ return {
+ name: `${name}-training-kit.zip`,
+ // JSON is valid YAML, so AI-Toolkit reads the config as-is.
+ data: zip([
+ ...files.map((f) => ({ name: `dataset/${f.name}`, data: f.data })),
+ { name: `${name}.yaml`, data: Buffer.from(JSON.stringify(job, null, 2)) },
+ { name: "README.md", data: Buffer.from(readme) },
+ ]),
+ };
+}
+
+/** Register a LoRA trained elsewhere (already in ComfyUI/models/loras). */
+export function attachLora(elementId: string, input: { file: string; trigger: string; modelId: string }) {
+ 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 }]);
+}
diff --git a/src/server/zip.ts b/src/server/zip.ts
new file mode 100644
index 00000000..6246bb78
--- /dev/null
+++ b/src/server/zip.ts
@@ -0,0 +1,43 @@
+import "server-only";
+import { crc32 } from "./png";
+
+/** Minimal ZIP writer (stored, no compression) — enough for training datasets and download kits. */
+export function zip(files: { name: string; data: Buffer }[]): Buffer {
+ const local: Buffer[] = [];
+ const central: Buffer[] = [];
+ let offset = 0;
+ for (const f of files) {
+ const name = Buffer.from(f.name, "utf8");
+ const crc = crc32(f.data);
+ const head = Buffer.alloc(30);
+ head.writeUInt32LE(0x04034b50, 0);
+ head.writeUInt16LE(20, 4); // version needed
+ head.writeUInt16LE(0x0800, 6); // UTF-8 names
+ head.writeUInt16LE(0, 8); // stored
+ head.writeUInt32LE(crc, 14);
+ head.writeUInt32LE(f.data.length, 18);
+ head.writeUInt32LE(f.data.length, 22);
+ head.writeUInt16LE(name.length, 26);
+ local.push(head, name, f.data);
+ const dir = Buffer.alloc(46);
+ dir.writeUInt32LE(0x02014b50, 0);
+ dir.writeUInt16LE(20, 4);
+ dir.writeUInt16LE(20, 6);
+ dir.writeUInt16LE(0x0800, 8);
+ dir.writeUInt32LE(crc, 16);
+ dir.writeUInt32LE(f.data.length, 20);
+ dir.writeUInt32LE(f.data.length, 24);
+ dir.writeUInt16LE(name.length, 28);
+ dir.writeUInt32LE(offset, 42);
+ central.push(dir, name);
+ offset += head.length + name.length + f.data.length;
+ }
+ const cd = Buffer.concat(central);
+ const end = Buffer.alloc(22);
+ end.writeUInt32LE(0x06054b50, 0);
+ end.writeUInt16LE(files.length, 8);
+ end.writeUInt16LE(files.length, 10);
+ end.writeUInt32LE(cd.length, 12);
+ end.writeUInt32LE(offset, 16);
+ return Buffer.concat([...local, cd, end]);
+}
diff --git a/tests/training.test.ts b/tests/training.test.ts
new file mode 100644
index 00000000..c34ecdf9
--- /dev/null
+++ b/tests/training.test.ts
@@ -0,0 +1,43 @@
+import { execFileSync } from "node:child_process";
+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 { buildPayload } from "@/lib/catalog/payload";
+import { zip } from "@/server/zip";
+
+describe("identity training", () => {
+ 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("writes AI-Toolkit jobs for Z-Image Turbo with the training adapter", () => {
+ 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.datasets[0].folder_path).toBe("/d");
+ });
+
+ it("switches hosted Z-Image to its LoRA endpoint only when a LoRA URL is present", () => {
+ const route = getModel("z-image-turbo-cloud")!.routes[0];
+ expect(route.loraEndpoint).toBe("fal-ai/z-image/turbo/lora");
+ expect(buildPayload(route.map!, { prompt: "x" }).loras).toBeUndefined();
+ });
+
+ 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();
+ expect(out.trim()).toBe("None photo of nvrysfz");
+ });
+});