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 O9: fal derives the depth from the cut, one LoRA copy per render, a look without its LoRA says so

Claude4c5147541b24
diff --git a/docs/research/fuobe-originals-recipes-5.json b/docs/research/fuobe-originals-recipes-5.json
index 6d028123..9e4bda83 100644
--- a/docs/research/fuobe-originals-recipes-5.json
+++ b/docs/research/fuobe-originals-recipes-5.json
@@ -18144,6 +18144,10 @@
"match_input_num_frames": true,
"match_input_frames_per_second": true
},
+ "fixed": {
+ "preprocess": true
+ },
+ "fixedNote": "preprocess on: fal derives the depth control from the cut itself. With it off (fal's default), video_url is read as the control video, and fal's own example input for this endpoint is a precomputed grayscale depth-map video (wan-vace-depth-video.mp4); Fuobe sends the RGB cut. Only first_frame_url carries the restyled frame: ref_image_urls (VACE's subject references) isn't sent. Unverified until the first live run.",
"frame": "fal-ai/qwen-image-edit-2511",
"segment": {
"maxFrames": 241,
@@ -18159,6 +18163,11 @@
"restyle": "video-restyle-wan22-fun-vace",
"join": "video-concat-N",
"mux": "video-mux-audio"
+ },
+ "licence": {
+ "licence": "Apache-2.0",
+ "commercial": true,
+ "note": "Wan 2.2 Fun VACE A14B (the restyle) and Qwen-Image-Edit 2511 (the first frame) are Apache-2.0; on the open engine Depth Anything 3 mono-large and lightx2v too"
}
}
},
diff --git a/scripts/gen-cloud-models.py b/scripts/gen-cloud-models.py
index a4b2dc64..df3e9b9b 100644
--- a/scripts/gen-cloud-models.py
+++ b/scripts/gen-cloud-models.py
@@ -72,7 +72,7 @@ M = []
def model(id, name, vendor, family, kind, tagline, routes, badges=None, pricing=None, defaults=None, options=None, fixed=None, hidden=False,
sliders=None, controls=None, api_defaults=None, formats=None, ranged_durations=False, fit_values=False, fps_targets=None, upscale_tiers=None,
- frame_step=None, original=False, sizes=None):
+ frame_step=None, original=False, sizes=None, licence=None):
"""sliders / controls: [(field, label)] read from each route's research inputs (dotted = nested field):
numeric fields with minimum/maximum become sliders, enums become composer controls; both travel as params.extra.
fixed: fields always sent. api_defaults: fields sent unless the request sets them (FieldMap.defaults).
@@ -88,13 +88,14 @@ def model(id, name, vendor, family, kind, tagline, routes, badges=None, pricing=
original: a Fuobe Original's cloud half (written to ORIGINAL_CLOUD; models.ts joins it to the ComfyUI routes).
sizes: {tier: {aspect: [w, h]}}: exact sizes per resolution tier (Fuobe Soul's table): FieldMap.size.table, sent
as width / height fields or as one {width, height} object field (fal's image_size); the tiers become the resolutions.
+ licence: the open weights' licence (ModelLicence) when no hosted LoRA endpoint the model runs on records it.
A route's options dict may also set max_images (FieldMap.maxImages), note, loraEndpoint (the same model with LoRAs:
FieldMap.loras comes from its research record) and pin (a Replicate model run by version: the research's version)."""
M.append(dict(id=id, name=name, vendor=vendor, family=family, kind=kind, tagline=tagline, routes=routes,
badges=badges or [], pricing=pricing, defaults=defaults or {}, options=options or {}, fixed=fixed or {}, hidden=hidden,
sliders=sliders or [], controls=controls or [], api_defaults=api_defaults or {}, formats=formats or {},
ranged_durations=ranged_durations, fit_values=fit_values, fps_targets=fps_targets or [], upscale_tiers=upscale_tiers or [],
- frame_step=frame_step, original=original, sizes=sizes))
+ frame_step=frame_step, original=original, sizes=sizes, licence=licence))
# ----- Image
@@ -563,12 +564,17 @@ model("fuobe-genjutsu-swap-lite", "Fuobe Genjutsu Lite · Swap", "Fuobe Original
[("video-swap", _VACE14, "fal", {"keys": {"mask": "mask_video_url"}, "fixed": {"resolution": "480p", "acceleration": "regular"}})],
original=True, pricing=("second", 0.04, f"480p · {_FRAMES16}"), options={"resolutions": ["480p"]},
api_defaults={"match_input_num_frames": True, "match_input_frames_per_second": True}, defaults={"resolution": "480p"})
+# fal's Wan 2.2 Fun VACE depth endpoint reads video_url as the depth control unless preprocess is on (its example input is
+# a precomputed depth-map video): Fuobe sends the RGB clip, so fal derives the depth itself (research
+# studios[shorts].original.cloud.fixedNote; unverified until the first live run).
+SHORTS_O = next(s for s in ORIGINALS["studios"] if s["id"] == "shorts")["original"]
model("fuobe-genjutsu-restyle", "Fuobe Genjutsu · Restyle", "Fuobe Original", "fuobe-genjutsu", "video",
"Every frame takes the look of a restyled first frame, motion kept by depth: Wan 2.2 Fun VACE",
- [("v2v", "fal-ai/wan-22-vace-fun-a14b/depth")],
+ [("v2v", "fal-ai/wan-22-vace-fun-a14b/depth", "fal", {"fixed": SHORTS_O["cloud"]["fixed"]})],
original=True, fit_values=True, pricing=("second", 0.1, f"720p; 580p $0.075, 480p $0.05 · {_FRAMES16}; the first frame's restyle is priced on its own",
{"byResolution": {"720p": 0.1, "580p": 0.075, "480p": 0.05}}),
- api_defaults={"match_input_num_frames": True, "match_input_frames_per_second": True}, defaults={"resolution": "720p"})
+ api_defaults={"match_input_num_frames": True, "match_input_frames_per_second": True}, defaults={"resolution": "720p"},
+ licence={**SHORTS_O["licence"], "note": "Wan 2.2 Fun VACE A14B weights are Apache-2.0 (the first frame's model has its own licence)"})
# Character swap (Openjutsu / Akatz Labs' H3 Character Swap): the part of the clip (5–15 s) is Video 1, the character
# Image 1 and the anchor first frame Image 2. Prompt expansion off so H3's reference tags reach the model as written.
model("fuobe-character-swap", "Fuobe Character swap", "Fuobe Original", "fuobe-character-swap", "video",
@@ -589,13 +595,14 @@ model("fuobe-mixed-media", "Fuobe Mixed Media", "Fuobe Original", "fuobe-mixed-m
"Every frame drawn again in the look under its own outlines, one seed: Z-Image Turbo + ControlNet with the look's LoRA",
[("edit", MIXED_O["frame"], "fal", {"fixed": MIXED_O["fixed"], "defaults": MIXED_O["defaults"]})],
original=True, pricing=("megapixel", per_megapixel(MIXED_O["frame"]), MIXED_O["price"]))
-SHORTS_O = next(s for s in ORIGINALS["studios"] if s["id"] == "shorts")["original"]["cloud"]
+# The restyled first frame goes as first_frame_url only (the recipe sends no VACE subject references: `images` is dropped),
+# and fal derives the depth from the cut (preprocess, fixed).
model("fuobe-shorts", "Fuobe Shorts", "Fuobe Original", "fuobe-shorts", "video",
"Your footage in a new look, motion kept: a restyled first frame carried through every frame by depth (Wan 2.2 Fun VACE)",
- [("v2v", SHORTS_O["restyle"], "fal", {"drop": ["aspectRatio"]})],
+ [("v2v", SHORTS_O["cloud"]["restyle"], "fal", {"drop": ["aspectRatio", "images"], "fixed": SHORTS_O["cloud"]["fixed"]})],
original=True, fit_values=True, pricing=("second", 0.1, f"720p; 580p $0.075, 480p $0.05 · {_FRAMES16}; the first frame's Qwen edit is priced on its own",
{"byResolution": {"720p": 0.1, "580p": 0.075, "480p": 0.05}}),
- api_defaults=SHORTS_O["defaults"], defaults={"resolution": "720p"})
+ api_defaults=SHORTS_O["cloud"]["defaults"], defaults={"resolution": "720p"}, licence=SHORTS_O["licence"])
model("ltx-2-5", "LTX 2.5 Pro", "Lightricks", "ltx", "video", "Fast 4K-capable video with audio",
[("t2v", "lightricks/ltx-2.5/text-to-video/pro"), ("i2v", "lightricks/ltx-2.5/image-to-video/pro")],
badges=["audio"], defaults={"aspectRatio": "16:9"})
@@ -1929,6 +1936,8 @@ for m in M:
d["licence"] = {"licence": lic["baseLicence"], "commercial": lic.get("commercialWeights"),
**({"note": lic["licenceNote"]} if lic.get("licenceNote") else {}),
**({"checked": lic["checked"]} if lic.get("checked") else {})}
+ elif m["licence"]:
+ d["licence"] = m["licence"]
defaults = {k: v for k, v in m["defaults"].items()}
# Drop defaults the model can't take.
if "aspectRatio" in defaults and defaults["aspectRatio"] not in opts.get("aspectRatios", [defaults["aspectRatio"]]):
diff --git a/skills/ad-multiplier/SKILL.md b/skills/ad-multiplier/SKILL.md
index 0c94fe12..bb8d48bc 100644
--- a/skills/ad-multiplier/SKILL.md
+++ b/skills/ad-multiplier/SKILL.md
@@ -26,8 +26,10 @@ Prompt is exclusive with Hook/CTA; Hook and CTA can be combined.
Op `v2v` with the ad in `video` and the change described precisely ("same shots and timing; the
creator is now in a sunny kitchen; the product is the green bottle from the image"), product or
subject photos in `images`. Cloud `kling-o3` (video edit with up to 4 references), `happy-horse-video-edit`,
-`gemini-omni-flash`; open `oss-mixed-media` or `oss-wan22-vace-restyle`. Resolution 1080p by
-default (480p for quick tests). 3–5 variants per batch, each one `generate` job.
+`gemini-omni-flash`; open (with `engine: "open"`) `fuobe-mixed-media` (every frame redrawn in the
+look, one seed; it reads no photos) or `fuobe-shorts` (Wan 2.2 Fun VACE carries a restyled first
+frame, given in `images`, through the ad). Resolution 1080p by default (480p for quick tests).
+3–5 variants per batch, each one `generate` job.
## Hook / CTA variants
1. Get the first (or last) frame: op `frame` on the ad, or ask the user for a screenshot.
diff --git a/src/components/mixed-media/mixed-studio.tsx b/src/components/mixed-media/mixed-studio.tsx
index 0e4fde23..bbbfb13d 100644
--- a/src/components/mixed-media/mixed-studio.tsx
+++ b/src/components/mixed-media/mixed-studio.tsx
@@ -377,7 +377,8 @@ function Editor({
},
range: mmRange,
fps,
- resolution: resShown,
+ // Smooth has no Resolution control: its first frame is drawn at 1K (a 2K pick under Per frame doesn't carry over unseen).
+ resolution: smooth ? "1K" : resShown,
modelId,
mode,
...(anchor ? { anchor } : {}),
diff --git a/src/lib/catalog/cloud-models.generated.ts b/src/lib/catalog/cloud-models.generated.ts
index 2d6f7f0a..d7a7b447 100644
--- a/src/lib/catalog/cloud-models.generated.ts
+++ b/src/lib/catalog/cloud-models.generated.ts
@@ -18739,6 +18739,9 @@ export const ORIGINAL_CLOUD: ModelDef[] = [
"720p"
]
},
+ "fixed": {
+ "preprocess": true
+ },
"defaults": {
"match_input_num_frames": true,
"match_input_frames_per_second": true
@@ -18765,6 +18768,11 @@ export const ORIGINAL_CLOUD: ModelDef[] = [
],
"maxImages": 4
},
+ "licence": {
+ "licence": "Apache-2.0",
+ "commercial": true,
+ "note": "Wan 2.2 Fun VACE A14B weights are Apache-2.0 (the first frame's model has its own licence)"
+ },
"defaults": {
"resolution": "720p"
},
@@ -18934,7 +18942,6 @@ export const ORIGINAL_CLOUD: ModelDef[] = [
"map": {
"negativePrompt": "negative_prompt",
"image": "first_frame_url",
- "images": "ref_image_urls",
"video": "video_url",
"seed": "seed",
"fps": "frames_per_second",
@@ -18949,6 +18956,9 @@ export const ORIGINAL_CLOUD: ModelDef[] = [
"720p"
]
},
+ "fixed": {
+ "preprocess": true
+ },
"defaults": {
"match_input_num_frames": true,
"match_input_frames_per_second": true
@@ -18967,7 +18977,12 @@ export const ORIGINAL_CLOUD: ModelDef[] = [
"580p",
"720p"
],
- "maxImages": 4
+ "maxImages": 1
+ },
+ "licence": {
+ "licence": "Apache-2.0",
+ "commercial": true,
+ "note": "Wan 2.2 Fun VACE A14B (the restyle) and Qwen-Image-Edit 2511 (the first frame) are Apache-2.0; on the open engine Depth Anything 3 mono-large and lightx2v too"
},
"defaults": {
"resolution": "720p"
diff --git a/src/lib/catalog/shorts.ts b/src/lib/catalog/shorts.ts
index 6717c3e9..e94db852 100644
--- a/src/lib/catalog/shorts.ts
+++ b/src/lib/catalog/shorts.ts
@@ -36,7 +36,7 @@ export const SHORTS = {
* Fuobe Shorts in the cloud: fal's Wan 2.2 Fun VACE makes 17–241 frames at 5–30 fps, matching its input clip's count and
* rate. A clip above 30 fps is worked at half (a third…) its rate and brought back (temporal_downsample_factor).
*/
- original: { maxFrames: 240, maxFps: 30, billFps: 16 },
+ original: { minFrames: 17, maxFrames: 240, minFps: 5, maxFps: 30, billFps: 16 },
accept: "video/mp4,video/quicktime,video/webm,.mp4,.mov,.m4v,.webm",
} as const;
@@ -383,6 +383,20 @@ export function planSegments(range: ShortsRange, engine: Engine, model?: { model
return model?.modelId === SHORTS_ORIGINAL ? planCloudSegments(range, originalSegmentSeconds(model.fps)) : planCloudSegments(range);
}
+/**
+ * What fal's Wan 2.2 Fun VACE won't take in a Fuobe Shorts cloud piece, if anything: fewer than 17 frames as it works them,
+ * or a clip under 5 fps. Said before anything runs (the cut, the first frame and its edit would be paid for, then refused).
+ * Null when the clip's rate isn't known.
+ */
+export function originalSegmentProblem(seconds: number, fps?: number): string | null {
+ if (!fps || !(fps > 0)) return null;
+ const o = SHORTS.original;
+ if (fps < o.minFps - 0.01) return `Wan 2.2 Fun VACE needs a clip of at least ${o.minFps} fps (this one is ${+fps.toFixed(2)} fps)`;
+ const rate = fps / (vaceDownsample(fps) + 1);
+ if (Math.floor(seconds * rate + 1e-6) < o.minFrames) return `Wan 2.2 Fun VACE needs at least ${o.minFrames} frames: select at least ${Math.ceil((o.minFrames / rate) * 10) / 10} s of this ${+fps.toFixed(2)} fps clip`;
+ return null;
+}
+
/** The seconds fal bills for a Fuobe Shorts segment: its frames ÷ 16 ("video seconds"); an unknown rate counts as 30 fps. */
export function originalBilledSeconds(seconds: number, fps?: number): number {
return Math.round(((seconds * (fps && fps > 0 ? fps : SHORTS.original.maxFps)) / SHORTS.original.billFps) * 1e6) / 1e6;
diff --git a/src/server/assist/studio-tools.ts b/src/server/assist/studio-tools.ts
index 4d850d9d..abeb35d1 100644
--- a/src/server/assist/studio-tools.ts
+++ b/src/server/assist/studio-tools.ts
@@ -5,6 +5,7 @@ import type { PlannedJob } from "@/lib/assist";
import { getModel } from "@/lib/catalog";
import { routesFor } from "@/lib/catalog/plan";
import { FACELESS_STYLE_IDS, STYLES } from "@/lib/catalog/faceless";
+import { FRAME_SEED, MIXED_ORIGINAL } from "@/lib/catalog/mixed-media";
import { SHORTS_MODELS } from "@/lib/catalog/shorts";
import type { ChainSlot, Engine, GenerationRequest, Operation } from "@/lib/catalog/types";
import { TOOL_MODELS } from "@/lib/layers";
@@ -202,11 +203,21 @@ function layerSteps(i: LayersToolInput, ctx: ToolContext): PipelineStep[] {
function restyleSteps(i: RestyleToolInput, ctx: ToolContext): PipelineStep[] {
const refs = (i.references ?? []).slice(0, 4);
+ const modelId = pick(ctx, "kling-o3", MIXED_ORIGINAL, i.model_id);
+ // On your GPU: Fuobe Mixed Media's per-frame pass (every frame redrawn under its own outlines, one seed). Its graph
+ // reads no reference images; the style's words carry the look.
+ const original = modelId === MIXED_ORIGINAL;
return labelled([
{
key: "restyle",
label: "Restyled video",
- request: req({ modelId: pick(ctx, "kling-o3", "oss-mixed-media", i.model_id), op: "v2v", prompt: i.style, inputs: { video: i.video, ...(refs.length && { images: refs }) } }),
+ request: req({
+ modelId,
+ op: "v2v",
+ prompt: i.style,
+ ...(original && { engine: "open" as const, params: { seed: FRAME_SEED } }),
+ inputs: { video: i.video, ...(refs.length && !original && { images: refs }) },
+ }),
},
]);
}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 63a5462a..6aaa0119 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -18,6 +18,8 @@ import { fitLoras, lorasFit } from "@/lib/catalog/loras";
import { dualEngine, onEngine, pickEngine } from "@/lib/catalog/engines";
import { promptWithLoras, soulKind, soulLook, soulPostSteps } from "@/lib/catalog/soul";
import { isDop } from "@/lib/catalog/dop";
+import { MIXED_ORIGINAL, originalFrameSize } from "@/lib/catalog/mixed-media";
+import { imageSize } from "@/lib/image-size";
import { finishSteps } from "@/lib/soul-post";
import {
CHAIN_LIST_SLACK,
@@ -54,7 +56,7 @@ import { mediaFacts } from "./media-facts";
import { convertMask } from "./png";
import { engineMode, getSetting } from "./settings";
import { fetchRemoteToFile } from "./remote-fetch";
-import { adoptFile, contentTypeFor, deleteAsset, readRef, saveFile, scratchDir } from "./storage";
+import { adoptFile, contentTypeFor, deleteAsset, localHead, readRef, saveFile, scratchDir } from "./storage";
interface Row {
id: string;
@@ -484,6 +486,20 @@ export function offeredFor(m: ModelDef, asked: Engine | undefined): ModelDef {
return requireOffered(m, asked ?? (mode === "both" ? undefined : mode));
}
+/**
+ * Fuobe Mixed Media's single picture in the cloud (DoP's Mixed Media stills, an API caller's edit) drawn at about 1
+ * megapixel in its picture's shape, as it's priced: without a size, fal keeps the upload's own (a 12-megapixel photo
+ * costs 12 times as much). The studio sends each frame's size itself; a picture that isn't a file in Fuobe keeps fal's.
+ */
+function sizedMixedFrame(plan: ReturnType<typeof planGeneration>, req: GenerationRequest): ReturnType<typeof planGeneration> {
+ if (plan.model.id !== MIXED_ORIGINAL || plan.model.engine !== "cloud" || plan.op !== "edit" || plan.params.extra?.image_size) return plan;
+ const first = req.inputs?.images?.[0];
+ const head = first ? localHead(first) : null;
+ const size = head ? imageSize(head) : null;
+ const fit = size ? originalFrameSize(size, "1K") : undefined;
+ return fit ? { ...plan, params: { ...plan.params, extra: { ...plan.params.extra, image_size: fit } } } : plan;
+}
+
/** Resolve mentions and drawings, plan, enforce the engine mode and pick a provider route. */
function prepare(original: GenerationRequest) {
// @element mentions become reference images / LoRAs; the stored request keeps the mentions for "Reuse".
@@ -497,7 +513,7 @@ function prepare(original: GenerationRequest) {
const model = allowed && dualEngine(allowed) ? onEngine(allowed, engineFor(allowed, worded.engine)) : allowed;
const lookup = (id: string) => (model && id === model.id ? model : getModel(id));
const req = model ? stripMotionPaths(applySketch(applyMentions(worded, model, listElements()).request, model).request, model) : worded;
- let plan = planGeneration(req, lookup, getPreset);
+ let plan = sizedMixedFrame(planGeneration(req, lookup, getPreset), req);
if (mode !== "both" && plan.model.engine !== mode) {
throw new Error(
mode === "open"
@@ -519,14 +535,20 @@ function prepare(original: GenerationRequest) {
const { route, demo } = chooseRoute(offeredRoutes(plan.model, routesFor(plan.model, plan.op)), req.inputs?.images?.length ?? 0, plan.loras, seconds);
// What the cloud run can carry: a LoRA whose licence doesn't allow hosting stays on the GPU, and an API
// takes at most so many (the plan's notes say which were left out). Open runs carry them all. Without a
- // civitai key a Soul look's civitai LoRA the run can't get is left out (and said), rather than failing at the
- // download: the look's words still carry it. Any other run (a motion, whose LoRA is the point) still stops there.
+ // civitai key a look's civitai LoRA the run can't get is left out (and said), rather than failing at the
+ // download: the look's words still carry it. Looks are Fuobe Soul's and Fuobe Mixed Media's (the studio's frames,
+ // Smooth's first frame, DoP's Mixed Media stills). Any other run (a motion, whose LoRA is the point) still stops there.
const asked = plan.loras;
+ const look = !!plan.soul || plan.model.id === MIXED_ORIGINAL;
const reachable =
- demo || !plan.soul ? { loras: asked, notes: [] } : withoutUnreachableCivitai(asked, route.provider === "comfyui" ? "comfyui" : route.provider === "replicate" ? "replicate" : "fal");
+ demo || !look ? { loras: asked, notes: [] } : withoutUnreachableCivitai(asked, route.provider === "comfyui" ? "comfyui" : route.provider === "replicate" ? "replicate" : "fal");
const fitted = fitLoras(reachable.loras, route);
- // A Soul look's triggers lead the prompt: a LoRA left out takes its trigger with it.
- const prompt = plan.soul ? promptWithLoras(plan.prompt, plan.soul.triggers, fitted.loras) : plan.prompt;
+ // A look's triggers lead the prompt: a LoRA left out takes its trigger with it.
+ const prompt = plan.soul
+ ? promptWithLoras(plan.prompt, plan.soul.triggers, fitted.loras)
+ : look
+ ? withoutTriggers(plan.prompt, asked.filter((l) => !reachable.loras.includes(l)), reachable.loras)
+ : plan.prompt;
plan = { ...plan, prompt, loras: fitted.loras };
const notes = [...(plan.notes ?? []), ...access.notes, ...reachable.notes, ...fitted.notes];
// A frame-count API that can't make the length asked (Replicate's Wan 2.2 fast: 81–121 frames) says what it makes.
diff --git a/src/server/loras.ts b/src/server/loras.ts
index 293d706e..ea1c4043 100644
--- a/src/server/loras.ts
+++ b/src/server/loras.ts
@@ -271,6 +271,22 @@ function downloadOnce(ref: LoraRef, dir: string, onProgress?: (m: string) => voi
return p;
}
+/**
+ * One copy per file and host at a time: a per-frame render (Fuobe Mixed Media: up to 240 frames with the same look LoRA)
+ * starts many submits at once, and each would otherwise read the file, ask civitai and upload it again. The ones that
+ * come after the first wait for its copy (or its error).
+ */
+const mirroring = new Map<string, Promise<LoraRef>>();
+
+function mirrorOnce(l: LoraRef, target: "fal" | "replicate", copy: () => Promise<LoraRef>): Promise<LoraRef> {
+ const key = `${target}::${l.file}`;
+ const cur = mirroring.get(key);
+ if (cur) return cur.then((done) => ({ ...l, hostedUrl: done.hostedUrl }));
+ const p = copy().finally(() => mirroring.delete(key));
+ mirroring.set(key, p);
+ return p;
+}
+
/** The licence a copy is made under: the research's snapshot (and the permissions civitai shows today, when read). */
const licenceSnapshot = (ref: LoraRef, entry: LoraEntry | undefined, permissionsNow?: string[] | null) => {
const l = ref.licence ?? entry?.licence;
@@ -348,7 +364,7 @@ export async function prepareCloudLoras(
// Only while the admin keeps GPU-only LoRAs on the GPU (fitLoras has left it out of a cloud run already).
if (localOnly(l)) throw new LoraError(`${name} is licensed for your GPU only, and Settings → Models & licences keeps such LoRAs off the cloud`);
if (l.own && !l.hostedUrl) {
- out.push(await sendOwnLora(l, target, upload, onProgress));
+ out.push(await mirrorOnce(l, target, () => sendOwnLora(l, target, upload, onProgress)));
continue;
}
if (cloudPath(l)) {
@@ -362,52 +378,66 @@ export async function prepareCloudLoras(
out.push({ ...l, hostedUrl: cached.hostedUrl });
continue;
}
- // The hosting right is read again before a copy is made (civitai permissions can change) and recorded with the copy.
- // It decides only while the admin keeps GPU-only LoRAs on the GPU: then no answer, or no "Rent", means no copy.
- const version = l.version ?? entry?.version ?? civitaiVersion(l.url);
- const strict = !!l.keepOnGpu;
- const modelId = entry?.civitaiModel ?? (version ? (await civitaiVersionFacts(version)).modelId : undefined);
- const now = modelId ? await civitaiPermissions(modelId) : null;
- if (strict && !now) throw new LoraError(`Couldn't confirm on civitai that ${name} may run on a hosted service, so it isn't copied to ${host} (Settings → Models & licences keeps LoRAs licensed for your GPU only off the cloud). Try again in a moment, or run it on your GPU`);
- if (strict && !now!.includes("Rent")) {
- throw new LoraError(`${name}'s civitai licence no longer allows running it on a hosted service, and Settings → Models & licences keeps such LoRAs off the cloud, so it runs only on your GPU`);
- }
- // A copy already on this machine is used when its bytes are the pinned ones (a same-named file may be another LoRA).
- const local = [getSetting("comfyLorasDir"), LORA_CACHE_DIR]
- .filter(Boolean)
- .map((d) => {
- try {
- return lorasPath(d, l.file);
- } catch {
- return "";
- }
- })
- .find((p) => p && fs.existsSync(p) && (!entry?.sha256 || sha256File(p) === entry.sha256));
- let file = local;
- let facts: Pick<Downloaded, "sha256" | "sizeBytes" | "version"> | null = null;
- if (!file) {
- const got = await downloadOnce(l, LORA_CACHE_DIR, onProgress);
- file = got.path;
- facts = got;
- }
- onProgress?.(`Copying ${name} to ${host} (once)`);
- const data = fs.readFileSync(file);
- const hostedUrl = await upload(data, path.basename(l.file));
- recordCopy({
- file: l.file,
- target,
- sourceUrl: l.url,
- version: facts?.version ?? l.version ?? entry?.version ?? null,
- hostedUrl,
- sha256: facts?.sha256 ?? crypto.createHash("sha256").update(data).digest("hex"),
- sizeBytes: data.length,
- licence: { ...licenceSnapshot(l, entry, now), ...(hostingNote(now) && { hosting: hostingNote(now) }) },
- });
- out.push({ ...l, hostedUrl });
+ const civitai = { ...l, url: l.url };
+ out.push(await mirrorOnce(l, target, () => mirrorCivitai(civitai, entry, target, upload, onProgress)));
}
return out;
}
+/** A civitai LoRA copied to the provider's storage (once: prepareCloudLoras runs it through mirrorOnce). */
+async function mirrorCivitai(
+ l: LoraRef & { url: string },
+ entry: LoraEntry | undefined,
+ target: "fal" | "replicate",
+ upload: (data: Buffer, name: string) => Promise<string>,
+ onProgress?: (m: string) => void,
+): Promise<LoraRef> {
+ const host = target === "fal" ? "fal.ai" : "Replicate";
+ const name = loraName(l);
+ // The hosting right is read again before a copy is made (civitai permissions can change) and recorded with the copy.
+ // It decides only while the admin keeps GPU-only LoRAs on the GPU: then no answer, or no "Rent", means no copy.
+ const version = l.version ?? entry?.version ?? civitaiVersion(l.url);
+ const strict = !!l.keepOnGpu;
+ const modelId = entry?.civitaiModel ?? (version ? (await civitaiVersionFacts(version)).modelId : undefined);
+ const now = modelId ? await civitaiPermissions(modelId) : null;
+ if (strict && !now) throw new LoraError(`Couldn't confirm on civitai that ${name} may run on a hosted service, so it isn't copied to ${host} (Settings → Models & licences keeps LoRAs licensed for your GPU only off the cloud). Try again in a moment, or run it on your GPU`);
+ if (strict && !now!.includes("Rent")) {
+ throw new LoraError(`${name}'s civitai licence no longer allows running it on a hosted service, and Settings → Models & licences keeps such LoRAs off the cloud, so it runs only on your GPU`);
+ }
+ // A copy already on this machine is used when its bytes are the pinned ones (a same-named file may be another LoRA).
+ const local = [getSetting("comfyLorasDir"), LORA_CACHE_DIR]
+ .filter(Boolean)
+ .map((d) => {
+ try {
+ return lorasPath(d, l.file);
+ } catch {
+ return "";
+ }
+ })
+ .find((p) => p && fs.existsSync(p) && (!entry?.sha256 || sha256File(p) === entry.sha256));
+ let file = local;
+ let facts: Pick<Downloaded, "sha256" | "sizeBytes" | "version"> | null = null;
+ if (!file) {
+ const got = await downloadOnce(l, LORA_CACHE_DIR, onProgress);
+ file = got.path;
+ facts = got;
+ }
+ onProgress?.(`Copying ${name} to ${host} (once)`);
+ const data = fs.readFileSync(file);
+ const hostedUrl = await upload(data, path.basename(l.file));
+ recordCopy({
+ file: l.file,
+ target,
+ sourceUrl: l.url,
+ version: facts?.version ?? l.version ?? entry?.version ?? null,
+ hostedUrl,
+ sha256: facts?.sha256 ?? crypto.createHash("sha256").update(data).digest("hex"),
+ sizeBytes: data.length,
+ licence: { ...licenceSnapshot(l, entry, now), ...(hostingNote(now) && { hosting: hostingNote(now) }) },
+ });
+ return { ...l, hostedUrl };
+}
+
// ---------------------------------------------------------------------------
// The user's own trained LoRAs (Fuobe Soul ID)
@@ -556,6 +586,27 @@ export function withoutUnreachableCivitai(loras: LoraRef[], target: MirrorTarget
};
}
+/**
+ * Before a look's run on your GPU (Fuobe Mixed Media) while Settings → LoRAs has no LoRA folder: Fuobe can't download a
+ * LoRA for ComfyUI then, so one ComfyUI doesn't list is left out (and said) and the look runs on its words, instead of
+ * failing when the run is handed over (ensureLorasOnComfy). `listed`: ComfyUI's LoRA files (null when it couldn't say:
+ * nothing is left out, ComfyUI's own check has the last word).
+ */
+export function withoutMissingOnComfy(loras: LoraRef[], listed: string[] | null): { loras: LoraRef[]; notes: string[] } {
+ if (!loras.length || !listed || getSetting("comfyLorasDir")) return { loras, notes: [] };
+ const have = new Set(listed.map((f) => f.replace(/\\/g, "/")));
+ const missing = loras.filter((l) => l.file && !have.has(l.file));
+ if (!missing.length) return { loras, notes: [] };
+ const names = [...new Set(missing.map(loraName))];
+ const list = names.length < 2 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
+ return {
+ loras: loras.filter((l) => !missing.includes(l)),
+ notes: [
+ `ComfyUI doesn't have ${list} yet, and Fuobe downloads LoRAs for it only once Settings → LoRAs has its LoRA folder, so this run leaves ${names.length > 1 ? "them" : "it"} out (the look runs on its words)`,
+ ],
+ };
+}
+
/** Test the civitai key (Settings → Save & test): civitai's /me answers 200 for a good key. */
export async function testCivitaiKey(): Promise<{ ok: boolean; detail: string }> {
const token = civitaiKey();
diff --git a/src/server/mixed-media.ts b/src/server/mixed-media.ts
index c8949c1e..6dec019a 100644
--- a/src/server/mixed-media.ts
+++ b/src/server/mixed-media.ts
@@ -25,14 +25,15 @@ import {
type MixedResolution,
} from "@/lib/catalog/mixed-media";
import { mixedLoras } from "@/lib/catalog/mixed-media-looks";
-import { clipLengthProblem, planSegments, type PlanStep } from "@/lib/catalog/shorts";
+import { clipLengthProblem, originalSegmentProblem, planSegments, type PlanStep } from "@/lib/catalog/shorts";
import { sourceSeconds, takesImage } from "@/lib/catalog/shorts-models";
import type { Engine, Generation, ProviderId } from "@/lib/catalog/types";
import { createPipeline } from "./chains";
import { db } from "./db";
import { DROPPED_UNUSED, getGeneration, previewChained, unfilledRequest, waitedOnFailure } from "./generations";
-import { withoutUnreachableCivitai } from "./loras";
-import { engineMode } from "./settings";
+import { withoutMissingOnComfy, withoutUnreachableCivitai } from "./loras";
+import { comfyLoraFiles, probeComfy } from "./providers/comfyui";
+import { engineMode, getSetting } from "./settings";
import { probeSource, ShortsError } from "./shorts";
/**
@@ -146,7 +147,11 @@ async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ i
if (body.anchor && !anchor) notes.push(`${model?.name} restyles from words only — the preview frame isn't sent`);
notes.push(`${model?.name} restyles the clip as smooth video in one pass — Per frame redraws every frame of it instead`);
} else if (mode === "smooth") {
- const pieces = planSegments(body.range, body.engine, { modelId: MIXED_SMOOTH_MODEL, fps: sourceFps }).length;
+ const segments = planSegments(body.range, body.engine, { modelId: MIXED_SMOOTH_MODEL, fps: sourceFps });
+ const pieces = segments.length;
+ // fal's Wan 2.2 Fun VACE takes 17 frames or more, at 5 fps or more: refused here, before the cut and the first frame are paid for.
+ const vace = body.engine === "cloud" ? segments.map((s) => originalSegmentProblem(s.end - s.start, sourceFps)).find(Boolean) : null;
+ if (vace) throw new ShortsError(`${vace} — or pick Per frame`, 422);
notes.push(
body.engine === "open"
? `Smooth draws the first frame in the look, then Wan 2.2 Fun VACE carries it through the clip by depth: 480p at 16 fps on your GPU${pieces > 1 ? `, in ${pieces} pieces of up to 5 s` : ""}`
@@ -155,7 +160,13 @@ async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ i
if (body.engine === "cloud" && sourceFps && sourceFps > 16.5) notes.push(`fal bills this clip's ${Math.round(sourceFps)} fps as ${(sourceFps / 16).toFixed(1)}× its length (video seconds at 16 fps)`);
} else if (body.engine === "open" && body.resolution !== "1K") notes.push("The open engine renders up to 1536 px on the long side");
// The look's LoRA: one that downloads from civitai needs the civitai key; without it the look runs on its words.
- const reach = original && mode !== "fast" ? withoutUnreachableCivitai(mixedLoras(preset.id), body.engine === "open" ? "comfyui" : "fal") : undefined;
+ let reach = original && mode !== "fast" ? withoutUnreachableCivitai(mixedLoras(preset.id), body.engine === "open" ? "comfyui" : "fal") : undefined;
+ // On your GPU without a LoRA folder (Settings → LoRAs) Fuobe can't download one, so ComfyUI must have it already: a LoRA
+ // it doesn't list is left out and said here, rather than the render failing once it's handed over.
+ if (reach?.loras.length && body.engine === "open" && !getSetting("comfyLorasDir") && (await probeComfy())) {
+ const onComfy = withoutMissingOnComfy(reach.loras, await comfyLoraFiles());
+ reach = { loras: onComfy.loras, notes: [...reach.notes, ...onComfy.notes] };
+ }
if (reach) notes.push(...reach.notes);
const name = (body.source.name ?? "").replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, 40);
return {
diff --git a/src/server/shorts.ts b/src/server/shorts.ts
index b9d83061..8ca9f550 100644
--- a/src/server/shorts.ts
+++ b/src/server/shorts.ts
@@ -10,6 +10,7 @@ import {
lookFromCustom,
lookFromPreset,
needsFit,
+ originalSegmentProblem,
planSegments,
planShorts,
planStitch,
@@ -249,10 +250,12 @@ function planWith(body: ShortsBody, info: SourceInfo): { input: ShortsPlanInput;
if (problem) throw new ShortsError(problem);
// Every segment has to be a clip the restyle model takes (a cut outside its window is paid for, then refused).
const limits = sourceSeconds(modelId);
- const odd = planSegments(body.range, body.engine, { modelId, fps })
- .map((s) => clipLengthProblem({ name: getModel(modelId)?.name ?? modelId, minSeconds: limits.min, maxSeconds: limits.max }, s.end - s.start))
- .find(Boolean);
+ const segments = planSegments(body.range, body.engine, { modelId, fps });
+ const odd = segments.map((s) => clipLengthProblem({ name: getModel(modelId)?.name ?? modelId, minSeconds: limits.min, maxSeconds: limits.max }, s.end - s.start)).find(Boolean);
if (odd) throw new ShortsError(`${odd} per segment — pick another model`);
+ // Fuobe Shorts in the cloud: fal's Wan 2.2 Fun VACE takes 17 frames or more, at 5 fps or more.
+ const vace = modelId === SHORTS_ORIGINAL && body.engine === "cloud" ? segments.map((s) => originalSegmentProblem(s.end - s.start, fps)).find(Boolean) : null;
+ if (vace) throw new ShortsError(`${vace} — or pick another model`);
// A custom preset without words on a words-only model would restyle from nothing but "the look of the reference images".
if (look.custom && !look.described && body.engine === "cloud" && !maxRefsFor(modelId, "cloud")) {
const readers = SHORTS_MODELS.cloud.filter((id) => maxRefsFor(id, "cloud") > 0).map((id) => getModel(id)?.name ?? id);
diff --git a/src/server/storage.ts b/src/server/storage.ts
index ec6bc6b0..36cbfd4a 100644
--- a/src/server/storage.ts
+++ b/src/server/storage.ts
@@ -224,6 +224,27 @@ export function absolutePath(relPath: string): string {
return abs;
}
+/**
+ * The first bytes of a file saved in Fuobe (an /api/files/ URL or an asset id), read at once: enough for a picture's
+ * size (src/lib/image-size.ts). Null for a link elsewhere, a data URI or a file that's gone.
+ */
+export function localHead(ref: string, maxBytes = 512 * 1024): Buffer | null {
+ try {
+ const rel = ref.startsWith("/api/files/") ? decodeURIComponent(ref.slice("/api/files/".length).split("?")[0]) : /^[\w-]{6,40}$/.test(ref) ? getAsset(ref)?.relPath : undefined;
+ if (!rel) return null;
+ const fd = fs.openSync(absolutePath(rel), "r");
+ try {
+ const buf = Buffer.alloc(Math.min(maxBytes, fs.fstatSync(fd).size));
+ fs.readSync(fd, buf, 0, buf.length, 0);
+ return buf;
+ } finally {
+ fs.closeSync(fd);
+ }
+ } catch {
+ return null;
+ }
+}
+
/**
* Resolve an asset reference from the UI (asset id, /api/files/... URL, http(s) URL or data URI)
* to bytes + content type.
diff --git a/tests/assist-context.test.ts b/tests/assist-context.test.ts
index f028b4b3..272fcf60 100644
--- a/tests/assist-context.test.ts
+++ b/tests/assist-context.test.ts
@@ -277,7 +277,12 @@ describe("studio tools", () => {
expect(studio.fallbackSteps.captions({ video, translate_to: "Spanish" }, { engine: "cloud" })[0].request).toMatchObject({ modelId: "veed-subtitles", params: { targetLanguage: "Spanish" } });
expect(plan("split_layers", { image: "/api/files/uploads/a.png", layers: 5 }).jobs).toMatchObject([{ op: "layers", modelId: "oss-qwen-layered" }]);
expect(plan("restyle_footage", { video, style: "claymation" }, "cloud").jobs).toMatchObject([{ op: "v2v", modelId: "kling-o3" }]);
- const ads = studio.fallbackSteps.ads({ brief: "oat milk", product_image: "/api/files/uploads/p.png", count: 8, aspect_ratios: ["1:1", "4:5", "9:16"] }, { engine: "cloud" });
+ // On your GPU: Fuobe Mixed Media's per-frame pass on the GPU, one seed (its graph reads no reference images).
+ const [open] = studio.fallbackSteps.restyle({ video, style: "anime", references: ["/api/files/uploads/r.png"] }, { engine: "open" });
+ expect(open.request).toMatchObject({ modelId: "fuobe-mixed-media", engine: "open", op: "v2v", prompt: "anime", params: { seed: 424242 }, inputs: { video } });
+ expect(open.request.inputs?.images).toBeUndefined();
+ expect(plan("restyle_footage", { video, style: "claymation" }, "open").jobs).toMatchObject([{ op: "v2v", modelId: "fuobe-mixed-media" }]);
+ const ads =studio.fallbackSteps.ads({ brief: "oat milk", product_image: "/api/files/uploads/p.png", count: 8, aspect_ratios: ["1:1", "4:5", "9:16"] }, { engine: "cloud" });
expect(ads).toHaveLength(12);
expect(ads[0]).toMatchObject({ modelId: "nano-banana-pro", op: "edit", inputs: { images: ["/api/files/uploads/p.png"] } });
});
diff --git a/tests/e2e/mixed-shorts-original.mjs b/tests/e2e/mixed-shorts-original.mjs
index 015ddd4f..95d9de7e 100644
--- a/tests/e2e/mixed-shorts-original.mjs
+++ b/tests/e2e/mixed-shorts-original.mjs
@@ -225,8 +225,18 @@ try {
await estimate.waitFor({ timeout: 30_000 }).catch(() => {});
const price = await estimate.innerText();
check("prices · mixed: a dollar estimate before running", /≈ \$\d/.test(price), price);
+ // A 2K pick under Per frame doesn't carry over to Smooth, which shows no Resolution: its first frame is drawn at 1K.
+ await page.getByRole("radiogroup", { name: "Resolution" }).getByRole("radio", { name: "2K" }).click();
+ await page.waitForTimeout(800);
+ const asked = [];
+ page.on("request", (req) => {
+ if (req.method() === "POST" && req.url().includes("/api/mixed-media/estimate")) asked.push(req.postDataJSON());
+ });
await page.getByRole("radiogroup", { name: "Restyle" }).getByRole("radio", { name: "Smooth" }).click();
await page.waitForTimeout(1500);
+ const smoothAsk = asked.filter((b) => b?.mode === "smooth").at(-1);
+ check("prices · mixed: Smooth asks for 1K after a 2K pick under Per frame", smoothAsk?.resolution === "1K", JSON.stringify(smoothAsk?.resolution));
+ check("prices · mixed: Smooth shows no Resolution", !(await page.getByRole("radiogroup", { name: "Resolution" }).count()));
const smoothPrice = await estimate.innerText().catch(() => "");
const smoothLine = (await editor.innerText()).match(/\d+\.\d s · 720p/)?.[0] ?? "";
check("prices · mixed: Smooth counts seconds at 720p", !!smoothLine, smoothLine);
diff --git a/tests/lora-fetch.test.ts b/tests/lora-fetch.test.ts
index 249ca53b..e4addb78 100644
--- a/tests/lora-fetch.test.ts
+++ b/tests/lora-fetch.test.ts
@@ -223,6 +223,28 @@ describe("Before a cloud run", () => {
expect(up.sent).toHaveLength(1);
});
+ it("copies a civitai file once when many frames ask for it at the same time (a per-frame render)", async () => {
+ setSetting("civitaiKey", KEY);
+ net = network(civitaiRoutes(Y2K_BODY));
+ const up = upload();
+ // Fuobe Mixed Media's cloud frames all start together, each with the look's LoRA.
+ const frames = await Promise.all(Array.from({ length: 24 }, (_, i) => prepareCloudLoras([{ ...y2k, strength: 0.5 + i / 100 }], "fal", up.fn)));
+ expect(up.sent).toEqual([{ name: "civitai-3422541-y2k.safetensors", size: Y2K_BODY.length }]);
+ expect(frames.map((f) => f![0].hostedUrl)).toEqual(Array(24).fill("https://v3.fal.media/files/civitai-3422541-y2k.safetensors"));
+ // Each frame keeps its own settings; civitai is asked once, and the file downloaded once.
+ expect(frames[3]![0].strength).toBe(0.53);
+ expect(net.calls.filter((c) => c.url.startsWith("https://civitai.com/api/v1/models/"))).toHaveLength(1);
+ expect(net.calls.filter((c) => c.url.includes("/api/download/") && c.method === "GET")).toHaveLength(1);
+ expect(listLoraCopies().filter((c) => c.target === "fal")).toHaveLength(1);
+ // A failed copy fails every frame that waited for it, and the next run tries again.
+ db().prepare("DELETE FROM lora_mirrors").run();
+ const failing = async (): Promise<string> => Promise.reject(new Error("fal storage is down"));
+ const tries = await Promise.allSettled(Array.from({ length: 3 }, () => prepareCloudLoras([y2k], "fal", failing)));
+ expect(tries.map((t) => t.status)).toEqual(["rejected", "rejected", "rejected"]);
+ expect((await prepareCloudLoras([y2k], "fal", up.fn))![0].hostedUrl).toBe("https://v3.fal.media/files/civitai-3422541-y2k.safetensors");
+ expect(up.sent).toHaveLength(2);
+ });
+
it("mirrors a civitai file whose hosting permission is gone, recording what civitai says (licences are information)", async () => {
setSetting("civitaiKey", KEY);
net = network(civitaiRoutes(Y2K_BODY, { permissions: ["Image", "RentCivit"] }));
diff --git a/tests/mixed-shorts-originals.test.ts b/tests/mixed-shorts-originals.test.ts
index 894c6000..6b687f84 100644
--- a/tests/mixed-shorts-originals.test.ts
+++ b/tests/mixed-shorts-originals.test.ts
@@ -14,7 +14,10 @@ process.env.FUOBE_DATA_DIR = dir;
process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here: open runs fall back to the demo
const { setSetting } = await import("@/server/settings");
-const { createGenerations, previewChained } = await import("@/server/generations");
+const { createGenerations, getGeneration, previewChained, previewGeneration } = await import("@/server/generations");
+const { saveFile } = await import("@/server/storage");
+const { estimateMixed } = await import("@/server/mixed-media");
+const { estimateShorts } = await import("@/server/shorts");
const { createPipeline } = await import("@/server/chains");
const { db } = await import("@/server/db");
const { falProvider } = await import("@/server/providers/fal");
@@ -90,6 +93,9 @@ describe("Fuobe Mixed Media and Fuobe Shorts in the catalog", () => {
// The cut is cropped to 9:16 / 16:9 first: fal's aspect_ratio is never asked for.
expect(view("fuobe-shorts", "cloud").routes[0].map?.aspectRatio).toBeUndefined();
expect(view("fuobe-shorts", "cloud").routes[0].map?.defaults).toEqual(shortsRecord.cloud.defaults);
+ // The weights' licence is the model's own data on both Originals (information for Settings → Models & licences).
+ expect(view("fuobe-shorts", "cloud").licence).toEqual(shortsRecord.licence);
+ expect(shortsRecord.licence).toMatchObject({ licence: "Apache-2.0", commercial: true });
});
it("are the studios' defaults, with the partners kept as choices", () => {
@@ -314,6 +320,15 @@ describe("Fuobe Shorts: segment → Qwen edit of frame 0 → Wan Fun VACE depth
expect(url).toContain("fal-ai/wan-22-vace-fun-a14b/depth");
expect(body).toMatchObject({ video_url: "https://x/cut.mp4", first_frame_url: "https://x/frame.png", match_input_num_frames: true, match_input_frames_per_second: true, resolution: "720p", seed: 7, temporal_downsample_factor: 1 });
expect(body.aspect_ratio).toBeUndefined();
+ // fal derives the depth from the RGB cut itself (preprocess, else video_url is read as a depth-map video), and the
+ // restyled frame goes only as the first frame: no VACE subject reference copy of it.
+ expect(body.preprocess).toBe(true);
+ expect(body.ref_image_urls).toBeUndefined();
+ expect(route.map?.fixed).toEqual(shortsRecord.cloud.fixed);
+ // Genjutsu's restyle runs the same endpoint, so it derives the depth too.
+ const restyle = view("fuobe-genjutsu-restyle", "cloud");
+ const r = await submit(restyle, restyle.routes[0], { prompt: "Anime.", video: "https://x/cut.mp4", images: ["https://x/frame.png"], resolution: "720p" });
+ expect(r.body).toMatchObject({ video_url: "https://x/cut.mp4", first_frame_url: "https://x/frame.png", preprocess: true });
const frame = view("fuobe-mixed-media", "cloud");
const sent = await submit(frame, frame.routes[0], {
prompt: "drkrm style, Noir.",
@@ -378,3 +393,163 @@ describe("DoP's Mixed Media effects run on Fuobe Mixed Media", () => {
expect(sketch.id).toBe("mixed-sketch");
});
});
+
+/** A PNG's first bytes: enough for its size (src/lib/image-size.ts), as a big photo's upload would start. */
+function pngHeader(width: number, height: number): Buffer {
+ const b = Buffer.alloc(33);
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(b, 0);
+ b.writeUInt32BE(13, 8);
+ b.write("IHDR", 12, "ascii");
+ b.writeUInt32BE(width, 16);
+ b.writeUInt32BE(height, 20);
+ b[24] = 8;
+ b[25] = 2;
+ return b;
+}
+
+/** What a step handed its provider (the demo provider records the input it was given). */
+async function handedOver(id: string): Promise<Record<string, unknown>> {
+ const end = Date.now() + 20_000;
+ while (Date.now() < end) {
+ const row = db().prepare("SELECT provider_input_json, status, error FROM generations WHERE id = ?").get(id) as { provider_input_json: string | null; status: string; error: string | null };
+ if (row.provider_input_json) return JSON.parse(row.provider_input_json);
+ if (row.status === "failed") throw new Error(row.error ?? "failed");
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ throw new Error(`${getGeneration(id)?.status}: nothing handed over`);
+}
+
+describe("DoP's Mixed Media stills, as the run reaches and prices them", () => {
+ it("leaves a civitai look LoRA out without the civitai key, and says so: the still runs on the look's words", () => {
+ setSetting("falKey", "test-key");
+ try {
+ const step = getPreset("effect-paper")!.prestep!.cloud;
+ expect(step.loras?.map((l) => l.file)).toEqual(["civitai-2959128-paperdiorama.safetensors"]);
+ expect(step.prompt).toMatch(/^layered paper diorama, cut paper art, /);
+ const ask = { feature: "effect", engine: "cloud" as const, modelId: step.modelId, op: step.op, prompt: step.prompt, loras: step.loras, params: step.params, inputs: { images: ["/api/files/uploads/a.png"] } };
+ const p = previewGeneration(ask);
+ expect(p).toMatchObject({ demo: false, engine: "cloud" });
+ expect(p.loras.applied).toEqual([]);
+ expect(p.loras.dropped).toEqual([{ file: "civitai-2959128-paperdiorama.safetensors", reason: expect.stringMatching(/civitai key/) }]);
+ expect(p.notes?.join(" ")).toMatch(/V67 Layered paper diorama downloads from civitai, which needs your free API key \(Settings → LoRAs\), so this run leaves it out/);
+ // Its trigger words go with it; the look's own words stay.
+ expect(p.prompt).not.toMatch(/layered paper diorama/);
+ expect(p.prompt).toBe(step.prompt.replace(/^layered paper diorama, cut paper art, /, ""));
+ // With the key it rides along, trigger and all.
+ setSetting("civitaiKey", "a-key");
+ const keyed = previewGeneration(ask);
+ expect(keyed.loras.applied.map((l) => l.file)).toEqual(["civitai-2959128-paperdiorama.safetensors"]);
+ expect(keyed.prompt).toBe(step.prompt);
+ } finally {
+ setSetting("falKey", "");
+ setSetting("civitaiKey", "");
+ }
+ });
+
+ it("draws the still at about 1 megapixel in the picture's shape on fal, as it's priced (not a 12-megapixel upload's own size)", async () => {
+ const photo = saveFile({ data: pngHeader(4000, 3000), contentType: "image/png", name: "big.png", source: "upload" }).url;
+ const [, still] = createGenerations({ feature: "effect", modelId: "fuobe-dop", presetId: "effect-noir", engine: "cloud", prompt: "a skater", inputs: { images: [photo] } });
+ expect(still).toMatchObject({ modelId: "fuobe-mixed-media", engine: "cloud", op: "edit" });
+ const sent = await handedOver(still.id);
+ const size = mm.originalFrameSize({ width: 4000, height: 3000 }, "1K")!;
+ expect(size).toEqual({ width: 1184, height: 880 });
+ expect(sent.extra).toEqual({ control_scale: 0.75, image_size: size });
+ // About 1 megapixel: the cent the composer shows before running.
+ expect(estimateCost(view("fuobe-mixed-media", "cloud"), { extra: { image_size: size } }, 1, "edit")).toBeCloseTo(0.01, 3);
+ expect(prestepCost(getPreset("effect-noir")!, "fuobe-dop", "cloud")).toBeCloseTo(0.01, 3);
+ });
+});
+
+describe("Refused before anything is paid for", () => {
+ it("fal's Wan 2.2 Fun VACE takes 17 frames or more, at 5 fps or more (as it works them)", () => {
+ expect(sh.originalSegmentProblem(1, 16)).toMatch(/needs at least 17 frames: select at least 1\.1 s of this 16 fps clip/);
+ expect(sh.originalSegmentProblem(1.07, 16)).toBeNull();
+ expect(sh.originalSegmentProblem(4, 4)).toMatch(/needs a clip of at least 5 fps \(this one is 4 fps\)/);
+ // A 60 fps clip is worked at 30 fps: 0.5 s is 15 frames there.
+ expect(sh.originalSegmentProblem(0.5, 60)).toMatch(/at least 17 frames/);
+ expect(sh.originalSegmentProblem(0.6, 60)).toBeNull();
+ // An unknown rate is left to the header read when the render starts.
+ expect(sh.originalSegmentProblem(0.2)).toBeNull();
+ });
+
+ it("Mixed Media's Smooth in the cloud and Fuobe Shorts in the cloud say so at the estimate; Per frame and your GPU don't need it", async () => {
+ const body = (over: Record<string, unknown>) => ({
+ engine: "cloud",
+ presetId: "mixed-noir",
+ values: {},
+ source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 12 },
+ range: { start: 0, end: 1 },
+ fps: 8,
+ resolution: "1K",
+ mode: "smooth",
+ ...over,
+ });
+ await expect(estimateMixed(body({}) as never)).rejects.toThrow(/needs at least 17 frames: select at least 1\.5 s of this 12 fps clip — or pick Per frame/);
+ await expect(estimateMixed(body({ source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 4 }, range: { start: 0, end: 6 }, fps: 4 }) as never)).rejects.toThrow(/at least 5 fps/);
+ expect(await estimateMixed(body({ range: { start: 0, end: 2 } }) as never)).toMatchObject({ mode: "smooth" });
+ expect(await estimateMixed(body({ mode: "frames" }) as never)).toMatchObject({ mode: "frames", frames: 6 });
+ expect(await estimateMixed(body({ engine: "open" }) as never)).toMatchObject({ mode: "smooth" });
+ const shorts = (over: Record<string, unknown>) => ({
+ engine: "cloud",
+ presetId: "shorts-claymation",
+ modelId: "fuobe-shorts",
+ source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 4 },
+ range: { start: 0, end: 6 },
+ aspectRatio: "9:16",
+ language: "auto",
+ ...over,
+ });
+ await expect(estimateShorts(shorts({}) as never)).rejects.toThrow(/Wan 2\.2 Fun VACE needs a clip of at least 5 fps .* — or pick another model/);
+ expect(await estimateShorts(shorts({ source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 24 } }) as never)).toMatchObject({ segments: 1 });
+ // A partner model has its own limits.
+ expect(await estimateShorts(shorts({ modelId: "gemini-omni-flash" }) as never)).toMatchObject({ segments: 1 });
+ });
+});
+
+describe("Fuobe Mixed Media on your GPU without a LoRA folder", () => {
+ type Reach = { ok: boolean; at: number; url: string };
+ const g = globalThis as unknown as { __fuobeComfyReach?: Reach };
+ const body = { engine: "open", presetId: "mixed-noir", values: {}, source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 24 }, range: { start: 0, end: 2 }, fps: 8, resolution: "1K", mode: "frames" };
+
+ /** A ComfyUI that answers, with these LoRA files. */
+ async function withComfy<T>(loras: string[], run: (asked: string[]) => Promise<T>): Promise<T> {
+ const real = globalThis.fetch;
+ const before = g.__fuobeComfyReach;
+ const asked: string[] = [];
+ g.__fuobeComfyReach = { ok: true, at: Date.now(), url: "http://127.0.0.1:9" };
+ globalThis.fetch = (async (url: string | URL | Request) => {
+ asked.push(String(url));
+ return String(url).endsWith("/models/loras") ? Response.json(loras) : new Response("{}", { status: 404 });
+ }) as typeof fetch;
+ try {
+ return await run(asked);
+ } finally {
+ globalThis.fetch = real;
+ g.__fuobeComfyReach = before;
+ }
+ }
+
+ it("runs a look whose LoRA ComfyUI hasn't on its words, and says how to add it, instead of failing once handed over", async () => {
+ const est = await withComfy(["other.safetensors"], async (asked) => {
+ const e = await estimateMixed(body as never);
+ expect(asked.filter((u) => u.endsWith("/models/loras"))).toHaveLength(1);
+ return e;
+ });
+ expect(est.notes.join(" ")).toMatch(/ComfyUI doesn't have frankbarbs DARKROOM Noir yet, and Fuobe downloads LoRAs for it only once Settings → LoRAs has its LoRA folder, so this run leaves it out \(the look runs on its words\)/);
+ // ComfyUI has it: it runs with it, nothing said.
+ const has = await withComfy(["darkroom-noir.safetensors"], () => estimateMixed(body as never));
+ expect(has.notes.join(" ")).not.toMatch(/ComfyUI doesn't have/);
+ // A LoRA folder set: Fuobe downloads it into the folder when the run is handed over, so ComfyUI isn't asked.
+ setSetting("comfyLorasDir", dir);
+ try {
+ const folder = await withComfy([], async (asked) => {
+ const e = await estimateMixed(body as never);
+ expect(asked.filter((u) => u.endsWith("/models/loras"))).toEqual([]);
+ return e;
+ });
+ expect(folder.notes.join(" ")).not.toMatch(/ComfyUI doesn't have/);
+ } finally {
+ setSetting("comfyLorasDir", "");
+ }
+ });
+});
diff --git a/tests/shorts-api.test.ts b/tests/shorts-api.test.ts
index 13d1fb4a..2f188917 100644
--- a/tests/shorts-api.test.ts
+++ b/tests/shorts-api.test.ts
@@ -591,7 +591,9 @@ describe("Mixed Media renders", () => {
expect(g.prompt).toMatch(/^drkrm style, /);
}
// Smooth: the first frame in the look (the Original), then Fuobe Shorts' Wan 2.2 Fun VACE pass; the cut's sound back.
- const smooth = await mixed.createMixed({ ...noir, mode: "smooth" } as never);
+ // fal's Wan 2.2 Fun VACE takes 17 frames or more: 1 s of this 16 fps clip is refused before anything is paid for.
+ await expect(mixed.createMixed({ ...noir, mode: "smooth" } as never)).rejects.toThrow(/needs at least 17 frames: select at least 1\.1 s .* or pick Per frame/);
+ const smooth = await mixed.createMixed({ ...noir, mode: "smooth", range: { start: 1, end: 3 } } as never);
const ops = smooth.items.map((g: Generation) => `${g.modelId} ${g.op}`).sort();
// The cut, its first frame, that frame in the look, Wan Fun VACE by depth, the selection's sound and the mux.
expect(ops).toEqual(["extract-frame frame", "fuobe-mixed-media edit", "fuobe-shorts v2v", "merge-audio-video mux", "trim-video trim", "trim-video trim"]);