From 26a3bfb797993478f371fe27550ea2b62ac360ea Mon Sep 17 00:00:00 2001 From: Towsty Date: Tue, 6 Oct 2026 19:06:14 -0500 Subject: [PATCH] Add asset-pack Image v2 API for Family Board stickers. POST /api/assets/generate wraps Flux/Krea generate with sticker/panel/icon presets; GET /api/assets/{id} returns status and PNG URLs using the existing poll path. Co-authored-by: Cursor --- docs/asset-pack.md | 128 ++++++++++++++++++++++ docs/image-v2.md | 2 + server/api/assets/[id].get.ts | 65 ++++++++++++ server/api/assets/generate.post.ts | 163 +++++++++++++++++++++++++++++ tests/asset-pack.test.mjs | 78 ++++++++++++++ utils/assetPack.ts | 94 +++++++++++++++++ 6 files changed, 530 insertions(+) create mode 100644 docs/asset-pack.md create mode 100644 server/api/assets/[id].get.ts create mode 100644 server/api/assets/generate.post.ts create mode 100644 tests/asset-pack.test.mjs create mode 100644 utils/assetPack.ts diff --git a/docs/asset-pack.md b/docs/asset-pack.md new file mode 100644 index 0000000..39f658a --- /dev/null +++ b/docs/asset-pack.md @@ -0,0 +1,128 @@ +# Asset pack API (Family Board stickers) + +Thin HTTP wrapper around **Image v2 generate** for kid-UI stickers, panel backgrounds, and icons. Same Comfy queue, same auth, same poll pattern as Studio 2. + +## Auth / LAN + +Uses the same trust model as Image v2 (`POST /api/v2/generate`): + +- If `NUXT_PUBLIC_AUTH_ENABLED=true`, send a logged-in session cookie (or log in first via `/login`). +- On the LAN, call the same Studio 2 base URL you already use (Coolify / thebeast host). Example: `https://aigen.` or whatever Coolify publishes for this app. +- Do not invent a second token. If Image v2 works from thebeast, this works with the same credentials. + +## Endpoints + +| Method | Path | Purpose | +|--------|------|---------| +| `POST` | `/api/assets/generate` | Queue a sticker / panel / icon job | +| `GET` | `/api/assets/{id}` | Status + PNG URL when complete | +| `GET` | `/api/generate/{id}` | Same job (Image v2 poll) | +| `GET` | `/api/generate/{id}/stream` | SSE progress (Image v2) | + +## Request body + +```json +{ + "prompt": "cheerful hedgehog-speed runner mascot with sneakers, original character", + "negative_prompt": "optional extra negatives", + "engine": "flux", + "width": 1024, + "height": 1024, + "transparent_friendly": true, + "style": "sticker", + "seed": null +} +``` + +| Field | Notes | +|-------|--------| +| `prompt` | Required. Your subject description (original characters — not trademarked IP). | +| `engine` | `flux` (default) or `krea`. Flux Klein / Krea turbo defaults from Image v2. | +| `style` | `sticker` (default), `panel_bg`, or `icon`. Expands into strong prompt prefixes/suffixes. | +| `width` / `height` | Snapped to 768 / 1024 / 1280. Defaults: sticker 1024², icon 768², panel_bg 1280². | +| `transparent_friendly` | Bias toward a plain / chroma-friendly background (default on for sticker/icon). | +| `negative_prompt` | Merged with a strong default (photoreal, watermark, Sonic/Mario/Minecraft/Nintendo/Sega/Mojang, NSFW, …). | +| `seed` | Number or `null` / omit for random. | + +## Curl: sticker + poll + +```bash +BASE='https://YOUR-AIGEN-HOST' # Studio 2 LAN / Coolify URL +# If auth is on, attach your session cookie: -H "Cookie: …" + +JOB=$(curl -sS -X POST "$BASE/api/assets/generate" \ + -H 'Content-Type: application/json' \ + -d '{ + "prompt": "cheerful hedgehog-speed runner mascot with sneakers, original character", + "engine": "flux", + "style": "sticker", + "transparent_friendly": true, + "width": 1024, + "height": 1024 + }') + +echo "$JOB" +ID=$(echo "$JOB" | jq -r '.jobId') + +# Poll until complete (or use /api/generate/$ID/stream) +while true; do + STATE=$(curl -sS "$BASE/api/assets/$ID") + STATUS=$(echo "$STATE" | jq -r '.status') + echo "$STATUS" + if [ "$STATUS" = "complete" ] || [ "$STATUS" = "error" ] || [ "$STATUS" = "cancelled" ]; then + echo "$STATE" | jq . + break + fi + sleep 2 +done + +# Download PNG (same auth cookie) +PNG=$(echo "$STATE" | jq -r '.pngUrl // .url') +curl -sS -o sticker.png "$BASE$PNG" +``` + +Krea turbo: + +```bash +curl -sS -X POST "$BASE/api/assets/generate" \ + -H 'Content-Type: application/json' \ + -d '{ + "prompt": "blocky explorer buddy with pickaxe vibes, original character, cute", + "engine": "krea", + "style": "sticker" + }' +``` + +## Response (queue) + +```json +{ + "jobId": "…", + "studioJobId": "…", + "queued": true, + "pollUrl": "/api/assets/…", + "generatePollUrl": "/api/generate/…", + "streamUrl": "/api/generate/…/stream", + "engine": "flux", + "style": "sticker", + "width": 1024, + "height": 1024, + "prompt": "…expanded…", + "negative": "…" +} +``` + +## Response (complete) + +`GET /api/assets/{id}` includes Image v2 snapshot fields plus: + +- `pngUrl` / `url` — `/api/library/stills/{stillId}` (downloadable PNG) +- `urls` — array of the same +- `thumbUrl` — `?thumb=1` +- `complete` — `true` when `status === "complete"` + +Files land in the existing library / artifacts layout (same as Image v2 generate). + +## Out of scope (v1) + +No rembg/alpha matte step required. No Studio 2 UI changes. No video / YuE changes. Do not prompt copyrighted character sheets by name. diff --git a/docs/image-v2.md b/docs/image-v2.md index 07cfd09..ec819bf 100644 --- a/docs/image-v2.md +++ b/docs/image-v2.md @@ -15,6 +15,8 @@ Image edit (v1) and Image v2 are siblings. v1 is unchanged. Do not mute-fix `wor Poll v2 jobs the same way as v1: `GET /api/generate/{id}/stream` and `GET /api/generate/{id}`. +For Family Board stickers / panel backgrounds / icons, see **[asset-pack.md](./asset-pack.md)** — `POST /api/assets/generate` is a thin wrapper around Image v2 generate with style presets. + ## Modes - **edit** — one image + text. Task is `scene`. Sending `image_b` is rejected. Use this to change lighting, background, or the whole frame from a single still. diff --git a/server/api/assets/[id].get.ts b/server/api/assets/[id].get.ts new file mode 100644 index 0000000..7c54c16 --- /dev/null +++ b/server/api/assets/[id].get.ts @@ -0,0 +1,65 @@ +/** + * Asset-pack status. Same job ids as Image v2. + * Poll: GET /api/assets/{id} (or GET /api/generate/{id}). + * On complete, includes downloadable still URL(s) under /api/library/stills/{stillId}. + */ +export default defineEventHandler(async (event) => { + const id = String(getRouterParam(event, 'id') || '').trim() + if (!id) throw createError({ statusCode: 400, statusMessage: 'Missing job id' }) + + const withUrls = (snap: Record) => { + const stillId = typeof snap.stillId === 'string' ? snap.stillId : '' + const url = stillId ? `/api/library/stills/${stillId}` : null + return { + ...snap, + url, + urls: url ? [url] : [], + pngUrl: url, + thumbUrl: url ? `${url}?thumb=1` : null, + complete: snap.status === 'complete' + } + } + + const live = getJob(id) + if (live) return withUrls(jobSnapshot(live) as Record) + + const pending = readPendingJob(id) + if (pending) { + const done = await resolvePendingJob(pending).catch(() => null) + if (done) return withUrls(done as Record) + const job = ensurePendingWatch(pending) + return withUrls(jobSnapshot(job) as Record) + } + + try { + const owner = libraryOwnerKey(event) + const studio = listStudioJobs(owner).find(item => item.id === id || item.liveJobId === id) + if (studio) { + const liveId = studio.liveJobId || '' + const liveJob = liveId ? getJob(liveId) : undefined + if (liveJob) { + return { + ...withUrls(jobSnapshot(liveJob) as Record), + studioJobId: studio.id + } + } + return { + jobId: studio.id, + studioJobId: studio.id, + status: studio.status || 'queued', + message: studio.error || 'Waiting in the studio queue', + progress: 0, + url: null, + urls: [], + pngUrl: null, + thumbUrl: null, + complete: studio.status === 'complete', + error: studio.error || undefined + } + } + } catch { + // fall through + } + + throw createError({ statusCode: 404, statusMessage: 'Job not found' }) +}) diff --git a/server/api/assets/generate.post.ts b/server/api/assets/generate.post.ts new file mode 100644 index 0000000..02bfddb --- /dev/null +++ b/server/api/assets/generate.post.ts @@ -0,0 +1,163 @@ +import { addStudioJob, kickStudioQueue, listStudioJobs, videoJobsBusy } from '~/server/utils/studioQueue' +import { comfyConfigured } from '~/server/utils/comfy' +import { + IMAGE_V2_CFG_DEFAULT, + IMAGE_V2_KREA_CFG, + IMAGE_V2_KREA_STEPS, + IMAGE_V2_STEPS_DEFAULT, + IMAGE_V2_TURBO_CFG, + IMAGE_V2_TURBO_STEPS, + imageV2WorkflowFile +} from '~/utils/imageV2' +import { clampImageCfg, clampImageSteps } from '~/utils/generationPresets' +import { persistLoraFields } from '~/server/utils/loras' +import { + assetPackSize, + buildAssetPackNegative, + buildAssetPackPrompt, + parseAssetPackEngine, + parseAssetPackStyle +} from '~/utils/assetPack' + +function parseBool(raw: unknown) { + return raw === true || raw === 'true' || raw === '1' || raw === 1 +} + +/** + * Thin Family Board / asset-pack wrapper around Image v2 generate. + * POST /api/assets/generate → same studio queue + poll as /api/v2/generate. + */ +export default defineEventHandler(async (event) => { + const body = await readBody>(event).catch(() => ({})) + const promptBody = String(body?.prompt || '').trim() + if (!promptBody) { + throw createError({ statusCode: 400, statusMessage: 'A prompt is required' }) + } + if (!comfyConfigured()) { + throw createError({ + statusCode: 503, + statusMessage: 'Beast ComfyUI is not configured. Set COMFY_HOST.' + }) + } + + const style = parseAssetPackStyle(body?.style, 'sticker') + const engine = parseAssetPackEngine(body?.engine ?? body?.Engine, 'flux') + const transparentFriendly = body?.transparent_friendly === undefined + ? style === 'sticker' || style === 'icon' + : parseBool(body.transparent_friendly) + const size = assetPackSize(style, body?.width, body?.height) + const prompt = buildAssetPackPrompt({ + prompt: promptBody, + style, + transparentFriendly + }) + const negative = buildAssetPackNegative( + String(body?.negative_prompt ?? body?.negative ?? '').trim() + ) + const turbo = parseBool(body?.turbo) + const steps = engine === 'krea' + ? clampImageSteps(body?.steps, IMAGE_V2_KREA_STEPS) + : turbo ? IMAGE_V2_TURBO_STEPS : clampImageSteps(body?.steps, IMAGE_V2_STEPS_DEFAULT) + const cfg = engine === 'krea' + ? clampImageCfg(body?.cfg, IMAGE_V2_KREA_CFG) + : turbo ? IMAGE_V2_TURBO_CFG : clampImageCfg(body?.cfg, IMAGE_V2_CFG_DEFAULT) + const seed = body?.seed != null && String(body.seed) !== '' && String(body.seed) !== 'random' + ? Number(body.seed) + : Math.floor(Math.random() * 2_147_483_647) + if (!Number.isFinite(seed)) { + throw createError({ statusCode: 400, statusMessage: 'seed must be a number or null' }) + } + + const ownerKey = libraryOwnerKey(event) + const library = publicLibrary(event) + const folderId = library.folders.some(folder => folder.id === String(body?.folderId || '')) + ? String(body.folderId) + : library.folders[0]?.id + if (!folderId) { + throw createError({ statusCode: 400, statusMessage: 'Create a library folder before generating' }) + } + assertFolderExists(event, folderId) + const destFolder = library.folders.find(folder => folder.id === folderId) + const folderLocked = Boolean(destFolder?.protected && !destFolder.unlocked) + const clipName = allocateOutputName(ownerKey, folderId, String(body?.name || `asset-${style}`).trim(), { + engine, + loraStack: [] + }) + + const studio = await addStudioJob({ + ownerKey, + familyId: crypto.randomUUID(), + kind: 'edit', + payload: { + prompt, + promptMid: prompt, + name: clipName, + folderId, + aspect: '1:1', + width: size.width, + height: size.height, + steps, + turbo, + seed, + cfg, + fps: 24, + samplerName: 'euler', + scheduler: 'simple', + duration: 0, + sound: false, + workflow: 'v1', + useIdentityRefs: false, + hideThumbnail: false, + hideInput: false, + folderLocked, + referenceStillIds: [null, null, null, null], + extensions: [], + queueAutoRun: false, + negative, + passes: [], + passMode: 'batch', + scaleToTotalPixels: false, + scaleMegapixels: 0, + imagePipeline: 'v2', + v2Mode: 'generate', + v2Task: 't2i', + engine, + snofsModel: 0, + snofsClip: 0, + consistencyModel: 0, + consistencyClip: 0, + ...persistLoraFields([]) + } + }) + await kickStudioQueue() + let latest = listStudioJobs(ownerKey).find(item => item.id === studio.id) + if (!latest?.liveJobId && !(await videoJobsBusy())) { + await kickStudioQueue() + latest = listStudioJobs(ownerKey).find(item => item.id === studio.id) + } + const liveJobId = latest?.liveJobId || '' + const jobId = liveJobId || studio.id + + return { + jobId, + studioJobId: studio.id, + queued: !liveJobId, + status: liveJobId ? 'queued' : 'queued', + pollUrl: `/api/assets/${jobId}`, + generatePollUrl: `/api/generate/${jobId}`, + streamUrl: `/api/generate/${jobId}/stream`, + seed, + steps, + cfg, + mode: 'generate', + task: 't2i', + engine, + style, + transparent_friendly: transparentFriendly, + workflow: imageV2WorkflowFile('generate', engine, { hasImage: false, hasReference: false }), + width: size.width, + height: size.height, + prompt, + negative + } +}) diff --git a/tests/asset-pack.test.mjs b/tests/asset-pack.test.mjs new file mode 100644 index 0000000..895345d --- /dev/null +++ b/tests/asset-pack.test.mjs @@ -0,0 +1,78 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync, writeFileSync, unlinkSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { pathToFileURL } from 'node:url' +import ts from 'typescript' + +const stub = ` +export const IMAGE_V2_ENGINES = ['flux', 'krea'] +export function parseImageV2Engine(raw, fallback = 'flux') { + const value = String(raw || '').trim().toLowerCase() + return IMAGE_V2_ENGINES.includes(value) ? value : fallback +} +export function clampImageV2Size(width, height) { + const sides = [768, 1024, 1280] + const snap = (raw, fallback) => { + const value = Number(raw) + if (!Number.isFinite(value) || value <= 0) return fallback + return sides.reduce((best, side) => Math.abs(side - value) < Math.abs(best - value) ? side : best, sides[0]) + } + return { width: snap(width, 1024), height: snap(height, 1024), aspect: null } +} +` +const assetSrc = readFileSync(new URL('../utils/assetPack.ts', import.meta.url), 'utf8') + .replace(/from '~\/utils\/imageV2'/g, "from './imageV2-stub.mjs'") + +const dir = join(tmpdir(), `asset-pack-${process.pid}`) +const { mkdirSync, rmSync } = await import('node:fs') +mkdirSync(dir, { recursive: true }) +const stubPath = join(dir, 'imageV2-stub.mjs') +const assetPath = join(dir, 'assetPack.mjs') +writeFileSync(stubPath, stub) +writeFileSync(assetPath, ts.transpileModule(assetSrc, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } +}).outputText) + +const { + buildAssetPackPrompt, + buildAssetPackNegative, + assetPackSize, + parseAssetPackEngine, + parseAssetPackStyle, + ASSET_PACK_DEFAULT_NEGATIVE +} = await import(pathToFileURL(assetPath).href) +rmSync(dir, { recursive: true, force: true }) + +test('sticker prompt expands with die-cut / transparent-friendly cues', () => { + const prompt = buildAssetPackPrompt({ + prompt: 'cheerful runner mascot', + style: 'sticker', + transparentFriendly: true + }) + assert.match(prompt, /die-cut sticker/i) + assert.match(prompt, /cheerful runner mascot/) + assert.match(prompt, /plain|chroma|keying/i) + assert.ok(!/Sonic|Mario|Minecraft/i.test(prompt)) +}) + +test('default negative blocks trademarked names and NSFW', () => { + const neg = buildAssetPackNegative() + assert.equal(neg, ASSET_PACK_DEFAULT_NEGATIVE) + assert.match(neg, /Sonic/) + assert.match(neg, /Mario/) + assert.match(neg, /Minecraft/) + assert.match(neg, /NSFW/i) + assert.match(buildAssetPackNegative('extra clutter'), /extra clutter/) +}) + +test('engine and style defaults; sizes snap to allowed sides', () => { + assert.equal(parseAssetPackEngine(undefined), 'flux') + assert.equal(parseAssetPackEngine('krea'), 'krea') + assert.equal(parseAssetPackStyle('panel_bg'), 'panel_bg') + assert.deepEqual(assetPackSize('sticker'), { width: 1024, height: 1024, aspect: null }) + assert.deepEqual(assetPackSize('icon'), { width: 768, height: 768, aspect: null }) + assert.equal(assetPackSize('panel_bg').width, 1280) + assert.equal(assetPackSize('sticker', 1000, 900).width, 1024) +}) diff --git a/utils/assetPack.ts b/utils/assetPack.ts new file mode 100644 index 0000000..ace7900 --- /dev/null +++ b/utils/assetPack.ts @@ -0,0 +1,94 @@ +import { clampImageV2Size, parseImageV2Engine, type ImageV2Engine } from '~/utils/imageV2' + +export const ASSET_PACK_STYLES = ['sticker', 'panel_bg', 'icon'] as const +export type AssetPackStyle = (typeof ASSET_PACK_STYLES)[number] + +export const ASSET_PACK_DEFAULT_NEGATIVE = [ + 'photoreal', + 'celebrity', + 'watermark', + 'logo', + 'signature', + 'readable text', + 'trademarked names', + 'Sonic', + 'Mario', + 'Minecraft', + 'Nintendo', + 'Sega', + 'Mojang', + 'NSFW', + 'nude', + 'gore', + 'bloody', + 'horror' +].join(', ') + +const STYLE_PRESETS: Record = { + sticker: { + prefix: 'die-cut sticker illustration, clean bold outline, flat soft shading, centered subject, plain transparent-friendly background, cute original character mascot', + suffix: 'kid-friendly UI sticker, high clarity, no watermark, original character not based on copyrighted IP', + defaultWidth: 1024, + defaultHeight: 1024 + }, + panel_bg: { + prefix: 'subtle repeating decorative background, soft kid-friendly theme, even lighting, not busy', + suffix: 'gentle panel background, no text, no logo, original pattern', + defaultWidth: 1280, + defaultHeight: 1280 + }, + icon: { + prefix: 'simple high-contrast UI icon, centered, clean silhouette, minimal detail', + suffix: 'app icon style, plain background, readable at small size, original symbol', + defaultWidth: 768, + defaultHeight: 768 + } +} + +export function parseAssetPackStyle(raw: unknown, fallback: AssetPackStyle = 'sticker'): AssetPackStyle { + const value = String(raw || '').trim().toLowerCase() + return (ASSET_PACK_STYLES as readonly string[]).includes(value) + ? (value as AssetPackStyle) + : fallback +} + +export function parseAssetPackEngine(raw: unknown, fallback: ImageV2Engine = 'flux'): ImageV2Engine { + return parseImageV2Engine(raw, fallback) +} + +export function assetPackSize(style: AssetPackStyle, width?: unknown, height?: unknown) { + const preset = STYLE_PRESETS[style] + return clampImageV2Size( + width == null || width === '' ? preset.defaultWidth : width, + height == null || height === '' ? preset.defaultHeight : height + ) +} + +export function buildAssetPackPrompt(opts: { + prompt: string + style?: AssetPackStyle + transparentFriendly?: boolean +}) { + const style = opts.style || 'sticker' + const preset = STYLE_PRESETS[style] + const body = String(opts.prompt || '').trim() + const transparent = opts.transparentFriendly + ? 'solid plain background for easy keying or crop, no busy backdrop, chroma-friendly fill' + : '' + return [preset.prefix, transparent, body, preset.suffix] + .map(part => String(part || '').trim()) + .filter(Boolean) + .join(', ') +} + +export function buildAssetPackNegative(userNegative?: string) { + const extra = String(userNegative || '').trim() + return extra + ? `${ASSET_PACK_DEFAULT_NEGATIVE}, ${extra}` + : ASSET_PACK_DEFAULT_NEGATIVE +}