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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
AI Influencer builder: server runs and /api/influencer, with prices first
Claude3a4df851870a
diff --git a/src/app/api/influencer/route.ts b/src/app/api/influencer/route.tsnew file mode 100644index 00000000..d317829b--- /dev/null+++ b/src/app/api/influencer/route.ts@@ -0,0 +1,43 @@+import { z } from "zod";+import { MAX_CLOTHING, MAX_DIRECTION } from "@/lib/influencer";+import { createInfluencer, previewInfluencer, type InfluencerBody } from "@/server/influencer";++const File = z.string().startsWith("/api/files/").max(500);++const Body = z.object({+ engine: z.enum(["cloud", "open"]),+ state: z.record(z.string(), z.unknown()),+ direction: z.string().max(MAX_DIRECTION).optional(),+ start: z.enum(["scratch", "reference", "face"]),+ photo: File.optional(),+ clothing: z.array(File).max(MAX_CLOTHING).optional(),+ modelId: z.string().max(60).optional(),+});++/** What's wrong with a body, in Higgsfield's words where it has them. */+function bodyError(issues: z.core.$ZodIssue[]): string {+ const at = (key: string) => issues.some((i) => i.path[0] === key);+ if (at("engine")) return "Pick Cloud or Open source";+ if (at("direction")) return "Keep the direction under 4,000 characters";+ if (at("clothing")) return issues.some((i) => i.path[0] === "clothing" && i.code === "too_big") ? "You can add up to three clothing references" : "Upload the clothing references again";+ if (at("photo")) return "Upload the photo again";+ if (at("start")) return "Pick how to start: from scratch, from a reference or with your face";+ return "Build your character first";+}++/**+ * AI Influencer builder: a character sheet from the builder's picks — Higgsfield's AI Influencer+ * (with a key), Nano Banana Pro or Seedream 5.0 on the cloud, the Soul Cast sheet workflow (plus+ * Qwen-Image-Edit 2511 for a face or clothing) on the open engine. `?preview=1` prices it instead.+ */+export async function POST(request: Request) {+ const parsed = Body.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: bodyError(parsed.error.issues) }, { status: 400 });+ const body = parsed.data as InfluencerBody;+ if (new URL(request.url).searchParams.get("preview")) return Response.json(previewInfluencer(body));+ try {+ return Response.json(createInfluencer(body), { status: 201 });+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: 422 });+ }+}diff --git a/src/server/influencer.ts b/src/server/influencer.tsnew file mode 100644index 00000000..f8e5e611--- /dev/null+++ b/src/server/influencer.ts@@ -0,0 +1,53 @@+import "server-only";+import { getModel } from "@/lib/catalog";+import type { Engine } from "@/lib/catalog/types";+import { cleanState, planInfluencer, type InfluencerRun, type InfluencerStart } from "@/lib/influencer";+import { createPipeline } from "./chains";+import { planCaps, previewRun, runEngine } from "./photodump";++/**+ * AI Influencer builder runs (/influencer): the pure plan (src/lib/influencer.ts) for the engine the+ * install allows, priced or created as one batch. On the open engine with a photo or clothing it is+ * two chained jobs: the Soul Cast sheet (a helper step) and the Qwen-Image-Edit pass you see.+ */++export interface InfluencerBody {+ engine: Engine;+ /** The builder's state as the page holds it; cleaned here (unknown, hidden and surplus picks dropped). */+ state: unknown;+ direction?: string;+ start: InfluencerStart;+ photo?: string;+ clothing?: string[];+ modelId?: string;+}++function plan(body: InfluencerBody) {+ const { state } = cleanState(body.state);+ const run: InfluencerRun = { ...body, engine: runEngine(body.engine), state };+ return planInfluencer(run, planCaps());+}++/** What a run would make and cost, without starting it (errors come back as `error`). */+export function previewInfluencer(body: InfluencerBody) {+ try {+ const p = plan(body);+ const priced = previewRun(+ p.steps.map((s) => s.request),+ p.notes,+ );+ if ("error" in priced) return priced;+ // One sheet, whatever helper step makes it first; the price is every step's.+ return { ...priced, modelId: p.modelId, modelName: getModel(p.modelId)?.name ?? p.modelId, count: 1, steps: p.steps.length };+ } catch (e) {+ return { error: (e as Error).message, notes: [] };+ }+}++export function createInfluencer(body: InfluencerBody) {+ const p = plan(body);+ const title = p.steps[p.steps.length - 1].request.title ?? "AI Influencer";+ const { batchId, items, byKey } = createPipeline(p.steps.map((s) => ({ ...s, request: { ...s.request, batchTitle: title } })));+ const last = p.steps[p.steps.length - 1].key;+ return { batchId, items, sheet: byKey[last], notes: p.notes, modelId: p.modelId };+}diff --git a/src/server/photodump.ts b/src/server/photodump.tsindex 7b62c14b..7ead545d 100644--- a/src/server/photodump.ts+++ b/src/server/photodump.ts@@ -157,8 +157,14 @@ export function createBatch(requests: GenerationRequest[], title: string): { batreturn { batchId, items };}+/** The steps a generation waited for (its chain), by id. */+function dependsOn(id: string): string[] {+ const dep = (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(id) as { depends_on: string | null } | undefined)?.depends_on;+ return dep ? (dep.startsWith("[") ? (JSON.parse(dep) as string[]) : [dep]) : [];+}+/** The features whose photos can be retried from their run's grid (Photodump, Fashion Factory, Character Sheet). */-const RETRY_FEATURES = new Set(["photodump", "fashion", "character-sheet", "app:app-ai-influencer"]);+const RETRY_FEATURES = new Set(["photodump", "fashion", "character-sheet", "app:app-ai-influencer", "influencer"]);/*** Run a failed or canceled photo again inside its run: the same request in the same batch (so the@@ -171,6 +177,23 @@ export function retryPhoto(id: string): Generation[] {if (!g) throw new Error("That photo is gone");if (!RETRY_FEATURES.has(g.feature)) throw new Error("This result isn't part of a photo run");if (g.status !== "failed" && g.status !== "canceled") throw new Error("Only a failed or canceled photo can be retried");+ // A chained photo (the AI Influencer builder's face pass) whose earlier step failed never got that step's+ // image: both run again, chained as before.+ const deps = dependsOn(id);+ const before = deps.map((d) => getGeneration(d, { includeDeleted: true }));+ if (before.some((d) => d?.status !== "succeeded")) {+ const step = before[0];+ if (deps.length !== 1 || !step || dependsOn(step.id).length || (step.status !== "failed" && step.status !== "canceled")) throw new Error("The step before it didn't finish — press Generate to run both again");+ const { items } = createPipeline(+ [+ { key: "before", request: step.request },+ { key: "photo", request: g.request, after: "before" },+ ],+ g.batchId ? { batchId: g.batchId } : {},+ );+ trashGenerations([step.id, id]);+ return items;+ }const req = fitted(g.request);const p = previewGeneration(req);const per = p.jobs > 1 ? Math.max(1, Math.round(p.outputs / p.jobs)) : undefined;diff --git a/tests/influencer-api.test.ts b/tests/influencer-api.test.tsnew file mode 100644index 00000000..a576bb5e--- /dev/null+++ b/tests/influencer-api.test.ts@@ -0,0 +1,128 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-influencer-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+delete process.env.HF_KEY;+delete process.env.HF_API_KEY;++const { setSetting } = await import("@/server/settings");+const gens = await import("@/server/generations");+const { saveFile } = await import("@/server/storage");+const route = await import("@/app/api/influencer/route");+const { compileCastPrompt } = await import("@/lib/influencer");+const { retryPhoto } = await import("@/server/photodump");++beforeAll(() => {+ setSetting("demoMode", "auto");+ setSetting("higgsfieldKey", "");+});+afterEach(() => {+ setSetting("engineMode", "both");+ setSetting("higgsfieldKey", "");+});+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=", "base64");+const upload = () => saveFile({ data: PNG, contentType: "image/png", source: "upload" }).url;+const post = (body: unknown, preview = false) =>+ route.POST(new Request(`http://x/api/influencer${preview ? "?preview=1" : ""}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));+const state = { tier: "freak", picks: { gender: ["female"], hair: ["hs_beehive"], aesthetic: ["goth"] }, locked: [] };++async function settle(id: string, ms = 40_000) {+ const until = Date.now() + ms;+ for (;;) {+ const g = gens.getGeneration(id, { includeDeleted: true })!;+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;+ if (Date.now() > until) throw new Error(`timed out: ${g.status} ${g.message}`);+ await new Promise((r) => setTimeout(r, 300));+ }+}++describe("/api/influencer", () => {+ it("prices a cloud sheet on Nano Banana Pro without a key, and Higgsfield's AI Influencer with one", async () => {+ const cloud = await (await post({ engine: "cloud", state, start: "scratch" }, true)).json();+ expect(cloud).toMatchObject({ modelId: "nano-banana-pro", modelName: "Nano Banana Pro", count: 1, steps: 1, demo: true });+ setSetting("higgsfieldKey", "key:secret");+ const hf = await (await post({ engine: "cloud", state, start: "scratch" }, true)).json();+ expect(hf).toMatchObject({ modelId: "ai-influencer", modelName: "AI Influencer", costUsd: 0.05, demo: false });+ const seedream = await (await post({ engine: "cloud", state, start: "scratch", modelId: "seedream-5-pro" }, true)).json();+ expect(seedream.modelId).toBe("seedream-5-pro");+ });++ it("prices the open sheet as free, in two steps with a face", async () => {+ const face = upload();+ const open = await (await post({ engine: "open", state, start: "face", photo: face }, true)).json();+ expect(open).toMatchObject({ modelId: "oss-qwen-edit", count: 1, steps: 2 });+ expect(open.notes).toEqual(["Two steps: Z-Image Turbo draws the sheet, then Qwen-Image-Edit 2511 puts your face on it"]);+ });++ it("makes the open sheet, then puts the face on it, as one batch (demo)", async () => {+ const face = upload();+ const res = await post({ engine: "open", state, start: "face", photo: face, clothing: [upload()], direction: "A potter from Porto" });+ expect(res.status).toBe(201);+ const run = await res.json();+ expect(run.items.map((g: { feature: string; modelId: string }) => [g.feature, g.modelId])).toEqual([+ ["influencer-step", "oss-zimage-soul-cast"],+ ["influencer", "oss-qwen-edit"],+ ]);+ expect(run.items[0].prompt).toBe(compileCastPrompt({ state: state as never, direction: "A potter from Porto" }));+ expect(run.sheet.id).toBe(run.items[1].id);+ expect(new Set(run.items.map((g: { batchId: string }) => g.batchId))).toEqual(new Set([run.batchId]));+ const done = await settle(run.sheet.id);+ expect(done.status).toBe("succeeded");+ // The edit took the sheet first, then the face and the clothing.+ expect(done.request.inputs?.images?.[1]).toBe(face);+ expect(done.request.inputs?.images).toHaveLength(3);+ expect(done.outputs.length).toBeGreaterThan(0);+ }, 60_000);++ it("retries a failed sheet in its run, but not a face pass whose sheet never came", async () => {+ const run = await (await post({ engine: "open", state, start: "face", photo: upload() })).json();+ await gens.cancelGeneration(run.items[0].id);+ const pass = await settle(run.sheet.id);+ expect(pass.status).toBe("failed");+ // Both steps run again, chained, in the same batch; the failed ones go to the Trash.+ const again = retryPhoto(pass.id);+ expect(again.map((g) => [g.feature, g.modelId, g.batchId])).toEqual([+ ["influencer-step", "oss-zimage-soul-cast", run.batchId],+ ["influencer", "oss-qwen-edit", run.batchId],+ ]);+ expect(gens.getGeneration(pass.id)).toBeNull();+ const redone = await settle(again[1].id);+ expect(redone.status).toBe("succeeded");+ expect(redone.request.inputs?.images).toHaveLength(2);+ const one = await (await post({ engine: "cloud", state, start: "scratch" })).json();+ await gens.cancelGeneration(one.items[0].id);+ expect(retryPhoto(one.items[0].id)[0]).toMatchObject({ feature: "influencer", batchId: one.batchId });+ }, 60_000);++ it("follows the engine mode", async () => {+ setSetting("engineMode", "open");+ const run = await (await post({ engine: "cloud", state, start: "scratch" })).json();+ expect(run.items.map((g: { modelId: string }) => g.modelId)).toEqual(["oss-zimage-soul-cast"]);+ expect(run.items[0].feature).toBe("influencer");+ });++ it("says what is wrong, in Higgsfield's words where it has them", async () => {+ const tooMany = await post({ engine: "cloud", state, start: "scratch", clothing: [upload(), upload(), upload(), upload()] });+ expect(tooMany.status).toBe(400);+ expect((await tooMany.json()).error).toBe("You can add up to three clothing references");+ const long = await post({ engine: "cloud", state, start: "scratch", direction: "x".repeat(4001) });+ expect((await long.json()).error).toBe("Keep the direction under 4,000 characters");+ const outside = await post({ engine: "cloud", state, start: "face", photo: "https://example.com/me.jpg" });+ expect((await outside.json()).error).toBe("Upload the photo again");+ const noFace = await post({ engine: "cloud", state, start: "face" });+ expect(noFace.status).toBe(422);+ expect((await noFace.json()).error).toBe("Add your photo first");+ const conflict = { tier: "total", picks: { body_type: ["body_heavy"], height: ["h_tall"] } };+ expect((await (await post({ engine: "cloud", state: conflict, start: "scratch" }, true)).json()).error).toBe("Heavy build cannot be combined with Tall or Very tall.");+ expect((await post({ engine: "cloud", state: conflict, start: "scratch" })).status).toBe(422);+ // Picks the tier doesn't show are dropped, not refused.+ const hidden = await (await post({ engine: "open", state: { tier: "normal", picks: { hair: ["hs_wings"] } }, start: "scratch" })).json();+ expect(hidden.items[0].prompt).toBe(compileCastPrompt({ state: { tier: "normal", picks: {}, locked: [] } }));+ });+});