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.

Image to 3D with turntables, an honest Virality predictor, av-tools tests

Claudecaf5491113ea
diff --git a/next.config.ts b/next.config.ts
index 9d0eae36..a5d69fba 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -12,6 +12,8 @@ const nextConfig: NextConfig = {
return [
{ source: "/characters", destination: "/elements", permanent: true },
{ source: "/characters/:id", destination: "/elements/:id", permanent: true },
+ // The Virality Predictor app became the /virality page (its frame step is the Hook Frame app).
+ { source: "/apps/app-virality-predictor", destination: "/virality", permanent: true },
// Studio hubs have one path per mode (src/lib/hubs.ts): old `?mode=` links, and a clip handed
// to Upscale or Audio without a mode, open that mode's own page (prerendered with the right studio).
...["audio", "video-tools", "upscale"].map((hub) => ({
diff --git a/src/app/(studio)/image-to-3d/page.tsx b/src/app/(studio)/image-to-3d/page.tsx
new file mode 100644
index 00000000..224ce284
--- /dev/null
+++ b/src/app/(studio)/image-to-3d/page.tsx
@@ -0,0 +1,12 @@
+import type { Metadata } from "next";
+import { Model3dStudio } from "@/components/model3d/model3d-studio";
+import { getModel } from "@/lib/catalog";
+import { MODELS_3D } from "@/lib/av/model3d";
+
+export const metadata: Metadata = { title: "Image to 3D" };
+
+/** The page passes the 3D models' names, so the client doesn't load the catalog. */
+export default function Page() {
+ const names = Object.fromEntries([...MODELS_3D.cloud, ...MODELS_3D.open].map((m) => [m.id, getModel(m.id)?.name ?? m.id]));
+ return <Model3dStudio names={names} />;
+}
diff --git a/src/app/(studio)/virality/page.tsx b/src/app/(studio)/virality/page.tsx
new file mode 100644
index 00000000..29b1d6e2
--- /dev/null
+++ b/src/app/(studio)/virality/page.tsx
@@ -0,0 +1,8 @@
+import type { Metadata } from "next";
+import { ViralityStudio } from "@/components/virality/virality-studio";
+
+export const metadata: Metadata = { title: "Virality predictor" };
+
+export default function Page() {
+ return <ViralityStudio />;
+}
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index 8ea7fba1..6262b9b6 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -38,6 +38,9 @@ import {
Library,
PersonStanding,
Scissors,
+ Box,
+ Swords,
+ TrendingUp,
type LucideIcon,
} from "lucide-react";
import {
@@ -119,6 +122,9 @@ const NAV: NavGroupDef[] = [
{ href: "/elements", label: "Elements", icon: AtSign },
{ href: "/upscale", label: "Upscale", icon: ZoomIn },
{ href: "/audio", label: "Audio", icon: AudioLines },
+ { href: "/katana", label: "Katana", icon: Swords },
+ { href: "/image-to-3d", label: "Image to 3D", icon: Box },
+ { href: "/virality", label: "Virality predictor", icon: TrendingUp },
],
collapsible: true,
},
diff --git a/src/components/av/media-drop.tsx b/src/components/av/media-drop.tsx
index b59eb97b..b8f10bdd 100644
--- a/src/components/av/media-drop.tsx
+++ b/src/components/av/media-drop.tsx
@@ -110,7 +110,7 @@ export function MediaDrop({
<Button variant="ghost" size="sm" className="rounded-full" onClick={() => input.current?.click()}>
<RefreshCw className="size-3.5" /> Replace
</Button>
- <Button variant="ghost" size="icon-sm" className="rounded-full" aria-label={`Remove ${title.toLowerCase()}`} onClick={() => onChange(null)}>
+ <Button variant="ghost" size="icon-sm" className="rounded-full" aria-label={`Remove ${kind === "video" ? "the video" : "the photo"}`} onClick={() => onChange(null)}>
<X className="size-4" />
</Button>
</div>
diff --git a/src/components/model3d/model3d-studio.tsx b/src/components/model3d/model3d-studio.tsx
new file mode 100644
index 00000000..f900f684
--- /dev/null
+++ b/src/components/model3d/model3d-studio.tsx
@@ -0,0 +1,219 @@
+"use client";
+
+import { Box, Clapperboard, Download, Loader2, Sparkles, Video } from "lucide-react";
+import Link from "next/link";
+import { createElement, useEffect, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Skeleton } from "@/components/ui/skeleton";
+import { FailedTile, PendingTile } from "@/components/studio/feed";
+import type { SlotValue } from "@/components/studio/media-slot";
+import { MediaDrop } from "@/components/av/media-drop";
+import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";
+import { uploadFile, useCreateGeneration, useEngine, useGenerations, useHydrated } from "@/lib/api";
+import { animateSpinHref, model3dRequest, model3dView, MODEL3D_FEATURE, MODELS_3D } from "@/lib/av/model3d";
+import type { Generation } from "@/lib/catalog/types";
+import { cn } from "@/lib/utils";
+import { recordableType, recordTurntable } from "./turntable";
+
+/** Image to 3D / Product spin: a product photo → a .glb to spin and download, a turntable video, and on to a video. */
+export function Model3dStudio({ names }: { names: Record<string, string> }) {
+ const [engine] = useEngine();
+ const create = useCreateGeneration();
+ const results = useGenerations({ features: [MODEL3D_FEATURE, "app:app-image-to-3d"], limit: 24 });
+ const [photo, setPhoto] = useState<SlotValue | null>(null);
+ const [picked, setPicked] = useState<Partial<Record<"cloud" | "open", string>>>({});
+ const modelId = picked[engine] ?? MODELS_3D[engine][0].id;
+ const blocker = !photo ? "Add a product photo" : photo.uploading ? "Uploading…" : null;
+ const go = () => {
+ if (blocker) return void toast(blocker, { id: "3d-blocker" });
+ create.mutate(model3dRequest({ engine, photo: photo!.ref, modelId }), {
+ onSuccess: () => toast.success("Building your 3D model"),
+ onError: (e) => toast.error((e as Error).message),
+ });
+ };
+ const items = results.data ?? [];
+ return (
+ <ToolShell title="Image to 3D">
+ <ToolHero title="Your product, in 3D" subtitle="One clear photo → a textured 3D model (.glb) you can spin, download, record as a turntable and turn into a video." />
+ <div className="mx-auto mt-8 grid max-w-[880px] gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
+ <MediaDrop kind="image" value={photo} onChange={setPhoto} title="Add a product photo" hint="One object, plain background, well lit" compact />
+ <Panel title="Model">
+ <div className="flex flex-col gap-1.5">
+ <Label htmlFor="m3d-model" className="sr-only">
+ Model
+ </Label>
+ <Select value={modelId} onValueChange={(v) => setPicked((p) => ({ ...p, [engine]: v }))}>
+ <SelectTrigger id="m3d-model" className="h-9 w-full rounded-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {MODELS_3D[engine].map((m) => (
+ <SelectItem key={m.id} value={m.id}>
+ {names[m.id] ?? m.id}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-[12px] text-muted-foreground">{MODELS_3D[engine].find((m) => m.id === modelId)?.note}</p>
+ </div>
+ <Button size="lg" className={cn("mt-4 w-full rounded-full", blocker && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={go} disabled={create.isPending}>
+ {create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Box className="size-4" />} Make it 3D
+ </Button>
+ <p className="mt-2 text-[12px] text-muted-foreground">
+ {engine === "open" ? "TRELLIS.2 also renders a turntable video on your GPU." : "Cloud models return the .glb; record a turntable right here in your browser."}
+ </p>
+ </Panel>
+ </div>
+ <section className="mx-auto mt-12 max-w-[880px]" aria-labelledby="models3d">
+ {(results.isLoading || items.length > 0) && (
+ <h3 id="models3d" className="mb-3 font-heading text-[22px]">
+ Your 3D models
+ </h3>
+ )}
+ {results.isLoading ? (
+ <div className="grid gap-3 sm:grid-cols-2">
+ <Skeleton className="aspect-[4/3] rounded-2xl" />
+ <Skeleton className="aspect-[4/3] rounded-2xl" />
+ </div>
+ ) : (
+ <div className="grid gap-3 sm:grid-cols-2">
+ {items.map((g) => (
+ <ResultCard key={g.id} g={g} />
+ ))}
+ </div>
+ )}
+ </section>
+ </ToolShell>
+ );
+}
+
+function ResultCard({ g }: { g: Generation }) {
+ const create = useCreateGeneration();
+ if (g.status === "queued" || g.status === "running") return <PendingTile g={g} ratio={4 / 3} />;
+ if (g.status !== "succeeded") return <FailedTile g={g} ratio={4 / 3} onRetry={() => create.mutate(g.request, { onError: (e) => toast.error((e as Error).message) })} />;
+ return <ModelCard g={g} />;
+}
+
+function ModelCard({ g }: { g: Generation }) {
+ const view = model3dView(g);
+ const [viewer, setViewer] = useState<HTMLElement | null>(null);
+ const [ready, setReady] = useState(false);
+ const [failed, setFailed] = useState(false);
+ const [recording, setRecording] = useState<number | null>(null);
+ const [recorded, setRecorded] = useState<{ url: string; saved?: string } | null>(null);
+ const hydrated = useHydrated();
+ const canRecord = hydrated && !!recordableType();
+ useEffect(() => {
+ let live = true;
+ import("@google/model-viewer").then(
+ () => live && setReady(true),
+ () => live && setFailed(true),
+ );
+ return () => {
+ live = false;
+ };
+ }, []);
+ useEffect(() => () => void (recorded && URL.revokeObjectURL(recorded.url)), [recorded]);
+ const record = async () => {
+ if (!viewer) return;
+ setRecording(0);
+ try {
+ const blob = await recordTurntable(viewer as Parameters<typeof recordTurntable>[0], { onProgress: setRecording });
+ const url = URL.createObjectURL(blob);
+ setRecorded({ url });
+ // Keep it in the Library (Uploads) so it can go on to Edit video.
+ const asset = await uploadFile(new File([blob], `${g.modelName ?? "model"} turntable.webm`, { type: "video/webm" }));
+ setRecorded({ url, saved: asset.url });
+ toast.success("Turntable recorded — saved to your uploads");
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setRecording(null);
+ }
+ };
+ const spin = animateSpinHref(view, recorded?.saved);
+ const name = (g.modelName ?? "model").replace(/[^\w .-]+/g, "");
+ return (
+ <article className="overflow-hidden rounded-2xl border bg-background shadow-soft">
+ <div className="relative aspect-[4/3] bg-[radial-gradient(circle_at_50%_40%,var(--muted),var(--background))]">
+ {failed ? (
+ <div className="grid size-full place-items-center p-6 text-center text-[13px] text-muted-foreground">Couldn&apos;t load the 3D viewer — download the .glb to open it.</div>
+ ) : !ready || !view.glb ? (
+ <div className="grid size-full place-items-center text-muted-foreground">
+ <Box className="size-8 animate-pulse" />
+ </div>
+ ) : (
+ createElement("model-viewer", {
+ ref: setViewer,
+ src: view.glb,
+ poster: view.poster,
+ alt: `3D model made with ${g.modelName ?? "a 3D model"}`,
+ "camera-controls": "",
+ "auto-rotate": "",
+ "shadow-intensity": "1",
+ exposure: "1",
+ "touch-action": "pan-y",
+ "interaction-prompt": "none",
+ style: { width: "100%", height: "100%", background: "transparent" },
+ })
+ )}
+ {recording !== null && (
+ <div className="absolute inset-x-3 bottom-3 rounded-full bg-background/90 px-3 py-1.5 text-[12px] font-medium shadow-soft" role="status">
+ Recording the turntable… {Math.round(recording * 100)}%
+ </div>
+ )}
+ {g.provider === "mock" && <span className="absolute top-3 left-3 rounded-full bg-highlight/40 px-2 py-0.5 text-[11px] font-medium">Demo</span>}
+ </div>
+ <div className="space-y-2 p-3">
+ <p className="truncate text-[13px] text-muted-foreground">{g.modelName}</p>
+ <div className="flex flex-wrap gap-1.5">
+ {view.glb && (
+ <Button asChild variant="outline" size="sm" className="rounded-full">
+ <a href={view.glb} download={`${name}.glb`}>
+ <Download className="size-3.5" /> .glb
+ </a>
+ </Button>
+ )}
+ {Object.entries(view.formats)
+ .filter(([k]) => k !== "glb")
+ .slice(0, 3)
+ .map(([k, url]) => (
+ <Button key={k} asChild variant="ghost" size="sm" className="rounded-full">
+ <a href={url} download>
+ .{k}
+ </a>
+ </Button>
+ ))}
+ {view.turntable ? (
+ <Button asChild variant="outline" size="sm" className="rounded-full">
+ <a href={view.turntable} download={`${name} turntable.mp4`}>
+ <Video className="size-3.5" /> Turntable
+ </a>
+ </Button>
+ ) : recorded ? (
+ <Button asChild variant="outline" size="sm" className="rounded-full">
+ <a href={recorded.url} download={`${name} turntable.webm`}>
+ <Video className="size-3.5" /> Turntable
+ </a>
+ </Button>
+ ) : (
+ <Button variant="outline" size="sm" className="rounded-full" onClick={record} disabled={!ready || !canRecord || recording !== null}>
+ <Clapperboard className="size-3.5" /> Record turntable
+ </Button>
+ )}
+ {spin && (
+ <Button asChild size="sm" className="rounded-full">
+ <Link href={spin} prefetch={false}>
+ <Sparkles className="size-3.5" /> Animate the spin
+ </Link>
+ </Button>
+ )}
+ </div>
+ {view.turntable && <video src={view.turntable} muted loop playsInline autoPlay className="hidden" aria-hidden />}
+ </div>
+ </article>
+ );
+}
diff --git a/src/components/model3d/turntable.ts b/src/components/model3d/turntable.ts
new file mode 100644
index 00000000..bdd80b16
--- /dev/null
+++ b/src/components/model3d/turntable.ts
@@ -0,0 +1,55 @@
+"use client";
+
+/**
+ * Record a turntable video of a <model-viewer> in the browser: one full turn of the camera around the
+ * model, captured from its canvas with MediaRecorder (WebM). For cloud 3D models that return only a .glb.
+ */
+
+/** The WebM codec the browser can record, or null. */
+export function recordableType(): string | null {
+ if (typeof MediaRecorder === "undefined") return null;
+ return ["video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm"].find((t) => MediaRecorder.isTypeSupported(t)) ?? null;
+}
+
+type ViewerElement = HTMLElement & { cameraOrbit: string; jumpCameraToGoal?: () => void; shadowRoot: ShadowRoot | null };
+
+/** Degrees per second of the recorded turn; a full turn takes 360 / TURN_SPEED seconds. */
+export const TURN_SPEED = 60;
+
+export async function recordTurntable(viewer: ViewerElement, o: { onProgress?: (p: number) => void; signal?: AbortSignal } = {}): Promise<Blob> {
+ const type = recordableType();
+ if (!type) throw new Error("This browser can't record video — download the .glb instead");
+ const canvas = viewer.shadowRoot?.querySelector("canvas");
+ if (!canvas || !("captureStream" in canvas)) throw new Error("The 3D viewer isn't ready yet");
+ const stream = (canvas as HTMLCanvasElement).captureStream(30);
+ const rec = new MediaRecorder(stream, { mimeType: type, videoBitsPerSecond: 6_000_000 });
+ const chunks: Blob[] = [];
+ rec.ondataavailable = (e) => e.data.size && chunks.push(e.data);
+ const stopped = new Promise<void>((resolve) => (rec.onstop = () => resolve()));
+ // Drive the camera ourselves: auto-rotate off, one turn at a steady speed.
+ const auto = viewer.hasAttribute("auto-rotate");
+ viewer.removeAttribute("auto-rotate");
+ const parts = (viewer.cameraOrbit || "0deg 75deg 105%").split(/\s+/);
+ const [, phi = "75deg", radius = "105%"] = parts;
+ const seconds = 360 / TURN_SPEED;
+ rec.start(250);
+ const t0 = performance.now();
+ await new Promise<void>((resolve) => {
+ const tick = () => {
+ const t = (performance.now() - t0) / 1000;
+ const done = t >= seconds || o.signal?.aborted;
+ viewer.cameraOrbit = `${Math.min(360, t * TURN_SPEED)}deg ${phi} ${radius}`;
+ viewer.jumpCameraToGoal?.();
+ o.onProgress?.(Math.min(1, t / seconds));
+ if (done) resolve();
+ else requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ });
+ rec.stop();
+ await stopped;
+ stream.getTracks().forEach((t) => t.stop());
+ if (auto) viewer.setAttribute("auto-rotate", "");
+ if (o.signal?.aborted) throw new Error("Stopped");
+ return new Blob(chunks, { type: "video/webm" });
+}
diff --git a/src/components/virality/measure.ts b/src/components/virality/measure.ts
new file mode 100644
index 00000000..1ffa5c77
--- /dev/null
+++ b/src/components/virality/measure.ts
@@ -0,0 +1,109 @@
+"use client";
+
+import { frameDiff, openVideo, releaseVideo, sampleFrames } from "@/components/av/frame-sampler";
+import { probeMedia } from "@/lib/media-probe";
+import { HOOK_SECONDS, hookTimes, LOUDNESS_STEP, loudnessSeries, lumaStats, MAX_AUDIO_BYTES, type AudioMeasure, type HookInput } from "@/lib/av/virality";
+
+/**
+ * Measure a video's hook in the browser: frames across the first 3 seconds (movement, the opening
+ * frame's contrast), faces and text where the browser has a detector (Chrome's Shape Detection API),
+ * and loudness from the decoded audio track. Nothing leaves the browser.
+ */
+export interface HookMeasure {
+ input: HookInput;
+ /** Small frames across the hook, for the timeline. */
+ strip: { t: number; url: string }[];
+ /** The first frame at up to 1280 px, for the Hook Frame app. */
+ opening: string | null;
+}
+
+type Detector = { detect(src: ImageData): Promise<unknown[]> };
+
+function detector(name: "FaceDetector" | "TextDetector"): Detector | null {
+ const C = (globalThis as unknown as Record<string, (new (o?: object) => Detector) | undefined>)[name];
+ if (typeof C !== "function") return null;
+ try {
+ return new C(name === "FaceDetector" ? { fastMode: true, maxDetectedFaces: 5 } : undefined);
+ } catch {
+ return null;
+ }
+}
+
+/** Run a detector on each frame; null when the browser has none or it refuses to run here. */
+async function detectAll<T>(d: Detector | null, frames: { t: number; data: ImageData }[], read: (found: unknown[]) => T): Promise<({ t: number } & T)[] | null> {
+ if (!d) return null;
+ const out: ({ t: number } & T)[] = [];
+ for (const f of frames) {
+ try {
+ out.push({ t: f.t, ...read(await d.detect(f.data)) });
+ } catch {
+ // Some platforms expose the class but can't run it (NotSupportedError): not measured.
+ return null;
+ }
+ }
+ return out;
+}
+
+function mono(buffer: AudioBuffer): Float32Array {
+ const out = new Float32Array(buffer.length);
+ for (let c = 0; c < buffer.numberOfChannels; c++) {
+ const ch = buffer.getChannelData(c);
+ for (let i = 0; i < ch.length; i++) out[i] += ch[i] / buffer.numberOfChannels;
+ }
+ return out;
+}
+
+async function measureLoudness(src: string, signal?: AbortSignal): Promise<AudioMeasure> {
+ try {
+ const res = await fetch(src, { signal });
+ if (!res.ok) return { error: "unreadable" };
+ if (Number(res.headers.get("content-length") ?? 0) > MAX_AUDIO_BYTES) {
+ void res.body?.cancel();
+ return { error: "too-large" };
+ }
+ const bytes = await res.arrayBuffer();
+ if (bytes.byteLength > MAX_AUDIO_BYTES) return { error: "too-large" };
+ // MP4/MOV say whether they carry sound; WebM and others are only known by trying to decode.
+ const info = probeMedia(new Uint8Array(bytes));
+ if (info?.hasVideo && !info.hasAudio) return { error: "no-audio" };
+ const ctx = new OfflineAudioContext(1, 1, 16000);
+ const audio = await ctx.decodeAudioData(bytes);
+ return { step: LOUDNESS_STEP, db: loudnessSeries(mono(audio), audio.sampleRate, LOUDNESS_STEP) };
+ } catch (e) {
+ if (signal?.aborted) throw e;
+ return { error: "unreadable" };
+ }
+}
+
+export async function measureHook(src: string, o: { signal?: AbortSignal; onProgress?: (share: number, stage: string) => void } = {}): Promise<HookMeasure> {
+ const step = (share: number, stage: string) => o.onProgress?.(share, stage);
+ step(0, "Opening the video");
+ const v = await openVideo(src);
+ try {
+ const duration = v.duration;
+ if (!Number.isFinite(duration) || duration <= 0) throw new Error("This video has no length the browser can read");
+ const times = hookTimes(duration);
+ step(0.05, "Reading the first 3 seconds");
+ const frames = await sampleFrames(v, times, { width: 120, jpeg: true, signal: o.signal, onProgress: (d) => step(0.05 + d * 0.5, "Reading the first 3 seconds") });
+ if (o.signal?.aborted) throw new DOMException("Stopped", "AbortError");
+ const motion = frames.map((f, i) => ({ t: f.t, diff: i ? frameDiff(frames[i - 1].data, f.data) : 0 }));
+ // Larger frames for the detectors and the opening frame: 0, 1 and 2 s.
+ step(0.6, "Looking for faces and text");
+ const checkTimes = [0, 1, 2].filter((t) => t < Math.min(HOOK_SECONDS, duration));
+ const width = Math.min(1280, v.videoWidth || 1280);
+ const big = await sampleFrames(v, checkTimes, { width, jpeg: true, signal: o.signal });
+ if (o.signal?.aborted) throw new DOMException("Stopped", "AbortError");
+ const faces = await detectAll(detector("FaceDetector"), big, (found) => ({ count: found.length }));
+ const text = await detectAll(detector("TextDetector"), big, (found) => ({ chars: found.reduce<number>((n, b) => n + String((b as { rawValue?: string }).rawValue ?? "").trim().length, 0) }));
+ step(0.8, "Measuring the sound");
+ const loudness = await measureLoudness(src, o.signal);
+ step(1, "Done");
+ return {
+ input: { duration, width: v.videoWidth, height: v.videoHeight, motion, opening: lumaStats(frames[0].data), faces, text, loudness },
+ strip: frames.filter((_, i) => i % 2 === 0).map((f) => ({ t: f.t, url: f.url! })),
+ opening: big[0]?.url ?? null,
+ };
+ } finally {
+ releaseVideo(v);
+ }
+}
diff --git a/src/components/virality/virality-studio.tsx b/src/components/virality/virality-studio.tsx
new file mode 100644
index 00000000..02c37a5f
--- /dev/null
+++ b/src/components/virality/virality-studio.tsx
@@ -0,0 +1,272 @@
+"use client";
+
+import { AudioLines, Contrast, Crop, Info, Loader2, Move, RefreshCw, ScanFace, Scissors, Smartphone, Sparkles, Subtitles, TrendingUp, Type, Volume2 } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useEffect, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Progress } from "@/components/ui/progress";
+import type { SlotValue } from "@/components/studio/media-slot";
+import { MediaDrop } from "@/components/av/media-drop";
+import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";
+import { uploadFile, useEngine } from "@/lib/api";
+import { HOOK_SECONDS, hookSignals, hookSummary, SILENCE_DB, VIRALITY_PARITY, type HookSignal, type SignalId, type Verdict } from "@/lib/av/virality";
+import { cn } from "@/lib/utils";
+import { measureHook, type HookMeasure } from "./measure";
+
+type Run =
+ | { ref: string; status: "running"; share: number; stage: string }
+ | { ref: string; status: "done"; measure: HookMeasure; signals: HookSignal[] }
+ | { ref: string; status: "error"; message: string };
+
+const HOOK_FRAME_APP = "/apps/app-hook-frame";
+
+/** Virality predictor: an honest, in-browser check of a video's first 3 seconds — no invented score. */
+export function ViralityStudio() {
+ const [clip, setClip] = useState<SlotValue | null>(null);
+ const [run, setRun] = useState<Run | null>(null);
+ const abort = useRef<AbortController | null>(null);
+ useEffect(() => () => abort.current?.abort(), []);
+ // A result belongs to the clip it was measured on.
+ const current = run && clip && run.ref === clip.ref ? run : null;
+ const change = (v: SlotValue | null) => {
+ abort.current?.abort();
+ setClip(v);
+ };
+ const go = async () => {
+ if (!clip) return void toast("Add a video first", { id: "virality-blocker" });
+ if (clip.uploading || !clip.ref) return void toast("Uploading…", { id: "virality-blocker" });
+ abort.current?.abort();
+ const ctrl = new AbortController();
+ abort.current = ctrl;
+ const ref = clip.ref;
+ setRun({ ref, status: "running", share: 0, stage: "Opening the video" });
+ try {
+ const measure = await measureHook(ref, { signal: ctrl.signal, onProgress: (share, stage) => !ctrl.signal.aborted && setRun({ ref, status: "running", share, stage }) });
+ if (!ctrl.signal.aborted) setRun({ ref, status: "done", measure, signals: hookSignals(measure.input) });
+ } catch (e) {
+ if (!ctrl.signal.aborted) setRun({ ref, status: "error", message: (e as Error).message || "Couldn't read this video" });
+ }
+ };
+ return (
+ <ToolShell title="Virality predictor" engineSwitch={false}>
+ <ToolHero title="Will your first 3 seconds hold?" subtitle="An honest check of your video's hook — movement, a cut, faces, on-screen text and sound in the opening seconds, measured right here in your browser. Nothing is generated or charged." />
+ <div className="mx-auto mt-8 grid max-w-[880px] gap-3">
+ <MediaDrop kind="video" value={clip} onChange={change} title="Add your video" hint="MP4 (H.264) or WebM · the opening 3 seconds are what's checked" compact />
+ <div className="flex flex-wrap items-center gap-2">
+ <Button size="lg" className={cn("rounded-full", (!clip || clip.uploading) && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={go} disabled={current?.status === "running"}>
+ {current?.status === "running" ? <Loader2 className="size-4 animate-spin" /> : current?.status === "done" ? <RefreshCw className="size-4" /> : <TrendingUp className="size-4" />}
+ {current?.status === "done" ? "Check again" : "Check the hook"}
+ </Button>
+ <p className="text-[12px] text-muted-foreground">Runs in your browser · works on both engines and in demo mode</p>
+ </div>
+ {current?.status === "running" && (
+ <div className="rounded-2xl border bg-background p-3 shadow-soft" role="status" aria-live="polite">
+ <div className="mb-2 flex items-center justify-between text-[13px]">
+ <span>{current.stage}…</span>
+ <span className="font-mono text-[12px] text-muted-foreground">{Math.round(current.share * 100)}%</span>
+ </div>
+ <Progress value={current.share * 100} aria-label="Analysis progress" />
+ </div>
+ )}
+ {current?.status === "error" && (
+ <div className="rounded-2xl border border-destructive/40 bg-background p-3 text-[13px]" role="alert">
+ <p className="font-medium text-destructive">Couldn&apos;t analyse this video</p>
+ <p className="mt-1 text-muted-foreground">{current.message}</p>
+ </div>
+ )}
+ {current?.status === "done" && <Results clip={clip!} measure={current.measure} signals={current.signals} />}
+ <ParityNote />
+ </div>
+ </ToolShell>
+ );
+}
+
+function ParityNote() {
+ const [engine] = useEngine();
+ return (
+ <aside className="rounded-2xl border bg-muted/40 p-3 text-[13px] sm:p-4" aria-labelledby="virality-parity">
+ <div className="flex items-start gap-2.5">
+ <Info className="mt-0.5 size-4 shrink-0 text-muted-foreground" aria-hidden />
+ <div className="min-w-0 space-y-1.5">
+ <p id="virality-parity" className="font-medium">
+ {VIRALITY_PARITY.title}
+ </p>
+ <p className="text-pretty text-muted-foreground">{VIRALITY_PARITY.body}</p>
+ <p className="text-pretty text-muted-foreground">{engine === "open" ? VIRALITY_PARITY.open : VIRALITY_PARITY.cloud}</p>
+ </div>
+ </div>
+ </aside>
+ );
+}
+
+const VERDICT: Record<Verdict, { label: string; dot: string; chip: string }> = {
+ strong: { label: "Strong", dot: "bg-success", chip: "bg-success/15 text-foreground" },
+ ok: { label: "Fine", dot: "bg-brand-text", chip: "bg-brand-faint text-brand-text" },
+ weak: { label: "Improve", dot: "bg-warning", chip: "bg-warning/20 text-foreground" },
+ unknown: { label: "Not measured", dot: "bg-subtle-foreground", chip: "bg-muted text-muted-foreground" },
+};
+
+const ICON: Record<SignalId, React.ComponentType<{ className?: string }>> = {
+ motion: Move,
+ change: Scissors,
+ faces: ScanFace,
+ text: Type,
+ sound: Volume2,
+ contrast: Contrast,
+ format: Smartphone,
+};
+
+function Results({ clip, measure, signals }: { clip: SlotValue; measure: HookMeasure; signals: HookSignal[] }) {
+ const counts = hookSummary(signals);
+ const byId = Object.fromEntries(signals.map((s) => [s.id, s])) as Record<SignalId, HookSignal>;
+ return (
+ <div className="grid gap-3">
+ <Panel title="Hook check" aside={<span className="text-[12px] text-muted-foreground">First {HOOK_SECONDS} s · rules of thumb</span>}>
+ <ul className="flex flex-wrap gap-1.5" aria-label="Summary">
+ {(["strong", "ok", "weak", "unknown"] as Verdict[])
+ .filter((v) => counts[v] > 0)
+ .map((v) => (
+ <li key={v} className={cn("inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[12px] font-medium", VERDICT[v].chip)}>
+ <span className={cn("size-1.5 rounded-full", VERDICT[v].dot)} aria-hidden />
+ {counts[v]} {VERDICT[v].label.toLowerCase()}
+ </li>
+ ))}
+ </ul>
+ <p className="mt-2 text-[13px] text-muted-foreground">
+ {counts.weak === 0 ? "Nothing in the opening flags a slow start." : `${counts.weak} thing${counts.weak > 1 ? "s" : ""} to look at in the opening.`} These are measurements, not a forecast of views.
+ </p>
+ <Timeline measure={measure} />
+ </Panel>
+ <Panel title="Signals">
+ <ul className="divide-y">
+ {signals.map((s) => {
+ const Icon = ICON[s.id];
+ return (
+ <li key={s.id} className="flex min-w-0 gap-3 py-2.5 first:pt-0 last:pb-0">
+ <span className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-xl bg-muted text-muted-foreground">
+ <Icon className="size-4" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
+ <span className="text-[14px] font-medium">{s.label}</span>
+ <span className={cn("rounded-full px-2 py-0.5 text-[11px] font-medium", VERDICT[s.verdict].chip)}>{VERDICT[s.verdict].label}</span>
+ </div>
+ <p className="mt-0.5 text-[13px] break-words">{s.detail}</p>
+ {s.tip && <p className="mt-0.5 text-[12px] text-pretty text-muted-foreground">{s.tip}</p>}
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ </Panel>
+ <NextSteps clip={clip} measure={measure} byId={byId} />
+ </div>
+ );
+}
+
+/** The opening frames over two strips: movement between frames and loudness, with the 3 s mark. */
+function Timeline({ measure }: { measure: HookMeasure }) {
+ const { motion, loudness } = measure.input;
+ const span = Math.max(HOOK_SECONDS, motion.at(-1)?.t ?? 0) || HOOK_SECONDS;
+ const peak = Math.max(0.05, ...motion.map((m) => m.diff));
+ const db = "db" in loudness ? loudness.db.slice(0, Math.round(HOOK_SECONDS / loudness.step)) : null;
+ const moving = motion.filter((m) => m.diff >= 0.01).length;
+ const loudCount = db?.filter((d) => d > SILENCE_DB).length ?? 0;
+ // The clip's own shape, kept between 3:4 and 16:9 so a vertical strip doesn't tower.
+ const frameRatio = Math.min(16 / 9, Math.max(3 / 4, measure.input.width / Math.max(1, measure.input.height) || 16 / 9));
+ return (
+ <figure className="mt-4" aria-label={`Timeline of the first ${HOOK_SECONDS} seconds: movement in ${moving} of ${motion.length} frames${db ? `, sound in ${loudCount} of ${db.length} tenths of a second` : ""}`}>
+ <div className="grid gap-1" style={{ gridTemplateColumns: `repeat(${measure.strip.length}, minmax(0, 1fr))` }}>
+ {measure.strip.map((f) => (
+ <div key={f.t} className="min-w-0">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={f.url} alt="" className="w-full rounded-md bg-media object-cover" style={{ aspectRatio: frameRatio }} />
+ <p className="mt-0.5 text-center font-mono text-[10px] text-muted-foreground">{f.t.toFixed(1)}s</p>
+ </div>
+ ))}
+ </div>
+ <div className="mt-3 grid grid-cols-[64px_minmax(0,1fr)] items-end gap-x-2 gap-y-2 text-[11px] text-muted-foreground">
+ <span className="flex items-center gap-1">
+ <Move className="size-3" aria-hidden /> Movement
+ </span>
+ <div className="flex h-8 items-end gap-px" aria-hidden>
+ {motion.map((m) => (
+ <span key={m.t} className="min-w-0 flex-1 rounded-sm bg-brand-text/70" style={{ height: `${Math.max(4, (m.diff / peak) * 100)}%`, opacity: m.t <= span ? 1 : 0.4 }} />
+ ))}
+ </div>
+ <span className="flex items-center gap-1">
+ <AudioLines className="size-3" aria-hidden /> Sound
+ </span>
+ {db ? (
+ <div className="flex h-8 items-end gap-px" aria-hidden>
+ {db.map((d, i) => (
+ <span key={i} className={cn("min-w-0 flex-1 rounded-sm", d > SILENCE_DB ? "bg-foreground/60" : "bg-muted")} style={{ height: `${Math.max(4, Math.min(100, ((d + 60) / 60) * 100))}%` }} />
+ ))}
+ </div>
+ ) : (
+ <p className="h-8 content-center">{"error" in loudness && loudness.error === "no-audio" ? "No audio track" : "Not measured"}</p>
+ )}
+ </div>
+ </figure>
+ );
+}
+
+function NextSteps({ clip, measure, byId }: { clip: SlotValue; measure: HookMeasure; byId: Record<SignalId, HookSignal> }) {
+ const router = useRouter();
+ const [busy, setBusy] = useState(false);
+ const toHookFrame = async () => {
+ if (!measure.opening) return;
+ setBusy(true);
+ try {
+ const blob = await (await fetch(measure.opening)).blob();
+ const asset = await uploadFile(new File([blob], `${(clip.name ?? "video").replace(/\.[^.]+$/, "")} opening frame.jpg`, { type: "image/jpeg" }));
+ router.push(`${HOOK_FRAME_APP}?${new URLSearchParams({ image: asset.url })}`);
+ } catch (e) {
+ toast.error((e as Error).message);
+ setBusy(false);
+ }
+ };
+ const weak = (id: SignalId) => byId[id]?.verdict === "weak";
+ const video = new URLSearchParams({ video: clip.ref }).toString();
+ return (
+ <Panel title="Next steps">
+ <div className="flex flex-wrap gap-2">
+ {measure.opening && (
+ <Button className="rounded-full" onClick={toHookFrame} disabled={busy}>
+ {busy ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />} Make a stronger opening frame
+ </Button>
+ )}
+ {(weak("text") || byId.text?.verdict === "unknown") && (
+ <Button asChild variant="outline" className="rounded-full">
+ <Link href="/video-tools/captions" prefetch={false}>
+ <Subtitles className="size-4" /> Add captions
+ </Link>
+ </Button>
+ )}
+ {weak("sound") && (
+ <Button asChild variant="outline" className="rounded-full">
+ <Link href={`/audio/video?${video}`} prefetch={false}>
+ <Volume2 className="size-4" /> Add sound
+ </Link>
+ </Button>
+ )}
+ {measure.input.height > 0 && measure.input.width / measure.input.height > 0.66 && (
+ <Button asChild variant="outline" className="rounded-full">
+ <Link href={`/reframe?${video}`} prefetch={false}>
+ <Crop className="size-4" /> Reframe to 9:16
+ </Link>
+ </Button>
+ )}
+ {(weak("motion") || weak("change")) && (
+ <Button asChild variant="outline" className="rounded-full">
+ <Link href="/video-tools/trim" prefetch={false}>
+ <Scissors className="size-4" /> Trim the slow start
+ </Link>
+ </Button>
+ )}
+ </div>
+ </Panel>
+ );
+}
diff --git a/src/lib/av/model3d.ts b/src/lib/av/model3d.ts
new file mode 100644
index 00000000..5104e6cf
--- /dev/null
+++ b/src/lib/av/model3d.ts
@@ -0,0 +1,66 @@
+import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
+
+/**
+ * Image to 3D / Product spin: which model, and what a finished job gives the viewer — the .glb, a
+ * turntable video (TRELLIS.2 renders one; for models that return only a mesh the page records one in
+ * the browser), a poster, the source photo — and where "Animate the spin" goes next.
+ */
+export const MODEL3D_FEATURE = "image-to-3d";
+
+export const MODELS_3D: Record<Engine, { id: string; note: string }[]> = {
+ cloud: [
+ { id: "hunyuan-3d-3-1-pro", note: "Textured, game-ready · ≈ $0.38" },
+ { id: "hunyuan-3d-3-1-rapid", note: "Faster single view · ≈ $0.23" },
+ { id: "trellis-2", note: "Detailed geometry · ≈ $0.30" },
+ { id: "tripo-h3-1", note: "Clean topology, PBR · ≈ $0.30" },
+ { id: "meshy-7-1", note: "Textured, optional rigging · ≈ $1.20" },
+ ],
+ open: [
+ { id: "oss-trellis2", note: "Textured GLB + turntable video · 16 GB GPU · MIT" },
+ { id: "oss-hunyuan3d-21", note: "Shape only · 10 GB GPU" },
+ ],
+};
+
+export function model3dRequest(o: { engine: Engine; photo: string; modelId?: string }): GenerationRequest {
+ const id = o.modelId && MODELS_3D[o.engine].some((m) => m.id === o.modelId) ? o.modelId : MODELS_3D[o.engine][0].id;
+ return { feature: MODEL3D_FEATURE, modelId: id, op: "image-to-3d", inputs: { images: [o.photo] } };
+}
+
+export interface Model3dView {
+ glb?: string;
+ /** A rendered turntable that came with the model (TRELLIS.2 open, demo). */
+ turntable?: string;
+ poster?: string;
+ /** The product photo it was made from. */
+ photo?: string;
+ /** Other formats the provider returned (OBJ, FBX, USDZ…), by extension. */
+ formats: Record<string, string>;
+}
+
+export function model3dView(g: Pick<Generation, "outputs" | "request">): Model3dView {
+ const mesh = g.outputs.find((o) => o.kind === "model3d");
+ const meta = (mesh?.meta ?? {}) as Record<string, unknown>;
+ const str = (v: unknown) => (typeof v === "string" && v ? v : undefined);
+ const videos = g.outputs.filter((o) => o.kind === "video");
+ const video = videos.find((o) => o.meta?.role === "turntable" || o.meta?.turntable) ?? videos[0];
+ const formats: Record<string, string> = {};
+ const listed = meta.formats;
+ if (listed && typeof listed === "object") for (const [k, v] of Object.entries(listed as Record<string, unknown>)) if (typeof v === "string") formats[k.toLowerCase()] = v;
+ return {
+ glb: mesh?.url,
+ turntable: str(meta.turntable) ?? str(meta.video) ?? video?.url,
+ poster: str(meta.preview) ?? str(meta.poster) ?? g.outputs.find((o) => o.kind === "image")?.url,
+ photo: g.request.inputs?.images?.[0],
+ formats,
+ };
+}
+
+const SPIN_PROMPT = "The product rotates slowly 360 degrees on a turntable in a clean studio, soft key light sweeping across it, the design and label stay exactly the same";
+
+/** "Animate the spin": restyle the turntable into a finished shot (Edit video), or animate the photo (Video). */
+export function animateSpinHref(v: Model3dView, turntable?: string): string | null {
+ const clip = turntable ?? v.turntable;
+ if (clip) return `/video-edit?${new URLSearchParams({ video: clip, prompt: "Turn this product turntable into a premium commercial shot: studio lighting, soft reflections, a clean seamless backdrop; keep the product and its rotation exactly" })}`;
+ if (v.photo) return `/video?${new URLSearchParams({ image: v.photo, prompt: SPIN_PROMPT })}`;
+ return null;
+}
diff --git a/src/lib/av/virality.ts b/src/lib/av/virality.ts
new file mode 100644
index 00000000..68fc8940
--- /dev/null
+++ b/src/lib/av/virality.ts
@@ -0,0 +1,217 @@
+/**
+ * Virality predictor, honestly: Higgsfield's predictor scores a video with Meta's TRIBE v2 (a brain-response
+ * model, CC BY-NC — non-commercial only) and no provider hosts it. Fuobe doesn't invent a score. It
+ * measures the hook — the first 3 seconds — in the browser (movement, a cut, faces, on-screen text,
+ * sound, the opening frame's contrast, the format) and holds each measurement against a plain rule of
+ * thumb. Every signal says what was measured and why it matters; nothing here is a prediction.
+ *
+ * This module is the pure part: the measurements in, the signals out. The browser side that takes the
+ * measurements is src/components/virality/measure.ts.
+ */
+
+/** The hook: what a viewer sees before deciding to keep watching. */
+export const HOOK_SECONDS = 3;
+/** Frames sampled across the hook, this far apart. */
+export const HOOK_STEP = 0.25;
+/** Loudness windows, seconds. */
+export const LOUDNESS_STEP = 0.1;
+/** Larger files aren't decoded for loudness in the browser (the whole track would sit in memory). */
+export const MAX_AUDIO_BYTES = 150 * 1024 * 1024;
+/** Quieter than this (dBFS RMS) counts as silence. */
+export const SILENCE_DB = -45;
+
+export const VIRALITY_PARITY = {
+ title: "A heuristic hook check, not a prediction",
+ body: "Higgsfield's Virality Predictor scores videos with Meta's TRIBE v2, a brain-response model released for non-commercial use only (CC BY-NC 4.0). No cloud provider hosts it, so Fuobe shows no virality score. This page measures your first 3 seconds in your browser and holds them against common rules of thumb — useful for spotting a slow opening, not a forecast of views.",
+ cloud: "Cloud: no hosted TRIBE v2 model exists to call.",
+ open: "Open engine: TRIBE v2 can run on your own GPU as an optional, non-commercial worker; Fuobe doesn't bundle it.",
+};
+
+export type Verdict = "strong" | "ok" | "weak" | "unknown";
+
+export type SignalId = "motion" | "change" | "faces" | "text" | "sound" | "contrast" | "format";
+
+export interface HookSignal {
+ id: SignalId;
+ label: string;
+ verdict: Verdict;
+ /** What was measured, in words. */
+ detail: string;
+ /** What to try when it's weak (or why it couldn't be measured). */
+ tip?: string;
+ /** When it happens, seconds from the start. */
+ at?: number;
+}
+
+export type AudioMeasure = { step: number; db: number[] } | { error: "no-audio" | "unreadable" | "too-large" };
+
+export interface HookInput {
+ duration: number;
+ width: number;
+ height: number;
+ /** Frames across the hook: time and mean luma difference from the previous sample (the first is 0). */
+ motion: { t: number; diff: number }[];
+ /** The first frame: luma standard deviation and mean, 0–1. */
+ opening: { contrast: number; brightness: number };
+ /** Faces found per checked frame; null when the browser has no face detector. */
+ faces: { t: number; count: number }[] | null;
+ /** Characters of text found per checked frame; null when the browser has no text detector. */
+ text: { t: number; chars: number }[] | null;
+ /** Loudness (dBFS RMS) per `step` seconds from 0, or why it couldn't be read. */
+ loudness: AudioMeasure;
+}
+
+// Rules of thumb (not calibrated against outcomes — they flag a still, silent or flat opening).
+const MOTION_STRONG = 0.03;
+const MOTION_OK = 0.01;
+const CUT = 0.12;
+const CONTRAST_STRONG = 0.2;
+const CONTRAST_OK = 0.12;
+const DARK = 0.12;
+
+const r1 = (n: number) => Math.round(n * 10) / 10;
+const dbfs = (n: number) => `${Math.round(n)}`.replace("-", "\u2212") + " dBFS";
+const NO_DETECTOR = "Chrome's Shape Detection API adds one (chrome://flags › Experimental Web Platform features)";
+const secs = (t: number) => `${r1(t).toFixed(1)} s`;
+
+/** Luma mean and standard deviation (0–1) of an RGBA frame. */
+export function lumaStats(frame: { data: ArrayLike<number> }): { brightness: number; contrast: number } {
+ const d = frame.data;
+ const n = Math.floor(d.length / 4);
+ if (!n) return { brightness: 0, contrast: 0 };
+ let sum = 0;
+ let sq = 0;
+ for (let i = 0; i < n * 4; i += 4) {
+ const l = (d[i] * 0.299 + d[i + 1] * 0.587 + d[i + 2] * 0.114) / 255;
+ sum += l;
+ sq += l * l;
+ }
+ const mean = sum / n;
+ return { brightness: mean, contrast: Math.sqrt(Math.max(0, sq / n - mean * mean)) };
+}
+
+/** RMS loudness in dBFS per `step` seconds of a mono signal (−100 for digital silence). */
+export function loudnessSeries(samples: ArrayLike<number>, sampleRate: number, step = LOUDNESS_STEP): number[] {
+ const size = Math.max(1, Math.round(sampleRate * step));
+ const out: number[] = [];
+ for (let start = 0; start < samples.length; start += size) {
+ const end = Math.min(samples.length, start + size);
+ let sq = 0;
+ for (let i = start; i < end; i++) sq += samples[i] * samples[i];
+ const rms = Math.sqrt(sq / Math.max(1, end - start));
+ out.push(rms > 1e-5 ? Math.max(-100, 20 * Math.log10(rms)) : -100);
+ }
+ return out;
+}
+
+/** The power average of dB values (what a meter shows for the span), or null for none. */
+export function meanDb(db: number[]): number | null {
+ if (!db.length) return null;
+ const p = db.reduce((s, d) => s + 10 ** (d / 10), 0) / db.length;
+ return p > 0 ? Math.max(-100, 10 * Math.log10(p)) : -100;
+}
+
+/** Sample times across the hook (and no further than the clip). */
+export function hookTimes(duration: number, step = HOOK_STEP): number[] {
+ const end = Math.min(HOOK_SECONDS, Math.max(0, duration - 0.05));
+ const out: number[] = [];
+ for (let t = 0; t <= end + 1e-6; t += step) out.push(Math.round(t * 100) / 100);
+ return out.length ? out : [0];
+}
+
+function motionSignal(m: HookInput["motion"]): HookSignal {
+ const label = "Movement in the first second";
+ const first = m.filter((f) => f.t > 0 && f.t <= 1.0001);
+ if (!first.length) return { id: "motion", label, verdict: "unknown", detail: "The clip is too short to tell", tip: "Hooks need at least a second" };
+ const peak = Math.max(...first.map((f) => f.diff));
+ const at = first.find((f) => f.diff === peak)!.t;
+ if (peak >= MOTION_STRONG) return { id: "motion", label, verdict: "strong", detail: `Clear movement by ${secs(at)}`, at };
+ if (peak >= MOTION_OK) return { id: "motion", label, verdict: "ok", detail: "Some movement, but subtle", tip: "Open on the action — a gesture, a reveal or a fast push-in reads as “something is happening”" };
+ return { id: "motion", label, verdict: "weak", detail: "The first second is nearly still", tip: "Cut the slow start: begin on movement, or trim the first beat" };
+}
+
+function changeSignal(m: HookInput["motion"]): HookSignal {
+ const label = "A change within 3 seconds";
+ const hook = m.filter((f) => f.t > 0 && f.t <= HOOK_SECONDS + 1e-4);
+ if (!hook.length) return { id: "change", label, verdict: "unknown", detail: "The clip is too short to tell" };
+ const peak = Math.max(...hook.map((f) => f.diff));
+ const at = hook.find((f) => f.diff === peak)!.t;
+ if (peak >= CUT) return { id: "change", label, verdict: "strong", detail: `A cut or big change at ${secs(at)}`, at };
+ const mean = hook.reduce((s, f) => s + f.diff, 0) / hook.length;
+ if (mean >= MOTION_OK) return { id: "change", label, verdict: "ok", detail: "Continuous movement, no cut", tip: "A cut, zoom or new angle before 3 s resets attention" };
+ return { id: "change", label, verdict: "weak", detail: "The picture barely changes in 3 s", tip: "Add a cut, a zoom or a new angle before the 3-second mark" };
+}
+
+function facesSignal(f: HookInput["faces"]): HookSignal {
+ const label = "A face early";
+ if (!f) return { id: "faces", label, verdict: "unknown", detail: "This browser has no face detector", tip: NO_DETECTOR };
+ const seen = f.filter((x) => x.count > 0).sort((a, b) => a.t - b.t)[0];
+ if (!seen) return { id: "faces", label, verdict: "weak", detail: "No face found in the first 3 s", tip: "For person-led videos, open on a face looking into the lens — feeds stop for faces" };
+ const most = Math.max(...f.map((x) => x.count));
+ const who = most > 1 ? `${most} faces` : "A face";
+ return seen.t <= 1 ? { id: "faces", label, verdict: "strong", detail: `${who} from ${secs(seen.t)}`, at: seen.t } : { id: "faces", label, verdict: "ok", detail: `${who} from ${secs(seen.t)}`, tip: "Bring the face into the first second", at: seen.t };
+}
+
+function textSignal(f: HookInput["text"]): HookSignal {
+ const label = "On-screen text";
+ if (!f) return { id: "text", label, verdict: "unknown", detail: "This browser has no text detector", tip: NO_DETECTOR };
+ const seen = f.filter((x) => x.chars >= 3).sort((a, b) => a.t - b.t)[0];
+ if (!seen) return { id: "text", label, verdict: "weak", detail: "No text found in the first 3 s", tip: "Many people watch muted: a short title or captions say what's coming" };
+ return seen.t <= 1 ? { id: "text", label, verdict: "strong", detail: `Text on screen from ${secs(seen.t)}`, at: seen.t } : { id: "text", label, verdict: "ok", detail: `Text appears at ${secs(seen.t)}`, tip: "Put the title up from the first frame", at: seen.t };
+}
+
+function soundSignal(a: AudioMeasure): HookSignal {
+ const label = "Sound from the start";
+ if ("error" in a) {
+ if (a.error === "no-audio") return { id: "sound", label, verdict: "weak", detail: "No audio track", tip: "Add a voice, music or a sound effect — Sound effects and Music can make one" };
+ if (a.error === "too-large") return { id: "sound", label, verdict: "unknown", detail: "The file is too large to decode in the browser", tip: "Trim it to the opening and check again" };
+ return { id: "sound", label, verdict: "unknown", detail: "No audio track, or a format this browser can't decode" };
+ }
+ const per = Math.round(HOOK_SECONDS / a.step);
+ const hook = a.db.slice(0, per);
+ const rest = a.db.slice(per);
+ const first = hook.findIndex((d) => d > SILENCE_DB);
+ if (first < 0) return { id: "sound", label, verdict: "weak", detail: "Silent for the first 3 s", tip: "Start with a line, a beat or a sound — silence reads as a slow start" };
+ const at = r1(first * a.step);
+ const hookDb = meanDb(hook.filter((d) => d > SILENCE_DB));
+ const restDb = meanDb(rest.filter((d) => d > SILENCE_DB));
+ const level = `opening ${dbfs(hookDb!)}${restDb != null ? ` · after ${dbfs(restDb)}` : ""}`;
+ const quieter = restDb != null && hookDb! < restDb - 6;
+ if (at <= 0.5 && !quieter) return { id: "sound", label, verdict: "strong", detail: `Sound from ${secs(at)} · ${level}`, at };
+ if (at <= 1.5)
+ return { id: "sound", label, verdict: "ok", detail: `Sound from ${secs(at)} · ${level}`, tip: quieter ? "The opening is quieter than the rest — lead with your strongest audio" : "Start the sound on the first frame", at };
+ return { id: "sound", label, verdict: "weak", detail: `Silent until ${secs(at)} · ${level}`, tip: "Start with a line, a beat or a sound — silence reads as a slow start", at };
+}
+
+function contrastSignal(o: HookInput["opening"]): HookSignal {
+ const label = "Opening frame contrast";
+ const pct = `${Math.round(o.contrast * 100)}% luma spread`;
+ if (o.brightness < DARK) return { id: "contrast", label, verdict: "weak", detail: `A very dark opening frame · ${pct}`, tip: "Lift the exposure of the first shot — the Hook Frame app can rework it" };
+ if (o.contrast >= CONTRAST_STRONG) return { id: "contrast", label, verdict: "strong", detail: `Punchy · ${pct}` };
+ if (o.contrast >= CONTRAST_OK) return { id: "contrast", label, verdict: "ok", detail: `Moderate · ${pct}`, tip: "More contrast and a clear focal point stand out in a busy feed" };
+ return { id: "contrast", label, verdict: "weak", detail: `Flat · ${pct}`, tip: "More contrast and a clear focal point stand out in a busy feed — the Hook Frame app can rework it" };
+}
+
+function formatSignal(i: Pick<HookInput, "width" | "height" | "duration">): HookSignal {
+ const label = "Format";
+ const mins = `${Math.floor(i.duration / 60)}:${String(Math.round(i.duration % 60)).padStart(2, "0")}`;
+ const long = i.duration > 90 ? ` · ${mins} long` : "";
+ const longTip = i.duration > 90 ? "Short-form feeds favour clips under a minute — consider a cut-down" : undefined;
+ if (!i.width || !i.height) return { id: "format", label, verdict: "unknown", detail: "Unknown size" };
+ const ratio = i.width / i.height;
+ if (ratio <= 0.66) return { id: "format", label, verdict: i.duration > 90 ? "ok" : "strong", detail: `Vertical ${i.width}×${i.height}${long}`, tip: longTip };
+ if (ratio <= 1.05) return { id: "format", label, verdict: "ok", detail: `Square-ish ${i.width}×${i.height}${long}`, tip: longTip ?? "Vertical 9:16 fills the whole phone screen — Reframe can convert it" };
+ return { id: "format", label, verdict: "weak", detail: `Landscape ${i.width}×${i.height}${long}`, tip: "Letterboxed in vertical feeds — Reframe can make a 9:16 version" };
+}
+
+/** Every signal, in the order the page lists them. */
+export function hookSignals(input: HookInput): HookSignal[] {
+ return [motionSignal(input.motion), changeSignal(input.motion), facesSignal(input.faces), textSignal(input.text), soundSignal(input.loudness), contrastSignal(input.opening), formatSignal(input)];
+}
+
+/** Counts per verdict — the page shows these, never a made-up overall score. */
+export function hookSummary(signals: HookSignal[]): Record<Verdict, number> {
+ const out: Record<Verdict, number> = { strong: 0, ok: 0, weak: 0, unknown: 0 };
+ for (const s of signals) out[s.verdict]++;
+ return out;
+}
diff --git a/tests/av-tools.test.ts b/tests/av-tools.test.ts
new file mode 100644
index 00000000..d40d5f60
--- /dev/null
+++ b/tests/av-tools.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it } from "vitest";
+import { buildPayload, extractOutputs } from "@/lib/catalog/payload";
+import { getModel } from "@/lib/catalog";
+import { burnRequest, burnRouteFor, CAPTION_STYLES, nearestColorName, OPEN_FONT_SIZE, previewText, styleById, usesCues, type CaptionLook } from "@/lib/av/captions";
+import { animateSpinHref, model3dRequest, model3dView, MODELS_3D } from "@/lib/av/model3d";
+import { frameParams, frameRequest } from "@/lib/av/frames";
+import type { Cue } from "@/lib/cues";
+
+const cues: Cue[] = [
+ { start: 0, end: 1.5, text: "hello there friends" },
+ { start: 1.6, end: 3, text: " " },
+ { start: 3.1, end: 4.2, text: "second line" },
+];
+const look = (o: Partial<CaptionLook> = {}): CaptionLook => ({ style: "clean", size: "M", position: "bottom", ...o });
+
+describe("caption style → burn params", () => {
+ it("picks the burner per engine and says which take the edited lines", () => {
+ expect(burnRouteFor("open", true)).toBe("open");
+ expect(burnRouteFor("cloud", false)).toBe("veed");
+ expect(burnRouteFor("cloud", true)).toBe("auto");
+ expect([usesCues("open"), usesCues("veed"), usesCues("auto")]).toEqual([true, true, false]);
+ });
+
+ it("open: the edited cues, size as % of the frame, top/bottom, karaoke as a few words at a time", () => {
+ const r = burnRequest({ route: "open", video: "v.mp4", cues, look: look({ style: "karaoke", size: "L", position: "center" }) });
+ expect(r).toMatchObject({ modelId: "oss-captions-burnin", op: "captions", inputs: { video: "v.mp4" } });
+ expect(r.params?.extra).toEqual({
+ cues: [
+ { start: 0, end: 1.5, text: "HELLO THERE FRIENDS" },
+ { start: 3.1, end: 4.2, text: "SECOND LINE" },
+ ],
+ fontSize: OPEN_FONT_SIZE.L,
+ fontColor: "#ffffff",
+ captionPosition: "bottom", // the open burner has no centre: bottom
+ wordsPerCaption: 3,
+ });
+ const plain = burnRequest({ route: "open", video: "v.mp4", cues, look: look({ color: "#ff0000", position: "top" }) });
+ expect(plain.params?.extra).toMatchObject({ fontColor: "#ff0000", captionPosition: "top", wordsPerCaption: 0 });
+ expect(() => burnRequest({ route: "open", video: "v.mp4", cues: [{ start: 0, end: 1, text: " " }], look: look() })).toThrow(/no lines/);
+ });
+
+ it("VEED: its preset, the lines as SRT and dotted customization keys that nest into the payload", () => {
+ const r = burnRequest({ route: "veed", video: "v.mp4", cues, look: look({ style: "boxed", position: "top" }) });
+ const extra = r.params!.extra as Record<string, unknown>;
+ expect(extra.preset).toBe("backdrop");
+ expect(extra.srt_content).toBe("1\n00:00:00,000 --> 00:00:01,500\nhello there friends\n\n2\n00:00:03,100 --> 00:00:04,200\nsecond line\n");
+ expect(extra["customization.position"]).toBe("top");
+ expect(extra["customization.shadow"]).toBe("none");
+ const veed = getModel("veed-subtitles")!;
+ const payload = buildPayload(veed.routes[0].map!, { prompt: "", video: "https://x/v.mp4", extra });
+ expect(payload.customization).toMatchObject({ position: "top", text_customizations: { baseline: { font: "Inter", weight: 700, color: "#ffffff" } } });
+ const karaoke = burnRequest({ route: "veed", video: "v.mp4", cues, look: look({ style: "karaoke" }) });
+ expect((karaoke.params!.extra as Record<string, unknown>)["customization.text_customizations.highlighted.color"]).toBe("#8b5cf6");
+ });
+
+ it("Auto Subtitle: named colours, size in px, words per subtitle, the spoken language", () => {
+ const r = burnRequest({ route: "auto", video: "v.mp4", cues: [], look: look({ style: "bold", size: "S" }), sourceLanguage: "es" });
+ expect(r.params).toEqual({
+ sourceLanguage: "es",
+ extra: { font_name: "Montserrat", font_weight: "black", font_color: "yellow", highlight_color: "yellow", position: "bottom", font_size: 60, words_per_subtitle: 6, background_color: "none" },
+ });
+ const k = burnRequest({ route: "auto", video: "v.mp4", cues: [], look: look({ style: "karaoke" }), sourceLanguage: "auto" });
+ expect(k.params).not.toHaveProperty("sourceLanguage");
+ expect(k.params!.extra).toMatchObject({ highlight_color: "purple", words_per_subtitle: 3 });
+ expect(nearestColorName("#00e5ff")).toBe("cyan");
+ expect(nearestColorName("#fefefe")).toBe("white");
+ });
+
+ it("every style has a VEED preset and a distinct id; the preview shows the line on screen", () => {
+ expect(new Set(CAPTION_STYLES.map((s) => s.id)).size).toBe(CAPTION_STYLES.length);
+ for (const s of CAPTION_STYLES) expect(s.veed).toBeTruthy();
+ expect(styleById("nope").id).toBe("clean");
+ expect(previewText(cues, 0.5, look())?.text).toBe("hello there friends");
+ expect(previewText(cues, 5, look())).toBeNull();
+ });
+});
+
+describe("3D viewer data flow", () => {
+ it("asks the engine's 3D model for the photo; an unknown pick falls back to the default", () => {
+ expect(model3dRequest({ engine: "cloud", photo: "p.png" })).toEqual({ feature: "image-to-3d", modelId: "hunyuan-3d-3-1-pro", op: "image-to-3d", inputs: { images: ["p.png"] } });
+ expect(model3dRequest({ engine: "open", photo: "p.png", modelId: "trellis-2" }).modelId).toBe("oss-trellis2");
+ expect(model3dRequest({ engine: "cloud", photo: "p.png", modelId: "tripo-h3-1" }).modelId).toBe("tripo-h3-1");
+ for (const m of [...MODELS_3D.cloud, ...MODELS_3D.open]) expect(getModel(m.id)?.routes.some((r) => r.op === "image-to-3d"), m.id).toBe(true);
+ });
+
+ it("a cloud GLB with formats and a preview → viewer, downloads, and Animate the spin from the photo", () => {
+ const outputs = extractOutputs(
+ { model_glb: { url: "https://cdn/x/model.glb", content_type: "application/octet-stream" }, model_urls: { glb: { url: "https://cdn/x/model.glb" }, obj: { url: "https://cdn/x/model.obj" }, usdz: { url: "https://cdn/x/model.usdz" } }, thumbnail: { url: "https://cdn/x/thumb.png" } },
+ "image-to-3d",
+ );
+ const view = model3dView({ outputs: outputs.map((o) => ({ ...o, meta: o.meta ?? {} })) as never, request: model3dRequest({ engine: "cloud", photo: "/api/files/p.png" }) });
+ expect(view).toEqual({ glb: "https://cdn/x/model.glb", poster: "https://cdn/x/thumb.png", photo: "/api/files/p.png", turntable: undefined, formats: { glb: "https://cdn/x/model.glb", obj: "https://cdn/x/model.obj", usdz: "https://cdn/x/model.usdz" } });
+ const href = animateSpinHref(view)!;
+ expect(href.startsWith("/video?")).toBe(true);
+ expect(new URLSearchParams(href.split("?")[1]).get("image")).toBe("/api/files/p.png");
+ // A turntable recorded in the browser takes over: restyle it in Edit video.
+ const recorded = animateSpinHref(view, "/api/files/turn.webm")!;
+ expect(recorded.startsWith("/video-edit?")).toBe(true);
+ expect(new URLSearchParams(recorded.split("?")[1]).get("video")).toBe("/api/files/turn.webm");
+ });
+
+ it("a TRELLIS.2 / demo result brings its own turntable", () => {
+ const view = model3dView({
+ outputs: [
+ { url: "/api/files/m.glb", kind: "model3d", meta: { format: "glb" } },
+ { url: "/api/files/turn.mp4", kind: "video", meta: { turntable: true } },
+ ] as never,
+ request: model3dRequest({ engine: "open", photo: "p.png" }),
+ });
+ expect(view.turntable).toBe("/api/files/turn.mp4");
+ expect(animateSpinHref(view)).toMatch(/^\/video-edit\?video=%2Fapi%2Ffiles%2Fturn\.mp4/);
+ expect(model3dView({ outputs: [], request: { feature: "x", modelId: "y", op: "image-to-3d" } as never })).toMatchObject({ glb: undefined, formats: {} });
+ expect(animateSpinHref({ formats: {} })).toBeNull();
+ });
+});
+
+describe("extract frame on both engines", () => {
+ it("cloud names the frame; open decodes a short window and takes its first frame", () => {
+ expect(frameParams("cloud", "last")).toEqual({ extra: { frame_type: "last" } });
+ expect(() => frameParams("cloud", { at: 2 })).toThrow(/first, middle or last/);
+ expect(frameParams("open", "last")).toBeUndefined();
+ expect(frameParams("open", "first")).toEqual({ startTime: 0, endTime: 0.5, extra: { frameIndex: 0 } });
+ expect(frameParams("open", { at: 3.2 })).toEqual({ startTime: 3.2, endTime: 3.7, extra: { frameIndex: 0 } });
+ expect(frameRequest({ feature: "f", engine: "open", video: "v.mp4", pick: "last" })).toEqual({ feature: "f", modelId: "oss-extract-frame", op: "frame", inputs: { video: "v.mp4" } });
+ expect(getModel("oss-extract-frame")?.routes[0]).toMatchObject({ provider: "comfyui", endpoint: "frame-extract", op: "frame" });
+ });
+});
diff --git a/tests/av-virality.test.ts b/tests/av-virality.test.ts
new file mode 100644
index 00000000..20d61260
--- /dev/null
+++ b/tests/av-virality.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it } from "vitest";
+import { hookSignals, hookSummary, hookTimes, loudnessSeries, lumaStats, meanDb, VIRALITY_PARITY, type HookInput } from "@/lib/av/virality";
+import { getPreset } from "@/lib/catalog";
+
+const base: HookInput = {
+ duration: 20,
+ width: 1080,
+ height: 1920,
+ motion: hookTimes(20).map((t, i) => ({ t, diff: i === 0 ? 0 : i === 6 ? 0.2 : 0.04 })),
+ opening: { contrast: 0.25, brightness: 0.5 },
+ faces: [
+ { t: 0, count: 1 },
+ { t: 1, count: 1 },
+ { t: 2, count: 0 },
+ ],
+ text: [
+ { t: 0, chars: 12 },
+ { t: 1, chars: 12 },
+ { t: 2, chars: 0 },
+ ],
+ loudness: { step: 0.1, db: [...Array(30).fill(-18), ...Array(100).fill(-20)] },
+};
+
+const verdicts = (i: HookInput) => Object.fromEntries(hookSignals(i).map((s) => [s.id, s.verdict]));
+
+describe("virality heuristic", () => {
+ it("samples the hook every quarter second, no further than the clip", () => {
+ expect(hookTimes(20)).toEqual([0, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3]);
+ expect(hookTimes(1)).toEqual([0, 0.25, 0.5, 0.75]);
+ expect(hookTimes(0)).toEqual([0]);
+ });
+
+ it("measures luma spread and loudness", () => {
+ const flat = { data: new Uint8ClampedArray([128, 128, 128, 255, 128, 128, 128, 255]) };
+ expect(lumaStats(flat).contrast).toBeCloseTo(0);
+ const split = { data: new Uint8ClampedArray([0, 0, 0, 255, 255, 255, 255, 255]) };
+ expect(lumaStats(split).brightness).toBeCloseTo(0.5);
+ expect(lumaStats(split).contrast).toBeCloseTo(0.5);
+ // A full-scale square wave is 0 dBFS; silence is the floor.
+ const square = Float32Array.from({ length: 1600 }, (_, i) => (i % 2 ? 1 : -1));
+ expect(loudnessSeries(square, 16000, 0.1)).toEqual([0]);
+ expect(loudnessSeries(new Float32Array(1600), 16000, 0.1)).toEqual([-100]);
+ expect(meanDb([-20, -20])).toBeCloseTo(-20);
+ expect(meanDb([])).toBeNull();
+ });
+
+ it("a moving, captioned, talking vertical opening is strong on every signal", () => {
+ const v = verdicts(base);
+ expect(v).toEqual({ motion: "strong", change: "strong", faces: "strong", text: "strong", sound: "strong", contrast: "strong", format: "strong" });
+ const change = hookSignals(base).find((s) => s.id === "change")!;
+ expect(change.at).toBe(1.5);
+ expect(hookSummary(hookSignals(base))).toEqual({ strong: 7, ok: 0, weak: 0, unknown: 0 });
+ });
+
+ it("flags a still, silent, flat landscape opening", () => {
+ const v = verdicts({
+ ...base,
+ width: 1920,
+ height: 1080,
+ motion: base.motion.map((m) => ({ ...m, diff: 0.002 })),
+ opening: { contrast: 0.05, brightness: 0.4 },
+ faces: [{ t: 0, count: 0 }],
+ text: [{ t: 0, chars: 0 }],
+ loudness: { step: 0.1, db: [...Array(12).fill(-80), ...Array(40).fill(-20)] },
+ });
+ expect(v).toEqual({ motion: "weak", change: "weak", faces: "weak", text: "weak", sound: "ok", contrast: "weak", format: "weak" });
+ const late = hookSignals({ ...base, loudness: { step: 0.1, db: Array(40).fill(-80) } }).find((s) => s.id === "sound")!;
+ expect(late.verdict).toBe("weak");
+ expect(late.detail).toMatch(/Silent for the first 3 s/);
+ });
+
+ it("says 'not measured' instead of guessing when the browser can't detect", () => {
+ const signals = hookSignals({ ...base, faces: null, text: null, loudness: { error: "unreadable" } });
+ const unknown = signals.filter((s) => s.verdict === "unknown").map((s) => s.id);
+ expect(unknown).toEqual(["faces", "text", "sound"]);
+ expect(signals.find((s) => s.id === "faces")!.detail).toBe("This browser has no face detector");
+ expect(hookSignals(base).find((s) => s.id === "sound")!.detail).toBe("Sound from 0.0 s · opening \u221218 dBFS · after \u221220 dBFS");
+ expect(hookSignals({ ...base, loudness: { error: "no-audio" } }).find((s) => s.id === "sound")!.verdict).toBe("weak");
+ });
+
+ it("a later face or a quieter opening is only 'fine'", () => {
+ const v = verdicts({ ...base, faces: [{ t: 2, count: 2 }], loudness: { step: 0.1, db: [...Array(10).fill(-80), ...Array(20).fill(-40), ...Array(50).fill(-12)] } });
+ expect(v.faces).toBe("ok");
+ expect(v.sound).toBe("ok");
+ });
+
+ it("shows no score anywhere and states the TRIBE v2 licence", () => {
+ for (const s of hookSignals(base)) expect(`${s.detail} ${s.tip ?? ""}`).not.toMatch(/score|viral|\/ ?100/i);
+ expect(VIRALITY_PARITY.body).toMatch(/TRIBE v2/);
+ expect(VIRALITY_PARITY.body).toMatch(/CC BY-NC/);
+ expect(VIRALITY_PARITY.open).toMatch(/non-commercial/);
+ });
+
+ it("the app that used to be Virality Predictor is the Hook Frame step", () => {
+ expect(getPreset("app-virality-predictor")).toBeUndefined();
+ expect(getPreset("app-hook-frame")?.name).toBe("Hook Frame");
+ });
+});
diff --git a/tests/av-workflows.test.ts b/tests/av-workflows.test.ts
new file mode 100644
index 00000000..ac4e40ae
--- /dev/null
+++ b/tests/av-workflows.test.ts
@@ -0,0 +1,83 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+import type { GenInput, Operation } from "@/lib/catalog/types";
+import type { MediaInfo } from "@/lib/media-probe";
+
+// The av-tools ComfyUI workflows (Extract frame, video-synced Foley, Product shot), bound for real.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-av-workflows-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://comfy.test:8188";
+
+const { loadManifest, prepareWorkflow } = await import("@/server/providers/comfyui");
+const { getModel } = await import("@/lib/catalog");
+const { computeFrames } = await import("@/lib/comfy");
+const { frameParams } = await import("@/lib/av/frames");
+
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const clip: MediaInfo = { container: "mp4", hasVideo: true, hasAudio: true, duration: 6, videoDuration: 6, width: 640, height: 360, fps: 30, frames: 180 };
+
+async function prepare(id: string, op: Operation, input: Partial<GenInput>) {
+ const uploads: string[] = [];
+ const res = await prepareWorkflow(id, { prompt: "", ...input } as GenInput, {
+ generationId: "gen1",
+ op,
+ upload: async (_d, _t, name) => {
+ uploads.push(name);
+ return `up_${name}`;
+ },
+ media: (name) => (name === "clip.mp4" ? clip : undefined),
+ serverRam: async () => undefined,
+ });
+ return { ...res, uploads };
+}
+
+describe("av-tools workflows", () => {
+ it("are in the manifest, validated against a live ComfyUI, with a licence, and used by a model", () => {
+ const byId = new Map(loadManifest().workflows.map((w) => [w.id, w]));
+ for (const [id, model] of [
+ ["frame-extract", "oss-extract-frame"],
+ ["v2a-hunyuan-foley", "oss-hunyuan-foley-video"],
+ ["product-shot-qwen-edit-2509", "oss-product-shot"],
+ ]) {
+ expect(byId.get(id)?.validated, id).toBe(true);
+ expect(byId.get(id)?.license, id).toBeTruthy();
+ expect(getModel(model)?.routes.find((r) => r.provider === "comfyui")?.endpoint, model).toBe(id);
+ }
+ });
+
+ it("Extract frame: the last frame by default; a moment as a short window's first frame", async () => {
+ const last = await prepare("frame-extract", "frame", { video: "clip.mp4", ...frameParams("open", "last") });
+ expect(last.workflow["1"].inputs.file).toBe("clip.mp4");
+ expect(last.workflow["2"].inputs).toMatchObject({ start_time: -1, duration: 0 });
+ expect(last.workflow["4"].inputs.batch_index).toBe(-1);
+ expect(last.workflow["5"].inputs.filename_prefix).toBe("fuobe/gen1");
+ const at = await prepare("frame-extract", "frame", { video: "clip.mp4", ...frameParams("open", { at: 3.2 }) });
+ expect(at.workflow["2"].inputs.start_time).toBe(3.2);
+ expect(at.workflow["2"].inputs.duration).toBeCloseTo(0.5);
+ expect(at.workflow["4"].inputs.batch_index).toBe(0);
+ const first = await prepare("frame-extract", "frame", { video: "clip.mp4", ...frameParams("open", "first") });
+ expect(first.workflow["2"].inputs).toMatchObject({ start_time: 0, duration: 0.5 });
+ await expect(prepare("frame-extract", "frame", { video: "clip.mp4", ...frameParams("open", { at: 9 }) })).rejects.toThrow(/past the end of the clip/);
+ });
+
+ it("Foley: the clip at the sampler's frame rate, as many frames as the sound is long", async () => {
+ const r = await prepare("v2a-hunyuan-foley", "v2a", { video: "clip.mp4", prompt: "footsteps on gravel", negativePrompt: "music", duration: 4, seed: 7 });
+ expect(r.workflow["5"].inputs.video).toBe("clip.mp4");
+ expect(r.workflow["6"].inputs.file).toBe("clip.mp4");
+ expect(r.workflow["3"].inputs).toMatchObject({ prompt: "footsteps on gravel", negative_prompt: "music", duration: 4, frame_rate: 8, seed: 7 });
+ expect(r.workflow["5"].inputs).toMatchObject({ force_rate: 8, frame_load_cap: computeFrames(4, 8, 4, 481) });
+ for (const n of ["4", "8"]) expect(r.workflow[n].inputs.filename_prefix).toBe("fuobe/gen1");
+ });
+
+ it("Product shot: the photo cut out onto white, the scene after the LoRA's trigger", async () => {
+ const r = await prepare("product-shot-qwen-edit-2509", "edit", { images: ["bottle.png"], prompt: "on a marble counter, morning light", seed: 3 });
+ expect(r.workflow["78"].inputs.image).toBe("bottle.png");
+ expect(r.workflow["1002"].inputs).toMatchObject({ string_a: "白底图转场景,", string_b: "on a marble counter, morning light" });
+ expect(r.workflow["433:3"].inputs.seed).toBe(3);
+ expect(r.workflow["1001"].inputs.lora_name).toBe("Qwen-Image-Edit-2509-White_to_Scene.safetensors");
+ expect(r.workflow["469"].inputs.filename_prefix).toBe("fuobe/gen1");
+ });
+});