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.

Shorts and Edit video: Enhance (H3 regenerate) redraws a segment or an edit at 1080p on your GPU

Claude301419437f67
diff --git a/src/app/api/shorts/sessions/[id]/segments/[index]/enhance/route.ts b/src/app/api/shorts/sessions/[id]/segments/[index]/enhance/route.ts
new file mode 100644
index 00000000..f1669392
--- /dev/null
+++ b/src/app/api/shorts/sessions/[id]/segments/[index]/enhance/route.ts
@@ -0,0 +1,13 @@
+import { enhanceSegment, ShortsError } from "@/server/shorts";
+import { NonceSchema, handle, once, optionalBody } from "@/server/shorts-schemas";
+
+/** Enhance (H3 regenerate): a 1080p take of this segment, redrawn on your GPU (a repeated requestId gets the first answer). */
+export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]/enhance">) {
+ return handle(async () => {
+ const { id, index } = await ctx.params;
+ const i = Number(index);
+ if (!Number.isInteger(i) || i < 0) throw new ShortsError("No such segment", 404);
+ const { requestId } = await optionalBody(request, NonceSchema);
+ return Response.json(await once(`shorts-enhance:${id}:${i}`, requestId, () => enhanceSegment(id, i)), { status: 201 });
+ }, request);
+}
diff --git a/src/components/shorts/hooks.ts b/src/components/shorts/hooks.ts
index 5d40cedf..b72f7f6e 100644
--- a/src/components/shorts/hooks.ts
+++ b/src/components/shorts/hooks.ts
@@ -156,6 +156,10 @@ export function useShortsActions(id?: string) {
mutationFn: (v: { index: number; requestId?: string }) => send<ShortsSessionView>(`/api/shorts/sessions/${id}/segments/${v.index}`, "POST", { requestId: v.requestId }),
onSuccess: put,
}),
+ enhance: useMutation({
+ mutationFn: (v: { index: number; requestId?: string }) => send<ShortsSessionView>(`/api/shorts/sessions/${id}/segments/${v.index}/enhance`, "POST", { requestId: v.requestId }),
+ onSuccess: put,
+ }),
primary: useMutation({
mutationFn: (v: { index: number; generationId: string }) => send<ShortsSessionView>(`/api/shorts/sessions/${id}/segments/${v.index}/primary`, "POST", { generationId: v.generationId }),
onSuccess: put,
diff --git a/src/components/shorts/session-view.tsx b/src/components/shorts/session-view.tsx
index 36343143..ca85250e 100644
--- a/src/components/shorts/session-view.tsx
+++ b/src/components/shorts/session-view.tsx
@@ -1,6 +1,6 @@
"use client";
-import { ArrowLeft, Check, Cloud, Cpu, Download, FolderDown, Layers, Loader2, RotateCcw, Scissors, Trash2 } from "lucide-react";
+import { ArrowLeft, Check, Cloud, Cpu, Download, FolderDown, Layers, Loader2, RotateCcw, Scissors, Sparkles, Trash2 } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
@@ -22,7 +22,9 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { MediaThumb } from "@/components/studio/result-media";
import { radioKeys, radioTab } from "@/components/studio/radio-keys";
import { Viewer } from "@/components/studio/viewer";
-import { chainState, formatSeconds, stitchCurrent, stitchSteps, takeSteps, type ChainState, type ShortsSessionSegment } from "@/lib/catalog/shorts";
+import { chainState, ENHANCE_COPY, formatSeconds, segmentSeconds, stitchCurrent, stitchSteps, takeSteps, type ChainState, type ShortsSessionSegment } from "@/lib/catalog/shorts";
+import { finishLengthProblem } from "@/lib/catalog/regenerate";
+import { useEngineMode } from "@/lib/api";
import type { Generation } from "@/lib/catalog/types";
import { formatCost, ratioValue, timeAgo } from "@/lib/format";
import { downloadHref, downloadName } from "@/lib/library";
@@ -95,6 +97,7 @@ function Frame({ title, children, actions }: { title: string; children: React.Re
function Session({ s }: { s: View }) {
const router = useRouter();
const actions = useShortsActions(s.id);
+ const engineMode = useEngineMode();
const [open, setOpen] = useState<Generation | null>(null);
const [confirm, setConfirm] = useState(false);
const gens = s.generations;
@@ -123,6 +126,13 @@ function Session({ s }: { s: View }) {
.then((v) => v && toast("Stitching your short"))
.catch((e: Error) => toastError(e));
};
+ const enhanceGuard = useSubmitGuard();
+ const enhance = (i: number) => {
+ if (actions.enhance.isPending) return;
+ void enhanceGuard(`enhance:${i}:${s.segments[i].primary}`, (requestId) => actions.enhance.mutateAsync({ index: i, requestId }))
+ .then((v) => v && toast(`Enhancing segment ${i + 1} at 1080p — pick the new take when it's ready`))
+ .catch((e: Error) => toastError(e));
+ };
const regenerate = (i: number) => {
if (actions.regenerate.isPending) return;
void takeGuard(`take:${i}:${s.segments[i].takes.length}`, (requestId) => actions.regenerate.mutateAsync({ index: i, requestId }))
@@ -245,10 +255,15 @@ function Session({ s }: { s: View }) {
onRegenerate={() => regenerate(i)}
regenerating={actions.regenerate.isPending && actions.regenerate.variables?.index === i}
busy={actions.regenerate.isPending}
+ enhanceable={s.engine === "open" && engineMode !== "cloud"}
+ onEnhance={() => enhance(i)}
+ enhancing={actions.enhance.isPending && actions.enhance.variables?.index === i}
onPrimary={(gid) => actions.primary.mutate({ index: i, generationId: gid }, { onError: (e) => toastError(e) })}
/>
))}
</div>
+ {/* A cloud short: Enhance (H3 regenerate) needs your GPU, said once rather than on every segment. */}
+ {s.engine === "cloud" && engineMode !== "cloud" && <p className="text-[12px] text-muted-foreground">{ENHANCE_COPY.cloudSession}.</p>}
</section>
</div>
{open && <Viewer generation={open} index={0} onClose={() => setOpen(null)} />}
@@ -294,6 +309,9 @@ function SegmentCard({
regenerating,
busy,
onPrimary,
+ enhanceable,
+ onEnhance,
+ enhancing,
}: {
seg: ShortsSessionSegment;
index: number;
@@ -308,8 +326,14 @@ function SegmentCard({
/** A new take (of any segment) is on its way. */
busy: boolean;
onPrimary: (id: string) => void;
+ /** Enhance (H3 regenerate): on an open-source short (Paid APIs only hides it). */
+ enhanceable: boolean;
+ onEnhance: () => void;
+ enhancing: boolean;
}) {
const primary = gens[seg.primary];
+ const chosenTake = seg.takes.find((t) => t.look === seg.primary);
+ const tooLong = finishLengthProblem(segmentSeconds(seg));
const video = videoOf(primary);
const price = demo ? "Placeholder · free" : cost === null ? "" : cost === 0 ? "Free" : `≈ ${formatCost(cost)}`;
return (
@@ -348,7 +372,12 @@ function SegmentCard({
{state.error && <p className="line-clamp-3 text-[12px] break-words text-muted-foreground">{state.error}</p>}
</div>
)}
- {state.status === "done" && <p className="text-[13px] text-muted-foreground">Take {seg.takes.findIndex((t) => t.look === seg.primary) + 1} is in the full video.</p>}
+ {state.status === "done" && (
+ <p className="text-[13px] text-muted-foreground">
+ Take {seg.takes.findIndex((t) => t.look === seg.primary) + 1}
+ {chosenTake?.enhance ? " (enhanced, 1080p)" : ""} is in the full video.
+ </p>
+ )}
{seg.takes.length > 1 && (
// Arrow keys move between the takes and pick them (radio pattern); the chosen take is the Tab stop.
// Only takes that can't be picked (still rendering, failed) are turned off, with the reason in their name.
@@ -365,7 +394,7 @@ function SegmentCard({
type="button"
role="radio"
aria-checked={chosen}
- aria-label={`Take ${ti + 1}${why ? ` (${why})` : chosen ? " (in the full video)" : ""}`}
+ aria-label={`Take ${ti + 1}${t.enhance ? ", enhanced" : ""}${why ? ` (${why})` : chosen ? " (in the full video)" : ""}`}
tabIndex={radioTab(chosen)}
disabled={st.status !== "done" && !chosen}
onClick={() => !chosen && st.status === "done" && onPrimary(t.look)}
@@ -377,6 +406,7 @@ function SegmentCard({
>
{v ? <MediaThumb output={v} /> : st.status === "working" ? <Loader2 className="mx-auto size-3.5 animate-spin text-muted-foreground" /> : null}
<span className="absolute bottom-0.5 left-0.5 rounded bg-black/55 px-1 text-[10px] font-semibold text-white">{ti + 1}</span>
+ {t.enhance && <span className="absolute top-0.5 right-0.5 rounded bg-black/55 px-1 text-[9px] font-semibold text-white">HD</span>}
</button>
);
})}
@@ -393,6 +423,19 @@ function SegmentCard({
Regenerate
{price && <span className="font-mono text-[11px] font-normal text-muted-foreground">{price}</span>}
</button>
+ {enhanceable && !chosenTake?.enhance && !tooLong && (
+ <button
+ type="button"
+ onClick={onEnhance}
+ disabled={state.status !== "done" || enhancing}
+ title={state.status !== "done" ? ENHANCE_COPY.notReady : `${ENHANCE_COPY.hint} · ${ENHANCE_COPY.gpu}`}
+ className="inline-flex h-8 items-center gap-1.5 rounded-full border bg-background px-3 text-[12px] font-medium hover:bg-accent disabled:opacity-60"
+ >
+ {enhancing ? <Loader2 className="size-3.5 animate-spin" /> : <Sparkles className="size-3.5" />}
+ {ENHANCE_COPY.label}
+ <span className="font-mono text-[11px] font-normal text-muted-foreground">1080p · Free</span>
+ </button>
+ )}
{video && primary && (
<a
href={downloadHref(video.url, downloadName(primary, video, 0))}
diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsx
index 758ed278..5c367de7 100644
--- a/src/components/studio/result-actions.tsx
+++ b/src/components/studio/result-actions.tsx
@@ -76,7 +76,7 @@ import { toSrt, toVtt } from "@/lib/cues";
import { cuesOf, outputActions, textOf, type ActionContext, type OutputAction, type OutputActionId } from "@/lib/output-actions";
import { cn } from "@/lib/utils";
import { copyWithToast } from "@/lib/clipboard";
-import { rerenderRequest } from "@/lib/catalog/regenerate";
+import { enhanceRequest, rerenderRequest } from "@/lib/catalog/regenerate";
import { toastError } from "@/lib/refusals";
export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {
@@ -111,6 +111,7 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {
finalize: Sparkles,
regenerate: Sparkles,
"rerender-2k": Sparkles,
+ "enhance-h3": Sparkles,
compare: Columns2,
reuse: RotateCcw,
"make-skill": BookmarkPlus,
@@ -249,6 +250,9 @@ export function useActionRunner(opts: RunnerOptions = {}) {
case "rerender-2k":
// fal's H3 at 2K: the same inputs, words and seed, a new render on the same hosted model (priced per second).
return create.mutate(rerenderRequest(g), { onSuccess: () => toast.success("Rendering it again at 2K"), onError: (e) => toastError(e) });
+ case "enhance-h3":
+ // Open-H3 Regenerate at 1080p on your GPU (RIFE first for a 16 fps edit), from the edit's own words.
+ return create.mutate(enhanceRequest(g, o.url), { onSuccess: () => toast.success("Enhancing at 1080p on your GPU"), onError: (e) => toastError(e) });
case "reuse":
return opts.onReuse?.(g);
case "make-skill":
diff --git a/src/lib/catalog/shorts.ts b/src/lib/catalog/shorts.ts
index a9a236a2..9938e4c0 100644
--- a/src/lib/catalog/shorts.ts
+++ b/src/lib/catalog/shorts.ts
@@ -15,6 +15,7 @@
*/
import { scenePoster, type PresetPreview, type PreviewFx, type PreviewScene } from "../preset-cards";
import { templateCover, templatePreview } from "../template-covers";
+import { finishLengthProblem, REGEN_FINISH_TIER, REGEN_FPS, REGEN_SMOOTH_MODEL, regenFinishSteps } from "./regenerate";
import type { ChainSlot, Engine, Generation, GenerationRequest } from "./types";
// ---------------------------------------------------------------------------
@@ -700,12 +701,12 @@ export type ClipRef = { key: string } | { url: string };
* are) and put the original sound back. Returns the steps and the key of the finished video
* (undefined when there is nothing to make: one segment and no sound to add).
*/
-export function planStitch(input: ShortsPlanInput, clips: ClipRef[], suffix = ""): { steps: PlanStep[]; final?: string } {
+export function planStitch(input: ShortsPlanInput, clips: ClipRef[], suffix = "", opts: { resolution?: string } = {}): { steps: PlanStep[]; final?: string } {
const t = SHORTS_TOOLS[input.engine];
const base = { feature: SHORTS_FEATURE, batchTitle: input.title };
const helper = { feature: SHORTS_STEP_FEATURE, batchTitle: input.title };
const steps: PlanStep[] = [];
- const params = input.engine === "open" ? { ...ratioParams(input), resolution: "480p" } : ratioParams(input);
+ const params = input.engine === "open" ? { ...ratioParams(input), resolution: opts.resolution ?? "480p" } : ratioParams(input);
// Each join step takes its clips either chained (key) or as files (url).
let level: ClipRef[] = clips;
let depth = 0;
@@ -717,7 +718,7 @@ export function planStitch(input: ShortsPlanInput, clips: ClipRef[], suffix = ""
const after = items.flatMap((c) => ("key" in c ? [c.key] : []));
const urls = items.flatMap((c) => ("url" in c ? [c.url] : []));
const key = last ? `join${suffix}` : `join${suffix}-${depth}-${gi}`;
- // Files first, then chained clips: a level only ever mixes the two in that order (stitch-again fold).
+ // Files first, then chained clips (a stitch-again fold); a finished stitch's mix is placed by `at` below.
steps.push({
key,
request: {
@@ -729,7 +730,10 @@ export function planStitch(input: ShortsPlanInput, clips: ClipRef[], suffix = ""
params,
step: { label: last ? "Stitch" : "Stitching", index: 1000 + depth, of: 1000 },
},
- ...(after.length ? { after, chain: after.map(() => ({ slot: "videos" as const })) } : {}),
+ // A group that mixes files and chained clips puts each chained clip at its own place (`at`), keeping the order.
+ ...(after.length
+ ? { after, chain: urls.length ? items.flatMap((c, at) => ("key" in c ? [{ slot: "videos" as const, at }] : [])) : after.map(() => ({ slot: "videos" as const })) }
+ : {}),
});
return { key };
});
@@ -773,6 +777,75 @@ export function planStitch(input: ShortsPlanInput, clips: ClipRef[], suffix = ""
return { steps, final: key };
}
+// ---------------------------------------------------------------------------
+// Enhance (H3 regenerate) on a segment (package n7-10; docs/research/new-models-7.md §2.10)
+
+export const ENHANCE_COPY = {
+ label: "Enhance (H3 regenerate)",
+ hint: "1080p · sharper, may redraw",
+ /** Only on your GPU: nobody hosts the open refiner. */
+ gpu: "Runs on your GPU (open source)",
+ cloudSession: "Enhance (H3 regenerate) runs on your GPU (open source): make the short on your GPU to use it",
+ done: "This take is already enhanced",
+ notReady: "Wait for this take to finish first",
+} as const;
+
+/** The segment's length in seconds (its exact frames at 16 fps on the open engine). */
+export const segmentSeconds = (seg: ShortsSegment) => (seg.frames ? seg.frames / SHORTS.openFps : seg.end - seg.start);
+
+/** Why a segment can't be enhanced in this session, or null. */
+export function enhanceProblem(input: Pick<ShortsPlanInput, "engine">, seg: ShortsSegment): string | null {
+ if (input.engine !== "open") return ENHANCE_COPY.cloudSession;
+ return finishLengthProblem(segmentSeconds(seg));
+}
+
+/**
+ * Enhance (H3 regenerate) on one segment's take: the restyle (Wan VACE, 16 fps) brought to 24 fps with RIFE, then redrawn
+ * by Open-H3 Regenerate at 1080p with the 576p preset and start sigma 0.8, from the segment's own restyle words. A new
+ * take of the segment, to compare and pick.
+ */
+export function planEnhance(input: ShortsPlanInput, seg: ShortsSegment, take: { url: string }, suffix = ""): { steps: PlanStep[]; keys: { smooth?: string; look: string } } {
+ const problem = enhanceProblem(input, seg);
+ if (problem) throw new Error(problem);
+ const plan = regenFinishSteps({
+ key: `enhance${seg.index}${suffix}`,
+ clip: { url: take.url },
+ prompt: segmentPrompt(input.look),
+ seconds: segmentSeconds(seg),
+ fps: SHORTS.openFps,
+ draftFrom: "other",
+ helper: { feature: SHORTS_STEP_FEATURE, batchTitle: input.title },
+ label: `Segment ${seg.index + 1}`,
+ ...(input.seed !== undefined ? { seed: input.seed } : {}),
+ });
+ // The redraw is the take (in History, like a restyle); RIFE's step stays a helper.
+ const steps = plan.steps.map((st) => (st.key === plan.final ? { ...st, request: { ...st.request, feature: SHORTS_FEATURE } } : st));
+ const smooth = steps.find((st) => st.request.modelId === REGEN_SMOOTH_MODEL)?.key;
+ return { steps, keys: { ...(smooth ? { smooth } : {}), look: plan.final } };
+}
+
+/**
+ * The stitch of the chosen takes when some are enhanced (1080p at 24 fps): the others are brought to 24 fps with RIFE so
+ * every clip shares one rate (the open join concatenates frames, it doesn't retime them), and the join runs at 1080p.
+ * With none enhanced it is the plain stitch.
+ */
+export function planFinishedStitch(input: ShortsPlanInput, clips: { url: string; enhanced: boolean }[], suffix = ""): { steps: PlanStep[]; final?: string } {
+ if (input.engine !== "open" || !clips.some((c) => c.enhanced)) return planStitch(input, clips.map((c) => ({ url: c.url })), suffix);
+ const helper = { feature: SHORTS_STEP_FEATURE, batchTitle: input.title };
+ const smooth: PlanStep[] = [];
+ const refs: ClipRef[] = clips.map((c, i) => {
+ if (c.enhanced) return { url: c.url };
+ const key = `smooth${suffix}-${i}`;
+ smooth.push({
+ key,
+ request: { ...helper, modelId: REGEN_SMOOTH_MODEL, op: "interpolate", inputs: { video: c.url }, params: { targetFps: REGEN_FPS, numOutputs: 1 }, step: { label: `Segment ${i + 1} to ${REGEN_FPS} fps`, index: 900 + i, of: 1000 } },
+ });
+ return { key };
+ });
+ const stitch = planStitch(input, refs, suffix, { resolution: REGEN_FINISH_TIER });
+ return { steps: [...smooth, ...stitch.steps], final: stitch.final };
+}
+
/** The whole session: every segment's first take, the stitch and the soundtrack. */
export function planShorts(input: ShortsPlanInput): { segments: ShortsSegment[]; steps: PlanStep[]; takes: TakeKeys[]; final?: string } {
const segments = planSegments(input.range, input.engine, { modelId: input.modelId, fps: input.source.fps });
@@ -788,7 +861,7 @@ export function planShorts(input: ShortsPlanInput): { segments: ShortsSegment[];
// Sessions (stored by src/server/shorts.ts, read by the page)
export interface ShortsTake {
- /** The generations of this take's steps, by role. */
+ /** The generations of this take's steps, by role (an enhanced take keeps the cut of the take it was made from). */
cut: string;
/** Cloud: the cut cropped to the output ratio. */
fit?: string;
@@ -796,6 +869,8 @@ export interface ShortsTake {
still?: string;
frame?: string;
look: string;
+ /** "Enhance (H3 regenerate)": the take this one redraws (its look), and RIFE's 24 fps step before the redraw. */
+ enhance?: { from: string; smooth?: string };
createdAt: number;
}
@@ -902,7 +977,14 @@ export function chainState(steps: { g?: Generation; label: string }[]): ChainSta
}
/** A take's steps with their labels. */
-export function takeSteps(t: Pick<ShortsTake, "cut" | "fit" | "still" | "frame" | "look">, gens: Record<string, Generation>): { g?: Generation; label: string }[] {
+export function takeSteps(t: Pick<ShortsTake, "cut" | "fit" | "still" | "frame" | "look" | "enhance">, gens: Record<string, Generation>): { g?: Generation; label: string }[] {
+ if (t.enhance) {
+ return [
+ { g: gens[t.enhance.from], label: "Restyling" },
+ ...(t.enhance.smooth ? [{ g: gens[t.enhance.smooth], label: `Smoothing to ${REGEN_FPS} fps` }] : []),
+ { g: gens[t.look], label: "Enhancing" },
+ ];
+ }
return [
{ g: gens[t.cut], label: "Cutting the segment" },
...(t.fit ? [{ g: gens[t.fit], label: "Cropping the segment" }] : []),
diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.ts
index eece3a23..817d8a36 100644
--- a/src/lib/output-actions.ts
+++ b/src/lib/output-actions.ts
@@ -12,7 +12,7 @@ import { PRESETS as GRADE_PRESETS } from "./grade";
import { storedPath } from "./share";
import { decodeMoss, LAYOUT_PARAM, readLayout, type LayoutDraft } from "./layout-prompt";
import { REMOVE_DIALOGUE_FEATURE } from "./av/remove-dialogue";
-import { canRerender, regenerateFamily, regenerateHref, rerenderLabel } from "./catalog/regenerate";
+import { canEnhance, canRerender, ENHANCE_LABEL, regenerateFamily, regenerateHref, rerenderLabel } from "./catalog/regenerate";
import { CLEAN_FEATURE } from "./av/clean-voice";
export type OutputActionId =
@@ -47,6 +47,7 @@ export type OutputActionId =
| "finalize"
| "regenerate"
| "rerender-2k"
+ | "enhance-h3"
| "compare"
| "reuse"
| "make-skill"
@@ -188,6 +189,8 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
if (o.kind === "video" && g.status === "succeeded") {
if (canRerender(g, ctx.engineMode)) out.push({ id: "rerender-2k", label: rerenderLabel(g.modelId), placement: "menu" });
else if ((g.engine === "open" || g.feature === "upload") && ctx.engineMode !== "cloud") out.push({ id: "regenerate", label: "Regenerate in 2K", placement: "menu", href: regenerateHref(o.url, g.feature === "upload" ? null : g.request.prompt) });
+ // An Edit video result (up to 15 s): redrawn at 1080p on your GPU, from the edit's own words.
+ if (canEnhance(g, o, ctx.engineMode)) out.push({ id: "enhance-h3", label: ENHANCE_LABEL, placement: "menu" });
}
if (ctx.compare) out.push({ id: "compare", label: "Compare with original", placement: "menu" });
if (ctx.reuse) out.push({ id: "reuse", label: "Reuse settings", placement: "menu" });
diff --git a/src/server/shorts.ts b/src/server/shorts.ts
index 81c360a3..bfefe148 100644
--- a/src/server/shorts.ts
+++ b/src/server/shorts.ts
@@ -4,6 +4,7 @@ import { getModel } from "@/lib/catalog";
import { maxRefsFor, reframes, resolutionFor, sourceSeconds } from "@/lib/catalog/shorts-models";
import {
clipLengthProblem,
+ ENHANCE_COPY,
clipShapeProblem,
customPresetName,
getShortsPreset,
@@ -12,8 +13,9 @@ import {
needsFit,
originalSegmentProblem,
planSegments,
+ planEnhance,
+ planFinishedStitch,
planShorts,
- planStitch,
planTake,
rangeProblem,
sessionPlanInput,
@@ -444,7 +446,7 @@ function takeOf(t: TakeKeys, id: (key: string) => string, createdAt: number): Sh
/** Every generation a session made. */
export function sessionIds(s: ShortsSession): string[] {
const ids = [
- ...s.segments.flatMap((g) => g.takes.flatMap((t) => [t.cut, ...(t.fit ? [t.fit] : []), ...(t.still ? [t.still] : []), ...(t.frame ? [t.frame] : []), t.look])),
+ ...s.segments.flatMap((g) => g.takes.flatMap((t) => [t.cut, ...(t.fit ? [t.fit] : []), ...(t.still ? [t.still] : []), ...(t.frame ? [t.frame] : []), ...(t.enhance?.smooth ? [t.enhance.smooth] : []), t.look])),
...s.stitches.flatMap((x) => [...x.ids, x.final]),
];
return [...new Set(ids)];
@@ -545,6 +547,40 @@ export function regenerateSegment(id: string, index: number): ShortsSessionView
return getSession(id);
}
+/**
+ * Enhance (H3 regenerate) one segment's chosen take: RIFE to 24 fps, then Open-H3 Regenerate at 1080p from the segment's
+ * restyle words (planEnhance). On your GPU only, so an open-source short; Engine mode "Paid APIs only" refuses it. The
+ * result is a new take beside the others, to compare and pick.
+ */
+export function enhanceSegment(id: string, index: number): ShortsSessionView {
+ const s = readSession(id);
+ const seg = segmentAt(s, index);
+ if (s.engine !== "open") throw new ShortsError(ENHANCE_COPY.cloudSession, 422);
+ checkEngine("open");
+ const take = seg.takes.find((t) => t.look === seg.primary);
+ if (!take) throw new ShortsError(ENHANCE_COPY.notReady, 409);
+ if (take.enhance) throw new ShortsError(ENHANCE_COPY.done, 409);
+ const g = getGeneration(take.look);
+ const url = g?.status === "succeeded" ? g.outputs.find((o) => o.kind === "video")?.url : undefined;
+ if (!url) throw new ShortsError(ENHANCE_COPY.notReady, 409);
+ let plan: ReturnType<typeof planEnhance>;
+ let pipeline;
+ try {
+ plan = planEnhance(sessionPlanInput(s), seg, { url }, `e${seg.takes.length}`);
+ pipeline = createPipeline(plan.steps, { batchId: s.batchId });
+ } catch (e) {
+ throw new ShortsError((e as Error).message, 422);
+ }
+ const next: ShortsTake = {
+ cut: take.cut,
+ look: pipeline.byKey[plan.keys.look].id,
+ enhance: { from: take.look, ...(plan.keys.smooth ? { smooth: pipeline.byKey[plan.keys.smooth].id } : {}) },
+ createdAt: Date.now(),
+ };
+ saveSession({ ...s, segments: s.segments.map((x, i) => (i === index ? { ...x, takes: [...x.takes, next] } : x)) });
+ return getSession(id);
+}
+
/** Use another take of a segment in the stitch. */
export function makePrimary(id: string, index: number, lookId: string): ShortsSessionView {
const s = readSession(id);
@@ -564,14 +600,15 @@ export function stitchSession(id: string): ShortsSessionView {
if (g.status === "queued" || g.status === "running") throw new ShortsError(`Segment ${i + 1} is still rendering`, 409);
const url = g.outputs.find((o) => o.kind === "video")?.url;
if (g.status !== "succeeded" || !url) throw new ShortsError(`Segment ${i + 1} didn't render — regenerate it first`, 409);
- return { url };
+ return { url, enhanced: !!seg.takes.find((t) => t.look === seg.primary)?.enhance };
});
// A second "Stitch again" while the same takes are still being stitched would pay for the same video twice.
const last = s.stitches[s.stitches.length - 1];
if (last && stitchCurrent(s) && [...last.ids, last.final].some((gid) => ["queued", "running"].includes(getGeneration(gid)?.status ?? ""))) {
throw new ShortsError("These takes are already being stitched", 409);
}
- const plan = planStitch(sessionPlanInput(s), clips, `-s${s.stitches.length}`);
+ // Enhanced takes are 1080p at 24 fps: the others are brought to 24 fps and the join runs at 1080p (planFinishedStitch).
+ const plan = planFinishedStitch(sessionPlanInput(s), clips, `-s${s.stitches.length}`);
const now = Date.now();
let stitch: ShortsStitch;
if (!plan.steps.length || !plan.final) {
diff --git a/tests/shorts-api.test.ts b/tests/shorts-api.test.ts
index 8d1ea892..0dfbd65a 100644
--- a/tests/shorts-api.test.ts
+++ b/tests/shorts-api.test.ts
@@ -23,6 +23,7 @@ const sessionRoute = await import("@/app/api/shorts/sessions/[id]/route");
const regenRoute = await import("@/app/api/shorts/sessions/[id]/segments/[index]/route");
const primaryRoute = await import("@/app/api/shorts/sessions/[id]/segments/[index]/primary/route");
const stitchRoute = await import("@/app/api/shorts/sessions/[id]/stitch/route");
+const enhanceRoute = await import("@/app/api/shorts/sessions/[id]/segments/[index]/enhance/route");
const estimateRoute = await import("@/app/api/shorts/estimate/route");
const presetsRoute = await import("@/app/api/shorts/presets/route");
const mixedRoute = await import("@/app/api/mixed-media/route");
@@ -265,6 +266,47 @@ describe("Shorts sessions", () => {
expect(frame.request.inputs?.images?.[0]).toMatch(/^\/api\/files\//);
});
+ it("enhances a segment on your GPU (RIFE to 24 fps, then Regenerate at 1080p) and stitches the mix at one rate", async () => {
+ const s = await shorts.createSession(body({ engine: "open" }) as never);
+ const before = await settle(s.segments[1].primary);
+ expect(before.status).toBe("succeeded");
+ const res = await enhanceRoute.POST(json("POST", { requestId: "enhance-1" }), params({ id: s.id, index: "1" }));
+ expect(res.status).toBe(201);
+ const v = await res.json();
+ const take = v.segments[1].takes.at(-1);
+ expect(take.enhance.from).toBe(s.segments[1].primary);
+ expect(gens.getGeneration(take.enhance.smooth)).toMatchObject({ modelId: "oss-rife", op: "interpolate", request: { params: { targetFps: 24 } } });
+ const regen = gens.getGeneration(take.look)!;
+ expect(regen).toMatchObject({ modelId: "oss-h3-regenerate", op: "upscale-video", engine: "open", feature: "shorts" });
+ expect(regen.request.params).toMatchObject({ resolution: "1080p", extra: { startSigma: 0.8, draftFrom: "other" } });
+ expect(regen.request.prompt).toBe(before.request.prompt);
+ expect(dependsOn(take.look)).toEqual([take.enhance.smooth]);
+ // The same request id answers with the first take; an enhanced take isn't enhanced again.
+ const same = await (await enhanceRoute.POST(json("POST", { requestId: "enhance-1" }), params({ id: s.id, index: "1" }))).json();
+ expect(same.segments[1].takes).toHaveLength(2);
+ expect(await settle(take.look)).toMatchObject({ status: "succeeded" });
+ const picked = shorts.makePrimary(s.id, 1, take.look);
+ expect((await enhanceRoute.POST(json("POST"), params({ id: s.id, index: "1" }))).status).toBe(409);
+ // The stitch: the other segments to 24 fps, the join at 1080p, each clip in its place.
+ await settle(s.stitches[0].final);
+ const st = await (await stitchRoute.POST(json("POST"), params({ id: picked.id }))).json();
+ const ids: string[] = st.stitches.at(-1).ids;
+ const smooth = ids.map((id) => gens.getGeneration(id)!).filter((g) => g.modelId === "oss-rife");
+ expect(smooth).toHaveLength(2);
+ const join = ids.map((id) => gens.getGeneration(id)!).find((g) => g.op === "concat")!;
+ expect(join.request.params?.resolution).toBe("1080p");
+ expect(await settle(st.stitches.at(-1).final)).toMatchObject({ status: "succeeded" });
+ const joined = gens.getGeneration(join.id)!;
+ const regenUrl = gens.getGeneration(take.look)!.outputs[0].url;
+ expect(joined.request.inputs?.videos?.[1]).toBe(regenUrl);
+ // A cloud short: Enhance runs on your GPU only.
+ const cloud = await shorts.createSession(body() as never);
+ await settle(cloud.segments[0].primary);
+ const refused = await enhanceRoute.POST(json("POST"), params({ id: cloud.id, index: "0" }));
+ expect(refused.status).toBe(422);
+ expect((await refused.json()).error).toMatch(/runs on your GPU \(open source\)/);
+ });
+
it("runs Fuobe Shorts in the cloud by default: cut → first frame → Qwen edit in the look → Wan Fun VACE by depth → join → sound", async () => {
const rest = { ...body(), modelId: undefined };
const s = await shorts.createSession(rest as never);