// api.js — the only module that talks to the backend. // // Two implementations behind one interface: // createApi({ mode: "mock" }) — fully offline; simulates delays, progress and every failure mode. // createApi({ mode: "gradio" }) — skeleton over @gradio/client with a TODO on each call. // // app.js never calls fetch() and never touches Gradio directly. Everything below the line // "CONTRACT" is the interface the UI relies on; the mock is the reference behaviour. /* ============================================================================================ * CONTRACT (JSDoc types) * ==========================================================================================*/ /** * A file coming FROM the backend. The adapter always downloads it into a Blob, so the UI can * keep its own copy (IndexedDB) and resend it later — server files are temporary. * @typedef {Object} FileOut * @property {Blob} blob * @property {string} name * @property {"clip"|"draft"|"context"|"refineContext"|"take"|"lora"} kind * @property {Object} [meta] Same shape as InspectResult.meta. */ /** * A file going TO the backend. Always a Blob/File the UI holds locally; the adapter uploads it on * every call that needs it (so a restarted Space never sees a stale server path). * @typedef {Blob|File} FileIn */ /** * @typedef {Object} LoraSlot * @property {string} id Catalog id ("turbo4-larryvrh", …) or "custom" (link) or "trained" (made here) or "file" (user's own .safetensors). * @property {string} name Display name. * @property {number} weight 0–2, default 1.0. * @property {string} [url] Custom URL (CivitAI / Hugging Face). May contain a token — never display unmasked. * @property {FileIn} [file] Trained LoRA file (.safetensors) held by the browser. */ /** * @typedef {Object} Status * @property {"loading"|"ready"|"error"} model * @property {string} message Human sentence, e.g. "Loading weights · 2 of 5". * @property {number} queue People waiting for this Space. * @property {number} quotaMultiplier 2 on xlarge GPUs (quota is charged 2× GPU time). * @property {string} bootId [EXTENSION] changes when the Space restarts → server files are gone. * @property {number|null} capSeconds [EXTENSION] per-request GPU reservation limit if known (~90–130 s). */ /** * @typedef {Object} GenerateRequest * @property {string} prompt * @property {FileIn} [firstFrame] * @property {FileIn} [lastFrame] * @property {"16:9"|"9:16"|"1:1"|"4:3"|"3:4"|"21:9"} ratio * @property {number} megapixels 0.15–1.03 — the draft canvas (or the clip canvas when upscale = 1). * @property {number} duration 2–14, step 0.5 (seconds asked; frames snap to 17n+5 at 24 fps). * @property {number} steps 1–30 (used when upscale = 1). * @property {number|null} seed null = random. * @property {number} upscale 1 = off, 1.5, 2, 2.5, 3. * @property {number} draftSteps 4–30 (upscale only). * @property {string} refineLadder "8x0.30" | "6x0.30" | "5x0.25" | "10x0.35" | "regen3" (upscale only). * @property {boolean} draftOnly Stop after the draft (upscale only). * @property {FileIn} [continueFrom] context (clip take) or draft (draft take) of the previous segment, * or [EXTENSION] an mp4 made by this Space (the backend encodes its end, ~5 s GPU). * @property {number} [continueSegment] [EXTENSION] segment number this request makes (for the file's embedded record). * @property {string} [takeId] [EXTENSION] take id to embed in the outputs. * @property {LoraSlot[]} loras Exactly what is in the rack, ≤ 5. */ /** * @typedef {Object} Geometry * @property {number} width * @property {number} height * @property {number} frames 17n+5 * @property {number} fps 24 * @property {number} seconds frames / fps * @property {{width:number,height:number}} [draft] present when upscale > 1 * @property {number} [newSeconds] continuation only: seconds actually added (duration − 0.92) */ /** * @typedef {Object} Notice * @property {"upscaleLowered"|"stepsLowered"|"info"} kind * @property {string} text Human sentence ready to show. * @property {*} [from] * @property {*} [to] */ /** * @typedef {Object} Estimate * @property {number} gpuSeconds * @property {number} quotaSeconds gpuSeconds × quotaMultiplier * @property {boolean} fits false = does not fit the reservation at any multiplier * @property {string[]} stepDown What to reduce when !fits, e.g. "Duration 5 s → 3.5 s". * @property {Geometry} geometry [EXTENSION] authoritative pixels/frames for display. * @property {number} [upscaleUsed] [EXTENSION] multiplier the backend will actually use (auto-lowered). * @property {Notice[]} notices [EXTENSION] */ /** * @typedef {Object} Timing * @property {number} gpuSeconds * @property {number} quotaSeconds * @property {number} wallSeconds */ /** * @typedef {Object} GenerateResult * @property {FileOut} video The clip, or the draft preview when draftOnly. * @property {number} seed * @property {Geometry} geometry * @property {Timing} timing * @property {{name:string,weight:number}[]} lorasApplied * @property {string} report Short plain-text log for the "details" fold. * @property {FileOut} [context] Continuation handle for a clip take. * @property {FileOut} [draft] Draft latent (refine source and continuation handle for a draft take). * @property {Notice[]} notices [EXTENSION] e.g. multiplier auto-lowered. */ /** * @typedef {Object} RefineRequest * @property {FileIn} source draft or clip made by this Space * @property {string} [clipPrompt] only when the clip carries no metadata * @property {FileIn} [refineContext] previous segment's refine context (take chains), or [EXTENSION] its refined/finished mp4 * @property {number} upscale * @property {string} refineLadder * @property {LoraSlot[]} loras */ /** * @typedef {Object} RefineResult * @property {FileOut} video * @property {number} seed * @property {Geometry} geometry * @property {Timing} timing * @property {{name:string,weight:number}[]} lorasApplied * @property {string} report * @property {FileOut} refineContext * @property {Notice[]} notices */ /** * @typedef {Object} InspectResult * @property {"draft"|"clip"|"context"|"refineContext"|"take"|"lora"|"backup"|"unknown"} kind "backup" is recognised in the browser * @property {boolean} [hasRecord] [EXTENSION] mp4 carries the embedded record (prompt, settings, LoRA) * @property {boolean} [canContinue] [EXTENSION] a take can continue from the end of this mp4 * @property {{width:number,height:number}} [continueCanvas] [EXTENSION] draft canvas the continuation runs at * @property {boolean} [scaledDown] [EXTENSION] mp4 is bigger than its draft canvas (an upscaled clip / take) * @property {number} [videoWidth] [EXTENSION] * @property {number} [videoHeight] [EXTENSION] * @property {Object|null} meta { prompt, seed, width, height, frames, segment, takeId, loras, keyframes, steps, upscale, rank, caption } * null = no embedded data (old file / re-encoded by a messenger) * @property {{code:string,message:string}} [error] RESIZED (sides not multiples of 32), FPS (not 24 fps), TOO_SHORT (< 1 s), IMAGE, NOT_FROM_SPACE, DRAFT_PREVIEW */ /** * @typedef {Object} Progress * @property {string} stage "waiting for a GPU" | "encoding the prompt" | "loading LoRA " | "activating N LoRA" | * "draft" | "generating" | "upscaling the latent" | "refine" | "decoding" | "encoding the clip" | * "uploading inputs" | "encoding the input clip" (reading an mp4 to continue from, before generation/refine) | * "encoding images" | "training" | "saving LoRA" * @property {number} step * @property {number} total 0 = indeterminate * @property {number} elapsedSeconds * @property {number} stageSeconds * @property {boolean} stalled stage hasn't moved > 60 s (never for "encoding the prompt"/"waiting for a GPU") * @property {"ok"|"reconnecting"} [connection] [EXTENSION] * @property {number} [queuePosition] [EXTENSION] while waiting for a GPU * @property {number} [loss] training only */ /** * @typedef {Object} TrainParams * @property {FileIn[]} images * @property {FileIn[]} videos * @property {number} framesPerClip 4–24 * @property {string} caption Must contain the invented name. * @property {string} name [EXTENSION] the invented name (trigger word) — used to name the file. * @property {string} ratio * @property {8|16|32} rank * @property {0.3|0.5} megapixels * @property {number} steps 100–1500; with startFrom = steps to ADD * @property {FileIn} [startFrom] LoRA file to continue training (rank/caption are taken from it) */ /** * @typedef {Object} TrainRun * @property {string} runId * @property {string} name * @property {"encoding"|"training"|"done"} phase * @property {number} encoded * @property {number} encodeTotal * @property {number} step * @property {number} steps * @property {number[]} loss one value per finished chunk/log point * @property {number} chunkSeconds ~85 GPU seconds per trainStep call * @property {number} gpuSecondsUsed */ /** * @typedef {Object} OpOptions * @property {(p:Progress)=>void} [onProgress] * @property {AbortSignal} [signal] Aborting stops the BROWSER from waiting. It does not stop GPU work already running, * and that work is still billed. The UI says so. */ /** * Errors are thrown as ApiError with a stable `code`. The UI maps codes to human text. * Codes: CANCELLED, MODEL_NOT_READY, QUOTA, TOO_LONG, ENCODER_DOWN, NETWORK, SERVER_RESTARTED, * GPU_ABORTED, TOKEN_EXPIRED, DOWNLOAD_FAILED, EMPTY_RESULT, BAD_FILE, BAD_URL, RUN_GONE, UNKNOWN */ export class ApiError extends Error { /** @param {string} code @param {string} message @param {Object} [extra] */ constructor(code, message, extra = {}) { super(message); this.name = "ApiError"; this.code = code; /** seconds until the quota resets, if the server said */ this.retryAfterSeconds = extra.retryAfterSeconds ?? null; /** for TOO_LONG */ this.stepDown = extra.stepDown ?? []; this.detail = extra.detail ?? ""; } } /** * @typedef {Object} Api * @property {"mock"|"gradio"} mode * @property {() => Promise} status * @property {(req: GenerateRequest|{op:"refine"}&RefineRequest|{op:"train"}&TrainParams) => Promise} estimate * @property {(req: GenerateRequest, o?: OpOptions) => Promise} generate * @property {(file: FileIn) => Promise} inspectFile * @property {(req: RefineRequest, o?: OpOptions) => Promise} refine * @property {(take: FileIn, segment: FileIn, o?: OpOptions) => Promise<{video: FileOut}>} join * @property {(video: FileIn, startFrame: number, endFrame: number|null, o?: OpOptions) => Promise<{video: FileOut}>} trim * @property {(video: FileIn, o?: OpOptions) => Promise<{video: FileOut, note: string}>} conform * [EXTENSION] Any video put on the Space's grid: sides cropped to multiples of 32, 24 fps. CPU only. * [EXTENSION] Frames [startFrame, endFrame) of an mp4 as a clip of its own (24 fps frames). CPU only. * @property {(p: TrainParams, o?: OpOptions) => Promise} trainBegin * @property {(run: TrainRun, o?: OpOptions) => Promise} trainStep * @property {(run: TrainRun, o?: OpOptions) => Promise<{lora: FileOut, report: string}>} trainEnd * @property {(runId: string) => Promise} trainResume * @property {(file: FileIn) => Promise<{slotSource:string,label:string,trigger?:string,caption?:string,rank:number,steps:number,sizeMb:number}|{error:{code:"NOT_LORA"|"WRONG_MODEL"|"DAMAGED"|"TOO_BIG",message:string}}>} addLoraFile * [EXTENSION] CPU-only check + placement of a user's .safetensors. No GPU, no quota. * @property {(slot: LoraSlot) => Promise<{card:{title:string,description:string,sizeMB:number,loadSeconds:number,trigger?:string}}>} prepareLora */ /* ============================================================================================ * Domain constants and helpers (mirror backend rules; estimate() stays authoritative) * ==========================================================================================*/ export const FPS = 24; export const CARRY_FRAMES = 22; export const CARRY_SECONDS = 0.92; export const RATIOS = { "16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1, "4:3": 4 / 3, "3:4": 3 / 4, "21:9": 21 / 9 }; export const LADDERS = [ { id: "8x0.30", label: "8 steps · denoise 0.30", steps: 8 }, { id: "6x0.30", label: "6 steps · denoise 0.30", steps: 6 }, { id: "5x0.25", label: "5 steps · denoise 0.25", steps: 5 }, { id: "10x0.35", label: "10 steps · denoise 0.35", steps: 10 }, { id: "regen3", label: "Regenerate · 3 steps (NVIDIA)", steps: 3, refineOnly: true }, ]; export const UPSCALES = [1, 1.5, 2, 2.5, 3]; export const CATALOG = [ { id: "turbo4-larryvrh", name: "Turbo 4-step · larryvrh", group: "Turbo", steps: 4, sizeMB: 612 }, { id: "turbo4-lightx2v", name: "Turbo 4-step · lightx2v", group: "Turbo", steps: 4, sizeMB: 598 }, { id: "turbo8-lightx2v", name: "Turbo 8-step · lightx2v", group: "Turbo", steps: 8, sizeMB: 598 }, { id: "turbo4-instantx", name: "Turbo 4-step · InstantX", group: "Turbo", steps: 4, sizeMB: 640 }, { id: "turbo4-pika-lite", name: "Turbo 4-step · Pika Flex lite", group: "Turbo", steps: 4, sizeMB: 310 }, { id: "turbo4-pika", name: "Turbo 4-step · Pika Flex", group: "Turbo", steps: 4, sizeMB: 3910 }, { id: "realism-people", name: "Realism · People", group: "Style", sizeMB: 288 }, { id: "motion-adapter", name: "Motion Adapter", group: "Motion", sizeMB: 154 }, { id: "spatial-physics", name: "Spatial Physics", group: "Motion", sizeMB: 302 }, { id: "wushu-action", name: "Wushu Action", group: "Motion", sizeMB: 221 }, { id: "lineart-anime", name: "Lineart Anime", group: "Style", sizeMB: 196 }, ]; const snap32 = (v) => Math.max(32, Math.round(v / 32) * 32); const MIN_MP = 0.15, MAX_MP = (1344 * 768) / 1e6; /** Python's round(): halves go to the even neighbour - the backend's grid arithmetic uses it. */ const pyRound = (v) => { const f = Math.floor(v), d = v - f; return d > 0.5 || (d === 0.5 && f % 2 !== 0) ? f + 1 : f; }; /** Canvas pixels for a ratio and area - the backend's canvas_for: height from the clamped area, both axes snapped. 1.03 MP at 16:9 → 1344×768. */ export function canvasSize(ratio, megapixels) { const r = RATIOS[ratio] ?? RATIOS["16:9"]; const area = Math.min(Math.max(+megapixels || 0.3, MIN_MP), MAX_MP) * 1e6; const h = Math.sqrt(area / r); return { width: snap32(h * r), height: snap32(h) }; } /** Frames snapped UP to the next 17n+5 - the backend's snap_frames. */ export function framesFor(seconds) { let f = Math.max(1, Math.round((+seconds || 0) * FPS)); // NaN would never reach 17n+5 and hang the page while (f % 17 !== 5) f++; return f; } /** The refine canvas - the backend's upscaled_canvas: both axes chosen together on the 32 grid, so the picture is not stretched. */ export function upscaledSize(width, height, factor) { const uh = Math.max(1, Math.floor(height / 32)), uw = Math.max(1, Math.floor(width / 32)); let best = null; for (const dh of [-1, 0, 1]) for (const dw of [-1, 0, 1]) { const ch = Math.max(1, pyRound(uh * factor) + dh), cw = Math.max(1, pyRound(uw * factor) + dw); const bh = ch / uh, bw = cw / uw; const skew = Math.abs(bh - bw) / ((bh + bw) / 2), err = Math.abs(bh * bw - factor * factor); if (!best || skew < best.skew || (skew === best.skew && err < best.err)) best = { skew, err, ch, cw }; } return { width: best.cw * 32, height: best.ch * 32 }; } /** Full geometry as the UI should display it until estimate() answers (estimate stays authoritative). */ export function geometryFor({ ratio, megapixels, duration, upscale = 1, continuation = false }) { const base = canvasSize(ratio, megapixels); const frames = framesFor(duration); const g = { width: base.width, height: base.height, frames, fps: FPS, seconds: +(frames / FPS).toFixed(2) }; if (upscale > 1) { g.draft = { ...base }; const up = upscaledSize(base.width, base.height, upscale); g.width = up.width; g.height = up.height; } if (continuation) g.newSeconds = +Math.max(0, (frames - CARRY_FRAMES) / FPS).toFixed(2); return g; } /** Hide tokens in URLs: ?token=abcdef1234 → ?token=••••1234 */ export function maskUrl(url = "") { return String(url).replace(/([?&](?:token|api_key|apikey|key)=)([^&#]+)/gi, (_, k, v) => k + "••••" + v.slice(-4)); } /* ============================================================================================ * Shared small utilities * ==========================================================================================*/ function sleep(ms, signal) { return new Promise((resolve, reject) => { if (signal?.aborted) return reject(new ApiError("CANCELLED", "Stopped waiting.")); const t = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, ms); function onAbort() { clearTimeout(t); reject(new ApiError("CANCELLED", "Stopped waiting.")); } signal?.addEventListener("abort", onAbort, { once: true }); }); } const rnd = (a, b) => a + Math.random() * (b - a); const uid = () => Math.random().toString(36).slice(2, 10); const lsGet = (k, d) => { try { const v = localStorage.getItem(k); return v ? JSON.parse(v) : d; } catch { return d; } }; const lsSet = (k, v) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch { /* storage unavailable */ } }; /* ============================================================================================ * MOCK implementation * ==========================================================================================*/ /** Scenarios selectable from the dev panel (?dev=1). */ export const MOCK_SCENARIOS = [ { id: "success", label: "Success" }, { id: "tooLong", label: "Reservation too long → auto-lower multiplier" }, { id: "noFit", label: "Doesn't fit at any multiplier" }, { id: "quota", label: "Quota exhausted" }, { id: "stall", label: "Stage stalls (hang)" }, { id: "network", label: "Network drop → reconnect" }, { id: "networkFail", label: "Network lost (fails)" }, { id: "restart", label: "Space restarts mid-job" }, { id: "slowQueue", label: "Slow GPU queue" }, { id: "encoderDown", label: "Text encoder down" }, { id: "emptyResult", label: "Empty result" }, ]; const MAGIC = "MMH3"; /** Mock: "zarya_r16_1400st.safetensors" → { name: "zarya", rank: 16, steps: 1400 }. The real backend reads the file's metadata. */ function loraMetaFromName(n) { const base = n.replace(/\.safetensors$/i, ""); const name = base.split(/_r\d+|_\d+st/)[0] || base; const rank = +(base.match(/_r(\d+)/)?.[1] || 16), steps = +(base.match(/_(\d+)st/)?.[1] || 800); return { name, rank, steps, caption: `a video of ${name}` }; } async function isZip(file) { try { const h = new Uint8Array(await file.slice(0, 4).arrayBuffer()); return h[0] === 0x50 && h[1] === 0x4b && h[2] === 3 && h[3] === 4; } catch { return false; } } function isVideoBlob(f, registry) { return !!f && ((f.type || "").startsWith("video/") || /\.(mp4|webm|mov|m4v)$/i.test(f.name || "") || !!registry?.[f.size]); } /** Reads width/height/duration of a local video, or null if the browser can't decode it. */ function probeVideo(file) { return new Promise((resolve) => { let url; try { url = URL.createObjectURL(file); } catch { return resolve(null); } const v = document.createElement("video"); const done = (r) => { clearTimeout(t); URL.revokeObjectURL(url); resolve(r); }; const t = setTimeout(() => done(null), 1500); v.preload = "metadata"; v.muted = true; v.onloadedmetadata = () => done(v.videoWidth ? { width: v.videoWidth, height: v.videoHeight, duration: v.duration } : null); v.onerror = () => done(null); v.src = url; }); } const pastTense = (n) => (n.kind === "upscaleLowered" ? { ...n, text: `Ran at ${n.to}× — ${n.from}× didn’t fit your per-request GPU limit.` } : n); class MockApi { constructor() { this.mode = "mock"; this.cfg = { scenario: "success", speed: 1, model: "ready", quotaMultiplier: 2, capSeconds: 120, ...lsGet("mmh3.mock", {}) }; this.bootId = lsGet("mmh3.mock.boot", "boot-1"); this.loadingUntil = 0; this.registry = lsGet("mmh3.mock.registry", {}); // size → meta, for clips (we can't embed into mock video) this.runs = lsGet("mmh3.mock.runs", {}); } /* ---- dev controls (not part of the contract) ---- */ configure(patch) { Object.assign(this.cfg, patch); if ("failRefineAt" in patch) this._refineCalls = 0; lsSet("mmh3.mock", this.cfg); if (patch.model === "loading") this.loadingUntil = Date.now() + 15000 / this.cfg.speed; } restartNow() { this.bootId = "boot-" + uid(); lsSet("mmh3.mock.boot", this.bootId); this.runs = {}; lsSet("mmh3.mock.runs", this.runs); this.loadingUntil = Date.now() + 6000 / this.cfg.speed; } /* ---- contract ---- */ /** What account the GPU pass names. The mock is always signed in. */ async whoAmI() { return { state: "user", user: "mock-user" }; } async status() { await sleep(120); let model = this.cfg.model; if (Date.now() < this.loadingUntil) model = "loading"; else if (model === "loading" && this.loadingUntil) { model = "ready"; this.cfg.model = "ready"; } const msg = { loading: "Loading model weights…", ready: "Ready", error: "Model failed to load. The Space owner has to restart it." }[model]; return { model, message: msg, queue: this.cfg.scenario === "slowQueue" ? 7 : Math.floor(rnd(0, 3)), quotaMultiplier: this.cfg.quotaMultiplier, bootId: this.bootId, capSeconds: this.cfg.capSeconds, }; } _cap(req = {}) { const sc = this.cfg.scenario; if (sc === "noFit") return 20; if (sc === "tooLong") { // the backend will lower the multiplier by one notch: cap sits just above the next lower multiplier const lower = UPSCALES.filter((u) => u > 1 && u < (req.upscale || 1)).at(-1); if (lower && !(req.op !== "refine" && req.draftOnly)) return Math.min(this.cfg.capSeconds, Math.round(this._gpuFor({ ...req, upscale: lower })) + 2); return Math.min(this.cfg.capSeconds, 40); } return this.cfg.capSeconds; } _gpuFor(req) { const K = 0.8e-7, KR = 3.7e-8, KD = 1e-7; const custom = (req.loras || []).filter((l) => l.id === "custom" || l.id === "trained").length; const overhead = 6 + custom * 4 + (req.loras?.length || 0) * 1; if (req.op === "refine") { const m = req.sourceMeta || { width: 736, height: 416, frames: 124 }; const px = m.width * m.height * req.upscale * req.upscale; const ladder = LADDERS.find((l) => l.id === req.refineLadder)?.steps ?? 8; return overhead + m.frames * px * ladder * KR + m.frames * px * KD; } const g = geometryFor({ ...req, upscale: req.upscale }); const basePx = (g.draft || g).width * (g.draft || g).height; if (req.upscale > 1) { const draft = g.frames * basePx * req.draftSteps * K; if (req.draftOnly) return overhead + draft + g.frames * basePx * KD; const ladder = LADDERS.find((l) => l.id === req.refineLadder)?.steps ?? 8; const finalPx = g.width * g.height; return overhead + draft + g.frames * finalPx * ladder * KR + g.frames * finalPx * KD; } return overhead + g.frames * basePx * req.steps * K + g.frames * basePx * KD; } _stepDown(req, cap) { const out = []; const fits = (patch) => this._gpuFor({ ...req, ...patch }) <= cap; if (req.op !== "refine") { for (let d = req.duration - 0.5; d >= 2; d -= 0.5) if (fits({ duration: d })) { out.push(`Duration ${req.duration} s → ${d} s`); break; } for (let mp = +(req.megapixels - 0.05).toFixed(2); mp >= 0.15; mp = +(mp - 0.05).toFixed(2)) if (fits({ megapixels: mp })) { out.push(`Area ${req.megapixels} MP → ${mp} MP`); break; } const sk = req.upscale > 1 ? "draftSteps" : "steps"; for (let s = req[sk] - 1; s >= (sk === "steps" ? 1 : 4); s--) if (fits({ [sk]: s })) { out.push(`${sk === "steps" ? "Steps" : "Draft steps"} ${req[sk]} → ${s}`); break; } if (req.upscale > 1 && !req.draftOnly) out.push("Tick “Stop at draft” and upscale later"); } else { out.push("Pick a lighter refine ladder (5 steps · 0.25)"); } if (!out.length) out.push("Shorten the clip or lower the area"); return out; } async estimate(req) { await sleep(60); const cap = this._cap(req); const notices = []; let upscaleUsed = req.upscale ?? 1; let gpu = req.op === "train" ? 0 : this._gpuFor(req); // a training request has no clip geometry let fits = gpu <= cap; if (!fits && upscaleUsed > 1 && !(req.op !== "refine" && req.draftOnly)) { for (const u of UPSCALES.filter((u) => u > 1 && u < req.upscale).reverse()) { const g2 = this._gpuFor({ ...req, upscale: u }); if (g2 <= cap) { upscaleUsed = u; gpu = g2; fits = true; notices.push({ kind: "upscaleLowered", from: req.upscale, to: u, text: `${req.upscale}× doesn’t fit your per-request GPU limit (${cap} s). It will run at ${u}×.` }); break; } } } if (req.readsVideo) gpu += 5; // encoding the input clip if (req.op === "train") { const chunks = Math.ceil((req.steps || 800) / 100) + 1; gpu = chunks * 85; fits = true; } const geometry = req.op === "refine" ? { width: snap32((req.sourceMeta?.width || 736) * upscaleUsed), height: snap32((req.sourceMeta?.height || 416) * upscaleUsed), frames: req.sourceMeta?.frames || 124, fps: FPS, seconds: +((req.sourceMeta?.frames || 124) / FPS).toFixed(2) } : req.op === "train" ? null : geometryFor({ ...req, upscale: upscaleUsed, continuation: !!req.continueFrom }); return { gpuSeconds: Math.round(gpu), quotaSeconds: Math.round(gpu * this.cfg.quotaMultiplier), fits, stepDown: fits ? [] : this._stepDown(req, cap), geometry, upscaleUsed, notices, capSeconds: cap, }; } /** Simulated progress runner. stages: [{name, total, seconds}] */ async _run(stages, { onProgress, signal }, hooks = {}) { const t0 = performance.now(); const sp = this.cfg.speed; const sc = this.cfg.scenario; const emit = (p) => onProgress?.({ connection: "ok", stalled: false, elapsedSeconds: (performance.now() - t0) / 1000, ...p }); let midpointHit = false; for (let si = 0; si < stages.length; si++) { const st = stages[si]; const s0 = performance.now(); const stageSec = () => (performance.now() - s0) / 1000; if (st.name === "waiting for a GPU" && sc === "slowQueue") { for (let q = 7; q >= 1; q--) { emit({ stage: st.name, step: 0, total: 0, stageSeconds: stageSec(), queuePosition: q }); await sleep(2200 / sp, signal); } } if (st.name === "encoding the prompt" && sc === "encoderDown") { emit({ stage: st.name, step: 0, total: 0, stageSeconds: 0 }); await sleep(2500 / sp, signal); throw new ApiError("ENCODER_DOWN", "The external text encoder didn’t answer."); } if (st.name === "waiting for a GPU" && sc === "quota") { emit({ stage: st.name, step: 0, total: 0, stageSeconds: 0 }); await sleep(900 / sp, signal); throw new ApiError("QUOTA", "Daily GPU quota used up.", { retryAfterSeconds: 3 * 3600 + 12 * 60 }); } const total = st.total || 0; const n = Math.max(1, total); for (let i = 0; i <= n; i++) { const step = total ? i : 0; emit({ stage: st.name, step, total, stageSeconds: stageSec(), loss: hooks.loss?.(i) }); // hang if (sc === "stall" && st.name === hooks.stallAt && i === 3) { const h0 = performance.now(); for (;;) { const held = (performance.now() - h0) / 1000; emit({ stage: st.name, step, total, stageSeconds: stageSec() + (held > 4 / sp ? 60 : 0), stalled: held > 4 / sp }); if (held > 30 / sp) throw new ApiError("GPU_ABORTED", "ZeroGPU ended the task after its reservation ran out."); await sleep(500, signal); } } // mid-job events if (!midpointHit && si >= Math.floor(stages.length / 2) && i === Math.floor(n / 2)) { midpointHit = true; if (sc === "network" || sc === "networkFail") { const r0 = performance.now(); while ((performance.now() - r0) / 1000 < 6 / sp) { emit({ stage: st.name, step, total, stageSeconds: stageSec(), connection: "reconnecting" }); await sleep(500, signal); } if (sc === "networkFail") throw new ApiError("NETWORK", "Lost the connection to the Space."); } if (sc === "restart") { this.restartNow(); throw new ApiError("SERVER_RESTARTED", "The Space restarted during the job."); } } if (i < n) await sleep(((st.seconds || 1) * 1000) / n / sp, signal); } } return (performance.now() - t0) / 1000; } _fileOut(kind, meta, name) { const json = MAGIC + JSON.stringify({ kind, meta }); return { blob: new Blob([json], { type: "application/octet-stream" }), name, kind, meta }; } async _clipOut(kind, meta, name, label) { const blob = await makeMockVideo(meta.width, meta.height, label); this.registry[blob.size] = { kind, meta }; lsSet("mmh3.mock.registry", this.registry); const ext = blob.type.includes("mp4") ? "mp4" : blob.type.includes("webm") ? "webm" : "png"; return { blob, name: `${name}.${ext}`, kind, meta }; } _readMeta(file) { return new Promise((resolve) => { if (!file || !file.slice) return resolve(null); file.slice(0, 4).text().then(async (head) => { if (head !== MAGIC) return resolve(null); try { resolve(JSON.parse((await file.text()).slice(4))); } catch { resolve(null); } }).catch(() => resolve(null)); }); } async _preflight(req, isRefine) { const s = await this.status(); if (s.model === "error") throw new ApiError("MODEL_NOT_READY", s.message); const est = await this.estimate(isRefine ? { op: "refine", ...req } : req); if (!est.fits) throw new ApiError("TOO_LONG", "Doesn’t fit the per-request GPU limit.", { stepDown: est.stepDown }); return { s, est }; } _loraStages(loras) { const st = []; this.loraUploads ??= {}; const sent = (this.loraUploads[this.bootId] ??= new Set()); for (const l of loras || []) { if (l.file) { // a file from the browser: (re)uploaded once per Space boot const key = `${l.name}:${l.file.size}`; if (!sent.has(key)) { st.push({ name: `uploading LoRA ${l.name}${Object.keys(this.loraUploads).length > 1 ? " (re-sent from this browser)" : ""}`, seconds: 1 }); sent.add(key); } } if (l.id === "custom" || l.id === "trained" || l.id === "file") st.push({ name: `loading LoRA ${l.name}`, seconds: 1.4 }); } if (loras?.length) st.push({ name: `activating ${loras.length} LoRA`, seconds: 0.6 }); return st; } async generate(req, opts = {}) { const { s, est } = await this._preflight(req, false); const u = est.upscaleUsed; const g = est.geometry; let cont = req.continueFrom ? await this._readMeta(req.continueFrom) : null; const contIsVideo = !!req.continueFrom && !cont && isVideoBlob(req.continueFrom, this.registry); if (contIsVideo) cont = { kind: "video", meta: this.registry[req.continueFrom.size]?.meta || { segment: req.continueSegment ? req.continueSegment - 1 : 1 } }; if (req.continueFrom && !cont) throw new ApiError("BAD_FILE", "The continuation file isn’t a draft, a context or a video from this Space."); const stages = [ { name: "waiting for a GPU", seconds: 0.8 }, ...(req.firstFrame || req.lastFrame || req.continueFrom ? [{ name: "uploading inputs", seconds: 0.6 }] : []), ...(contIsVideo ? [{ name: "encoding the input clip", seconds: 1.2 }] : []), ...(s.model === "loading" ? [{ name: "loading the model", seconds: 4 }] : []), { name: "encoding the prompt", seconds: 0.8 }, ...this._loraStages(req.loras), ]; if (u > 1) { stages.push({ name: "draft", total: req.draftSteps, seconds: 3.5 }); if (!req.draftOnly) stages.push({ name: "upscaling the latent", seconds: 0.8 }, { name: "refine", total: LADDERS.find((l) => l.id === req.refineLadder)?.steps || 8, seconds: 3 }); } else stages.push({ name: "generating", total: req.steps, seconds: 4 }); stages.push({ name: "decoding", seconds: 1 }, { name: "encoding the clip", seconds: 0.6 }); const wall = await this._run(stages, opts, { stallAt: u > 1 ? "draft" : "generating" }); if (this.cfg.scenario === "emptyResult") throw new ApiError("EMPTY_RESULT", "The model returned no frames."); const seed = req.seed ?? Math.floor(Math.random() * 2 ** 31); const takeId = req.takeId || cont?.meta?.takeId || uid(); const segment = req.continueSegment || (cont?.meta?.segment || 0) + 1; const draftOnly = u > 1 && req.draftOnly; const outW = draftOnly ? g.draft.width : g.width, outH = draftOnly ? g.draft.height : g.height; const meta = { prompt: req.prompt, seed, width: outW, height: outH, frames: g.frames, segment, takeId, loras: (req.loras || []).map((l) => ({ name: l.name, weight: l.weight })), keyframes: [!!req.firstFrame, !!req.lastFrame], steps: u > 1 ? req.draftSteps : req.steps, upscale: u, ratio: req.ratio, megapixels: req.megapixels, duration: req.duration, }; const kind = draftOnly ? "draft" : "clip"; const video = await this._clipOut(kind === "draft" ? "draftPreview" : "clip", meta, `${kind}_s${segment}_${seed}`, `${draftOnly ? "DRAFT" : "CLIP"} · seg ${segment} · ${outW}×${outH}`); video.kind = kind; const res = { video, seed, geometry: { ...g, width: outW, height: outH }, timing: { gpuSeconds: est.gpuSeconds, quotaSeconds: est.quotaSeconds, wallSeconds: +wall.toFixed(1) }, lorasApplied: meta.loras, notices: est.notices.map(pastTense), report: `seed ${seed}\ncanvas ${outW}×${outH}, ${g.frames} frames\nGPU ${est.gpuSeconds}s × ${s.quotaMultiplier} = ${est.quotaSeconds}s quota`, }; if (u > 1) res.draft = this._fileOut("draft", { ...meta, width: g.draft.width, height: g.draft.height }, `draft_s${segment}_${seed}.mmh3`); if (!draftOnly) res.context = this._fileOut("context", meta, `context_s${segment}_${seed}.mmh3`); return res; } async inspectFile(file) { await sleep(300); const name = (file.name || "").toLowerCase(); if (/\.(h3take|h3backup)$/.test(name) || (await isZip(file))) return { kind: "backup", meta: null }; const emb = await this._readMeta(file); if (emb) return { kind: emb.kind === "draftPreview" ? "clip" : emb.kind, meta: emb.meta }; const reg = this.registry[file.size]; const isVideo = (file.type || "").startsWith("video/") || /\.(mp4|webm|mov|m4v)$/.test(name); if (/\.safetensors$/.test(name)) return { kind: "lora", meta: loraMetaFromName(name) }; if (isVideo || (reg && !file.type)) return this._inspectVideo(file, reg, name); if ((file.type || "").startsWith("image/")) return { kind: "unknown", meta: null, error: { code: "IMAGE", message: "This is a picture, not a clip." } }; return { kind: "unknown", meta: null, error: { code: "NOT_FROM_SPACE", message: "This file wasn’t made by this Space." } }; } /** mp4 checks + what continuing from it would look like. Mock file-name hints: "resized", "30fps", "short", "take". */ async _inspectVideo(file, reg, name) { if (/resized|scaled/.test(name)) return { kind: "clip", meta: null, canContinue: false, error: { code: "RESIZED", message: "This video was resized after export: 1280×720 isn’t a size this Space makes (sides must be multiples of 32)." } }; if (/(25|30|50|60)fps/.test(name)) return { kind: "clip", meta: null, canContinue: false, error: { code: "FPS", message: `This video is ${name.match(/(25|30|50|60)fps/)[1]} fps. Clips from this Space are 24 fps.` } }; if (/short/.test(name)) return { kind: "clip", meta: null, canContinue: false, error: { code: "TOO_SHORT", message: "This video is shorter than 1 second — too short to continue from." } }; if (reg) { const m = reg.meta; const canvas = m.ratio && m.megapixels ? canvasSize(m.ratio, m.megapixels) : { width: m.width, height: m.height }; const out = { kind: reg.kind === "take" ? "take" : "clip", meta: m, hasRecord: true, canContinue: true, continueCanvas: canvas, scaledDown: m.width > canvas.width, videoWidth: m.width, videoHeight: m.height }; if (reg.kind === "draftPreview") out.error = { code: "DRAFT_PREVIEW", message: "This is the preview video of a draft. Upscale needs the draft file itself, or a finished clip.", soft: true }; return out; } const d = (await probeVideo(file)) || { width: 736, height: 416, duration: 5 }; if (d.width % 32 || d.height % 32) return { kind: "clip", meta: null, canContinue: false, error: { code: "RESIZED", message: `This video was resized after export: ${d.width}×${d.height} isn’t a size this Space makes (sides must be multiples of 32).` } }; if (d.duration && d.duration < 1) return { kind: "clip", meta: null, canContinue: false, error: { code: "TOO_SHORT", message: "This video is shorter than 1 second — too short to continue from." } }; return { kind: /take|joined/.test(name) ? "take" : "clip", meta: null, hasRecord: false, canContinue: true, continueCanvas: { width: d.width, height: d.height }, scaledDown: false, videoWidth: d.width, videoHeight: d.height, duration: d.duration }; } /** Checks a .safetensors file on the server's CPU and places it for the stack. Mock name hints: "wrong"/"sdxl"/"flux", "broken"/"damaged", "huge". */ async addLoraFile(file) { await sleep(900 / this.cfg.speed); const name = (file.name || "").toLowerCase(); const emb = await this._readMeta(file); if (!/\.safetensors$/.test(name) && emb?.kind !== "lora") return { error: { code: "NOT_LORA", message: "That isn’t a LoRA file. Choose a .safetensors file." } }; if (/wrong|sdxl|flux|sd15/.test(name)) return { error: { code: "WRONG_MODEL", message: "This LoRA was made for another model — its layers don’t match MiniMax H3." } }; if (/broken|damaged|corrupt/.test(name)) return { error: { code: "DAMAGED", message: "The file is damaged or incomplete (the download may have been cut off)." } }; if (/huge/.test(name) || file.size > 1.5e9) return { error: { code: "TOO_BIG", message: "The file is too big (over 1.5 GB). LoRAs for this model are usually 30–700 MB." } }; const m = emb?.meta || loraMetaFromName(name); this.loraUploads ??= {}; (this.loraUploads[this.bootId] ??= new Set()).add(`${m.name}:${file.size}`); return { slotSource: `upload:${uid()}`, label: m.name, trigger: m.name, caption: m.caption, rank: m.rank, steps: m.steps, sizeMb: Math.max(1, Math.round(file.size / 1e6)) || 1 }; } async refine(req, opts = {}) { const srcMeta = (await this._readMeta(req.source))?.meta || this.registry[req.source?.size]?.meta || null; if (!srcMeta && !req.clipPrompt) throw new ApiError("BAD_FILE", "No prompt in this clip — type it in."); const sourceMeta = srcMeta || { width: 736, height: 416, frames: 124, prompt: req.clipPrompt, seed: 1, segment: 1 }; const { s, est } = await this._preflight({ ...req, sourceMeta }, true); const ctxIsVideo = !!req.refineContext && !(await this._readMeta(req.refineContext)) && isVideoBlob(req.refineContext, this.registry); if (req.refineContext && !ctxIsVideo && !(await this._readMeta(req.refineContext))) throw new ApiError("BAD_FILE", "The refine context isn’t from this Space."); const srcIsVideo = !(await this._readMeta(req.source)); const ladder = LADDERS.find((l) => l.id === req.refineLadder); const stages = [ { name: "waiting for a GPU", seconds: 0.8 }, { name: "uploading inputs", seconds: 0.6 }, ...(ctxIsVideo || srcIsVideo ? [{ name: "encoding the input clip", seconds: 1.2 }] : []), ...(req.clipPrompt ? [{ name: "encoding the prompt", seconds: 0.8 }] : []), ...this._loraStages(req.loras), ...(ladder?.id === "regen3" ? [] : [{ name: "upscaling the latent", seconds: 0.8 }]), { name: "refine", total: ladder?.steps || 8, seconds: 3.5 }, { name: "decoding", seconds: 1 }, { name: "encoding the clip", seconds: 0.6 }, ]; this._refineCalls = (this._refineCalls || 0) + 1; const failHere = this.cfg.failRefineAt && this._refineCalls === this.cfg.failRefineAt; if (failHere) { this.cfg.failRefineAt = 0; lsSet("mmh3.mock", this.cfg); // fail once, so "Resume" works await this._run(stages.slice(0, -3).concat([{ name: "refine", total: 4, seconds: 1.5 }]), opts, {}); throw new ApiError("GPU_ABORTED", "ZeroGPU ended the task before the refine finished."); } const wall = await this._run(stages, opts, { stallAt: "refine" }); if (this.cfg.scenario === "emptyResult") throw new ApiError("EMPTY_RESULT", "The model returned no frames."); const u = est.upscaleUsed; const meta = { ...sourceMeta, prompt: sourceMeta.prompt || req.clipPrompt, width: est.geometry.width, height: est.geometry.height, upscale: u, refined: true, loras: (req.loras || []).map((l) => ({ name: l.name, weight: l.weight })) }; const video = await this._clipOut("clip", meta, `refined_s${meta.segment || 1}_${meta.seed}`, `REFINED ${u}× · seg ${meta.segment || 1} · ${meta.width}×${meta.height}`); return { video, seed: meta.seed, geometry: est.geometry, timing: { gpuSeconds: est.gpuSeconds, quotaSeconds: est.quotaSeconds, wallSeconds: +wall.toFixed(1) }, lorasApplied: meta.loras, notices: est.notices.map(pastTense), report: `refine ${ladder?.label}\n${meta.width}×${meta.height}\nGPU ${est.gpuSeconds}s × ${s.quotaMultiplier} = ${est.quotaSeconds}s quota${req.refineContext ? "\nheld previous refine tail" : ""}`, refineContext: this._fileOut("refineContext", meta, `refctx_s${meta.segment || 1}.mmh3`), }; } async join(take, segment, opts = {}) { await this._run([{ name: "joining (CPU)", seconds: 1.2 }], { ...opts, }, {}); const a = this.registry[take.size]?.meta || {}, b = this.registry[segment.size]?.meta || {}; const meta = { ...b, segments: (a.segments || 1) + 1, kind: "take" }; const v = await this._clipOut("take", meta, `take_${meta.segments}seg`, `TAKE · ${meta.segments} segments`); return { video: { ...v, kind: "take" } }; } async trim(video, startFrame, endFrame, opts = {}) { await this._run([{ name: "cutting the video (CPU)", seconds: 1 }], { ...opts }, {}); const reg = this.registry[video.size]; if (!reg) return { video: { blob: video, name: video.name.replace(/(\.\w+)?$/, `_cut$1`), kind: "clip", meta: null } }; const m = reg.meta || {}; const total = m.frames || Math.round((m.duration || 5) * 24); const end = endFrame == null ? total : Math.min(total, endFrame); const frames = Math.max(1, end - (startFrame || 0)); const meta = { ...m, frames, duration: +(frames / 24).toFixed(2) }; return { video: await this._clipOut("clip", meta, `cut_${startFrame}_${end}`, `CUT ${startFrame}–${end} · ${m.width}×${m.height}`) }; } async conform(video, opts = {}) { await this._run([{ name: "converting the video (CPU)", seconds: 1.5 }], { ...opts }, {}); const d = (await probeVideo(video)) || { width: 736, height: 416, duration: 5 }; const w = Math.floor(d.width / 32) * 32, h = Math.floor(d.height / 32) * 32; const blob = await makeMockVideo(w, h, `CONFORMED · ${w}×${h} · 24 fps`); return { video: { blob, name: (video.name || "video").replace(/\.\w+$/, "").replace(/_?(\d+fps|resized|scaled)/g, "") + "_conformed.mp4", kind: "clip", meta: null }, note: `Converted: ${d.width}x${d.height} -> ${w}x${h} (cropped), 30 -> 24 fps` }; } /** Dev-only: ready-made take segments (draft and, optionally, its refine) without running jobs. */ async fixture({ n, takeId, prompt, refined, clip, upscale = 2, ratio = "16:9", megapixels = 0.3, duration = 5, loras = [] }) { if (clip) { // a finished 1× clip, as if downloaded from Create const g = geometryFor({ ratio, megapixels, duration, upscale: 1 }); const seed = Math.floor(Math.random() * 2 ** 31); const meta = { prompt, seed, width: g.width, height: g.height, frames: g.frames, segment: 1, takeId: takeId || uid(), loras, steps: 6, upscale: 1, ratio, megapixels, duration }; return { clip: await this._clipOut("clip", meta, `clip_${seed}`, `CLIP · ${g.width}×${g.height}`) }; } const g = geometryFor({ ratio, megapixels, duration, upscale }); const seed = Math.floor(Math.random() * 2 ** 31); const meta = { prompt, seed, width: g.draft.width, height: g.draft.height, frames: g.frames, segment: n, takeId, loras, steps: 15, upscale, ratio, megapixels, duration }; const timing = { gpuSeconds: 55, quotaSeconds: 55 * this.cfg.quotaMultiplier, wallSeconds: 41 }; const [dv, rv] = await Promise.all([ this._clipOut("draftPreview", meta, `draft_s${n}_${seed}`, `DRAFT · seg ${n} · ${meta.width}×${meta.height}`), refined ? this._clipOut("clip", { ...meta, width: g.width, height: g.height, refined: true }, `refined_s${n}_${seed}`, `REFINED ${upscale}× · seg ${n} · ${g.width}×${g.height}`) : null, ]); dv.kind = "draft"; const out = { draft: { video: dv, draft: this._fileOut("draft", meta, `draft_s${n}_${seed}.mmh3`), seed, geometry: { ...g, width: meta.width, height: meta.height }, timing, lorasApplied: loras, notices: [], report: "dev preset" } }; if (rv) { const rm = { ...meta, width: g.width, height: g.height, refined: true }; out.refined = { video: rv, seed, geometry: g, timing: { ...timing, gpuSeconds: 48, quotaSeconds: 48 * this.cfg.quotaMultiplier }, lorasApplied: loras, notices: [], report: "dev preset", refineContext: this._fileOut("refineContext", rm, `refctx_s${n}.mmh3`) }; } return out; } _saveRun(run) { this.runs[run.runId] = run; lsSet("mmh3.mock.runs", this.runs); return { ...run }; } async trainBegin(p, opts = {}) { const st = await this.status(); if (st.model === "error") throw new ApiError("MODEL_NOT_READY", st.message); const startMeta = p.startFrom ? (await this.inspectFile(p.startFrom)).meta : null; const encodeTotal = p.images.length + p.videos.length * p.framesPerClip; const run = { runId: "run-" + uid(), name: p.name, phase: "encoding", encoded: 0, encodeTotal, step: 0, steps: p.steps, loss: [], chunkSeconds: 85, gpuSecondsUsed: 0, rank: startMeta?.rank || p.rank, caption: startMeta?.caption || p.caption, continued: !!p.startFrom }; const sc = this.cfg.scenario; if (sc === "quota") { await sleep(800 / this.cfg.speed, opts.signal); throw new ApiError("QUOTA", "Daily GPU quota used up.", { retryAfterSeconds: 2 * 3600 }); } await this._run([{ name: "waiting for a GPU", seconds: 0.8 }, { name: "uploading inputs", seconds: 1 }, { name: "encoding images", total: encodeTotal, seconds: 4 }], opts, { stallAt: "encoding images" }); run.encoded = encodeTotal; run.phase = "training"; run.gpuSecondsUsed += 85; return this._saveRun(run); } async trainStep(run, opts = {}) { if (!this.runs[run.runId]) throw new ApiError("RUN_GONE", "The Space restarted and this training run is gone from the server."); const from = run.step, to = Math.min(run.steps, run.step + 100); let last = run.loss.at(-1) ?? 0.42; const lossAt = (i) => +(Math.max(0.05, last * (1 - 0.004 * i) + rnd(-0.01, 0.01))).toFixed(3); if (this.cfg.scenario === "quota") { await sleep(800 / this.cfg.speed, opts.signal); throw new ApiError("QUOTA", "Daily GPU quota used up.", { retryAfterSeconds: 2 * 3600 }); } // progress shows absolute steps await this._run([{ name: "waiting for a GPU", seconds: 0.6 }, { name: "training", total: to - from, seconds: 3.5 }], { ...opts, onProgress: (p) => opts.onProgress?.(p.stage === "training" ? { ...p, step: from + p.step, total: run.steps } : p), }, { loss: lossAt, stallAt: "training" }); const next = { ...run, step: to, gpuSecondsUsed: run.gpuSecondsUsed + 85, loss: [...run.loss, lossAt(to - from)] }; return this._saveRun(next); } async trainEnd(run, opts = {}) { if (!this.runs[run.runId]) throw new ApiError("RUN_GONE", "The Space restarted and this training run is gone from the server."); await this._run([{ name: "saving LoRA", seconds: 1.2 }], opts, {}); const done = { ...run, phase: "done" }; this._saveRun(done); const lora = this._fileOut("lora", { rank: run.rank, caption: run.caption, steps: run.step, name: run.name }, `${run.name}_r${run.rank}_${run.step}st.safetensors`); return { lora, report: `LoRA ${run.name}: rank ${run.rank}, ${run.step} steps, final loss ${run.loss.at(-1) ?? "—"}` }; } async trainResume(runId) { await sleep(400); const r = this.runs[runId]; if (!r) throw new ApiError("RUN_GONE", "The Space restarted and this training run is gone from the server."); return { ...r }; } async prepareLora(slot) { await sleep(350); const c = CATALOG.find((x) => x.id === slot.id); if (c) return { card: { title: c.name, description: c.group === "Turbo" ? `Speed LoRA. Use ${c.steps} steps (or ${c.steps + 2} for more detail).` : `${c.group} LoRA from the catalog.`, sizeMB: c.sizeMB, loadSeconds: 0 } }; if (slot.id === "trained" || slot.id === "file") return { card: { title: slot.name, description: slot.id === "file" ? "Your file, kept in this browser." : "Trained in this Space. Uses its name as trigger word.", sizeMB: Math.max(1, Math.round((slot.file?.size || 38e6) / 1e6)), loadSeconds: 3, trigger: slot.name } }; const url = slot.url || ""; if (!/^https:\/\/(civitai\.com|huggingface\.co)\//.test(url)) throw new ApiError("BAD_URL", "Only CivitAI or Hugging Face links work here."); if (/civitai/.test(url) && !/token=/.test(url) && /download/.test(url)) { return { card: { title: "CivitAI LoRA", description: "This download may need a CivitAI token (add ?token=… to the link).", sizeMB: 210, loadSeconds: 9 } }; } return { card: { title: decodeURIComponent(url.split("/").filter(Boolean).pop()).slice(0, 40), description: /civitai/.test(url) ? "CivitAI model" : "Hugging Face file", sizeMB: Math.round(rnd(80, 600)), loadSeconds: Math.round(rnd(4, 18)) } }; } } /* A small real video so the player works offline. Falls back to a PNG still. */ async function makeMockVideo(w, h, label) { const scale = Math.min(1, 320 / Math.max(w, h)); const cw = Math.max(64, Math.round((w * scale) / 2) * 2), ch = Math.max(64, Math.round((h * scale) / 2) * 2); const canvas = document.createElement("canvas"); canvas.width = cw; canvas.height = ch; const ctx = canvas.getContext("2d"); const hue = Math.floor(Math.random() * 360); const draw = (t) => { const g = ctx.createLinearGradient(0, 0, cw, ch); g.addColorStop(0, `hsl(${hue},45%,22%)`); g.addColorStop(1, `hsl(${(hue + 60) % 360},45%,32%)`); ctx.fillStyle = g; ctx.fillRect(0, 0, cw, ch); ctx.fillStyle = "rgba(255,255,255,.85)"; ctx.beginPath(); ctx.arc(cw * (0.15 + 0.7 * t), ch * 0.55 + Math.sin(t * 6.28) * ch * 0.12, Math.min(cw, ch) * 0.08, 0, 7); ctx.fill(); ctx.font = `600 ${Math.max(10, Math.round(cw / 22))}px system-ui, sans-serif`; ctx.fillText(label, 10, 10 + Math.max(10, Math.round(cw / 22))); }; draw(0); const types = ["video/mp4;codecs=avc1", "video/mp4", "video/webm;codecs=vp9", "video/webm"]; const type = typeof MediaRecorder !== "undefined" && canvas.captureStream ? types.find((t) => MediaRecorder.isTypeSupported(t)) : null; if (!type) return new Promise((r) => canvas.toBlob((b) => r(b), "image/png")); const rec = new MediaRecorder(canvas.captureStream(24), { mimeType: type, videoBitsPerSecond: 400000 }); const chunks = []; rec.ondataavailable = (e) => e.data.size && chunks.push(e.data); const done = new Promise((r) => (rec.onstop = r)); rec.start(); const t0 = performance.now(), dur = 1500; await new Promise((resolve) => { const tick = () => { const t = (performance.now() - t0) / dur; draw(Math.min(1, t)); if (t < 1) requestAnimationFrame(tick); else resolve(); }; requestAnimationFrame(tick); setTimeout(resolve, dur + 400); // rAF may be throttled in background tabs }); rec.stop(); await done; return new Blob(chunks, { type: type.split(";")[0] }); } /* ============================================================================================ * GRADIO implementation - the Space's endpoints in app.py (gr.Server). Every endpoint takes one * JSON object and answers one; long ones stream {progress} events, then {result}. * The page must be served by the Space itself (inside the HF iframe) so the client gets the * ZeroGPU headers and quota is charged to the visitor. * ==========================================================================================*/ // 2.7.1 carries the "supports-zerogpu-headers" handshake with the Hugging Face page (checked 2026-11-07). const GRADIO_CLIENT_URL = "https://cdn.jsdelivr.net/npm/@gradio/client@2.7.1/dist/browser.js"; let gradioModule = null; // Loaded as soon as the adapter exists, not on first use: the client registers its listener for the Hugging Face // page's ZeroGPU message when the module loads, and a late listener could miss it. /** Endpoints that book ZeroGPU (directly or through the conditioner) and so need the visitor's pass. */ const GPU_ENDPOINTS = new Set(["/generate", "/refine", "/train_begin", "/train_step"]); const loadGradio = () => (gradioModule ??= import(/* @vite-ignore */ GRADIO_CLIENT_URL)); class GradioApi { constructor({ space } = {}) { this.mode = "gradio"; this.space = space || window.location.origin; // served by the Space → same origin this._c = null; this.bootId = null; this._loraSources = new WeakMap(); // Blob → { source, boot }: a LoRA file is uploaded once per Space boot loadGradio().catch(() => {}); } _client() { this._c ??= loadGradio().then(({ Client }) => Client.connect(this.space, { events: ["data", "status"] })); this._c.catch(() => { this._c = null; }); return this._c; } async _upload(file) { const { handle_file } = await loadGradio(); return file instanceof Blob ? handle_file(file) : null; } /** A bare "Failed to fetch" (the browser's own words when the Space doesn't answer, e.g. while it restarts) as a * network error, with the client dropped so the next try connects afresh. */ _netError(e) { if (e instanceof ApiError) return e; const t = String(e?.message || e || ""); if (!/failed to fetch|networkerror|load failed|network/i.test(t)) return e; this._c = null; return new ApiError("NETWORK", "Couldn’t reach the Space — it may be restarting. Wait a minute, then try again."); } /** One endpoint call. Streams `{progress}` to onProgress and returns the `{result}` (or the plain answer). */ /** ZeroGPU refuses a request whose proxy token (handed over by the Hugging Face page when it was sent) expired * while it waited - before any GPU time, so it is sent again, which fetches a fresh token. */ async _call(endpoint, payload, o = {}) { for (let attempt = 0; ; attempt++) { // The first pass the Hugging Face page hands out after a pause can name no account: on 2026-11-09 23:56 a // request went out anonymous and its automatic retry 0.3 s later went out signed in. Asking the page for a // pass first (and dropping it) gives the real request a fresh one; a retry waits a little longer. if (GPU_ENDPOINTS.has(endpoint)) await this._freshPass(attempt ? 1500 : 500); try { return await this._callOnce(endpoint, payload, o); } catch (raw) { const e = this._netError(raw); // Both are refused before any GPU time: an expired pass, or a request that reached ZeroGPU without the // visitor's pass (the Hugging Face page's handshake did not answer in time). A new try asks for a fresh one. if (!["TOKEN_EXPIRED", "NOT_SIGNED_IN"].includes(e?.code) || attempt >= 2 || o.signal?.aborted) throw e; o.onProgress?.({ stage: "renewing the GPU token", step: 0, total: 0, elapsedSeconds: 0, stageSeconds: 0, stalled: false, connection: "ok" }); } } } /** Asks the Hugging Face page for a GPU pass and drops it, then waits `settle` ms. Never throws. */ async _freshPass(settle = 500) { try { if (window.parent === window || !window.supports_zerogpu_headers) return; const host = window.location.hostname; const parent = host.includes(".dev.") ? `https://moon-${host.split(".")[1]}.dev.spaces.huggingface.tech` : host.endsWith(".hf.space") ? "https://huggingface.co" : null; if (!parent) return; await new Promise((done) => { const channel = new MessageChannel(); const timer = setTimeout(() => { channel.port1.close(); done(); }, 3000); channel.port1.onmessage = () => { clearTimeout(timer); channel.port1.close(); done(); }; window.parent.postMessage("zerogpu-headers", parent, [channel.port2]); }); await sleep(settle); } catch { /* the request goes out as it would have */ } } async _callOnce(endpoint, payload, { onProgress, signal } = {}) { let c; try { c = await this._client(); } catch (e) { throw new ApiError("NETWORK", `Can’t reach the Space (${e?.message || e}).`); } if (signal?.aborted) throw new ApiError("CANCELLED", "Stopped waiting."); const job = c.submit(endpoint, payload); const t0 = performance.now(); const onAbort = () => { try { job.cancel(); } catch { /* ignore */ } }; signal?.addEventListener("abort", onAbort, { once: true }); try { for await (const msg of job) { if (signal?.aborted) throw new ApiError("CANCELLED", "Stopped waiting."); if (msg.type === "status") { if (msg.stage === "error") throw mapGradioError(msg); if (msg.stage === "pending" && onProgress) { const s = (performance.now() - t0) / 1000; onProgress({ stage: "waiting for a GPU", step: 0, total: 0, elapsedSeconds: s, stageSeconds: s, stalled: false, queuePosition: msg.position != null ? msg.position + 1 : undefined, connection: "ok" }); } continue; } if (msg.type !== "data") continue; const d = msg.data?.[0]; if (d && typeof d === "object" && d.progress) { onProgress?.({ ...d.progress, connection: "ok" }); continue; } if (d && typeof d === "object" && "result" in d) return d.result; return d; } throw new ApiError("NETWORK", "The connection closed before a result arrived. The GPU job may still have run — check the session list before retrying."); } finally { signal?.removeEventListener("abort", onAbort); } } /** One result file, tried three times: the body read failing midway threw a bare "Failed to fetch" after the GPU * had finished (2026-11-07), and the retry then paid for the whole job again. */ async _file(out, o) { if (!out) return undefined; const t0 = performance.now(); const say = (got, size, attempt) => { const s = (performance.now() - t0) / 1000, mb = (n) => (n / 1048576).toFixed(1); o?.onProgress?.({ stage: `downloading the ${out.kind || "result"}${attempt ? ` (try ${attempt + 1})` : ""}`, step: size ? Math.min(100, Math.round(got / size * 100)) : 0, total: size ? 100 : 0, elapsedSeconds: s, stageSeconds: s, stalled: false, connection: "ok", note: size ? `${mb(got)} of ${mb(size)} MB` : `${mb(got)} MB` }); }; for (let attempt = 0; ; attempt++) { // A download that stops sending bytes is dropped after STALL ms and tried again: with no timeout the page sat on // the GPU's last stage ("done") for good after the server had delivered (2026-11-22). const ctrl = new AbortController(), STALL = 30000; let timer = setTimeout(() => ctrl.abort(), STALL); const kick = () => { clearTimeout(timer); timer = setTimeout(() => ctrl.abort(), STALL); }; const stop = () => ctrl.abort(); o?.signal?.addEventListener("abort", stop, { once: true }); try { say(0, out.size || 0, attempt); const r = await fetch(new URL(out.url, this.space), { cache: "no-store", signal: ctrl.signal }); if (r.status === 404 || r.status === 403) throw new ApiError("SERVER_RESTARTED", "The result file is no longer on the server."); if (!r.ok) throw new Error(`HTTP ${r.status}`); const size = +r.headers.get("content-length") || out.size || 0; let blob; if (r.body?.getReader) { const reader = r.body.getReader(), parts = []; let got = 0, last = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; parts.push(value); got += value.length; kick(); if (performance.now() - last > 400) { last = performance.now(); say(got, size, attempt); } } if (size && got !== size) throw new Error(`got ${got} of ${size} bytes`); blob = new Blob(parts, { type: r.headers.get("content-type") || "" }); } else blob = await r.blob(); return { blob, name: out.name, kind: out.kind, meta: out.meta || undefined }; } catch (e) { if (o?.signal?.aborted) throw new ApiError("CANCELLED", "Stopped waiting."); if (e instanceof ApiError) throw e; if (e?.name === "AbortError") e = new Error(`no data for ${STALL / 1000} s`); // The browser's own reason goes along (2026-11-12: on a phone with 10 GB of storage free, downloads still // failed after about five videos - the reason was never on screen). console.warn("[download]", out.name, `attempt ${attempt + 1}`, e?.name, e?.message); if (attempt >= 2) throw new ApiError("DOWNLOAD_FAILED", `The result was made, but it didn’t download to this browser (${e?.name || "Error"}: ${e?.message || "no reason given"}).`); await new Promise((res) => setTimeout(res, 1500 * (attempt + 1))); } finally { clearTimeout(timer); o?.signal?.removeEventListener("abort", stop); } } } /** A finished job whose files did not all download is kept, so "Try again" with the same request only downloads * them - the GPU does not run, and is not paid for, twice. */ async _deliver(key, run, files) { const kept = this._undelivered; let r = kept && kept.key === key && Date.now() - kept.t < 30 * 60 * 1000 ? kept.r : null; if (!r) r = await run(); this._undelivered = { key, r, t: Date.now() }; const out = await files(r); this._undelivered = null; return out; } /** The rack for the server. A LoRA file goes up once per boot; after that only its server path is sent. */ async _loras(loras = []) { const out = []; for (const l of loras) { const o = { id: l.id, name: l.name, weight: l.weight, url: l.url || null }; if (l.file instanceof Blob) { let known = this._loraSources.get(l.file); if (!known || known.boot !== this.bootId) { const r = await this.addLoraFile(l.file); if (r.error) throw new ApiError("BAD_FILE", `${l.name}: ${r.error.message}`); known = this._loraSources.get(l.file); } o.source = known.source; } out.push(o); } return out; } /** Runs `call(loras)`; once more with fresh uploads if the server lost a LoRA file (a restart). */ async _withLoras(loras, call) { try { return await call(await this._loras(loras)); } catch (e) { if (e?.code !== "LORA_GONE") throw e; for (const l of loras || []) if (l.file instanceof Blob) this._loraSources.delete(l.file); return call(await this._loras(loras)); } } /** * Which account the Hugging Face page puts into the GPU pass, asked the same way the client asks before every GPU * request (a "zerogpu-headers" message with a reply port). The pass is a JWT; its payload's `user` is null for an * anonymous visitor - seen on refused requests on 2026-11-09 from a visitor who was signed in. * @returns {Promise<{state: "user"|"anonymous"|"outside"|"no-handshake"|"no-answer"|"no-token"|"unreadable", user?: string, expiresIn?: number}>} */ async whoAmI() { if (window.parent === window) return { state: "outside" }; const host = window.location.hostname; const parent = host.includes(".dev.") ? `https://moon-${host.split(".")[1]}.dev.spaces.huggingface.tech` : host.endsWith(".hf.space") ? "https://huggingface.co" : null; if (!parent) return { state: "outside" }; try { await this._client(); } catch { /* the handshake starts when the client does; it may still answer */ } for (let i = 0; i < 50 && !window.supports_zerogpu_headers; i++) await sleep(100); if (!window.supports_zerogpu_headers) return { state: "no-handshake" }; const headers = await new Promise((done) => { const channel = new MessageChannel(); const timer = setTimeout(() => { channel.port1.close(); done(null); }, 5000); channel.port1.onmessage = ({ data }) => { clearTimeout(timer); channel.port1.close(); done(data); }; window.parent.postMessage("zerogpu-headers", parent, [channel.port2]); }); if (!headers || typeof headers !== "object") return { state: "no-answer" }; // Header names are case-insensitive, and the page's own spelling is not documented. // The page sends X-ZeroGPU-Token and X-ZeroGPU-UUID (2026-11-09); Hugging Face's proxy turns them into the // X-IP-Token the server reads, and without a valid one mints an IP-only pass with no account. const key = Object.keys(headers).find((k) => k.toLowerCase() === "x-zerogpu-token") || Object.keys(headers).find((k) => k.toLowerCase() === "x-ip-token"); const token = key ? headers[key] : null; if (!token) { console.info("[account] pass answer without x-ip-token; keys:", Object.keys(headers).join(", ") || "(none)"); return { state: "no-token", keys: Object.keys(headers) }; } try { const part = String(token).split(".")[1].replace(/-/g, "+").replace(/_/g, "/"); const payload = JSON.parse(atob(part + "=".repeat((4 - part.length % 4) % 4))); // `user` came as an ~800-character string on 2026-11-09, not a name: JSON, a JWT or base64 JSON is opened; // anything else only says that an account is there. const b64json = (s) => { try { const t = s.replace(/-/g, "+").replace(/_/g, "/"); const v = JSON.parse(atob(t + "=".repeat((4 - t.length % 4) % 4))); return v && typeof v === "object" ? v : null; } catch { return null; } }; const open = (s) => { try { const v = JSON.parse(s); if (v && typeof v === "object") return v; } catch { /* not JSON */ } const p = s.split("."); return (p.length === 3 && b64json(p[1])) || b64json(s); }; const header = key; const fields = Object.keys(payload).join(", "); console.info("[account]", header, "fields:", fields); let u = payload.user ?? payload.username ?? payload.name ?? payload.sub; if (typeof u === "string" && u.length > 40) u = open(u) || "signed in"; const user = !u ? "" : typeof u === "string" ? u : String(u.name || u.username || u.user || u.id || "signed in"); const expiresIn = typeof payload.exp === "number" ? Math.round(payload.exp - Date.now() / 1000) : undefined; return user ? { state: "user", user: String(user), expiresIn, header, fields } : { state: "anonymous", expiresIn, header, fields }; } catch { // The page's X-ZeroGPU-Token is sealed (~1700 characters, not a JWT, 2026-11-09): it is there, but which // account it names only Hugging Face's proxy can tell - the server log does, from the X-IP-Token it mints. return { state: /zerogpu/i.test(key) ? "pass" : "unreadable", header: key, length: String(token).length }; } } async status() { const c = await this._client(); const d = (await c.predict("/status", {})).data[0]; this.bootId = d.boot_id ?? ""; return { model: d.model, message: d.message, queue: d.queue ?? 0, quotaMultiplier: d.quota_multiplier ?? 1, bootId: this.bootId, capSeconds: d.cap_seconds ?? null }; } async estimate(req) { const c = await this._client(); try { return (await c.predict("/estimate", { request: stripFiles(req) })).data[0]; } catch (e) { throw mapGradioError(e); } } async generate(req, o) { const base = { prompt: req.prompt, ratio: req.ratio, megapixels: req.megapixels, duration: req.duration, steps: req.steps, seed: req.seed ?? null, upscale: req.upscale, draftSteps: req.draftSteps, refineLadder: req.refineLadder, draftOnly: !!req.draftOnly, continueSegment: req.continueSegment ?? null, takeId: req.takeId ?? null, firstFrame: await this._upload(req.firstFrame), lastFrame: await this._upload(req.lastFrame), continueFrom: await this._upload(req.continueFrom), }; const key = "generate " + JSON.stringify([base.prompt, base.ratio, base.megapixels, base.duration, base.steps, base.seed, base.upscale, base.draftOnly, base.continueSegment, base.takeId, req.continueFrom?.size ?? null]); return this._deliver(key, () => this._withLoras(req.loras, (loras) => this._call("/generate", { request: { ...base, loras } }, o)), async (r) => ({ video: await this._file(r.video, o), seed: r.seed, geometry: r.geometry, timing: r.timing, lorasApplied: r.lorasApplied, report: r.report, notices: r.notices || [], context: await this._file(r.context, o), draft: await this._file(r.draft, o), })); } async inspectFile(file) { if (/\.(h3take|h3backup)$/i.test(file.name || "") || (await isZip(file))) return { kind: "backup", meta: null }; // backups never go to the server const c = await this._client(); try { return (await c.predict("/inspect_file", { file: await this._upload(file) })).data[0]; } catch (e) { throw mapGradioError(e); } } async refine(req, o) { const base = { source: await this._upload(req.source), clipPrompt: req.clipPrompt || "", refineContext: await this._upload(req.refineContext), upscale: req.upscale, refineLadder: req.refineLadder, }; const key = "refine " + JSON.stringify([req.source?.size ?? null, req.source?.name ?? null, req.refineContext?.size ?? null, base.clipPrompt, base.upscale, base.refineLadder]); return this._deliver(key, () => this._withLoras(req.loras, (loras) => this._call("/refine", { request: { ...base, loras } }, o)), async (r) => ({ video: await this._file(r.video, o), seed: r.seed, geometry: r.geometry, timing: r.timing, lorasApplied: r.lorasApplied, report: r.report, notices: r.notices || [], refineContext: await this._file(r.refineContext, o), })); } async join(take, segment, o) { const r = await this._call("/join", { take: await this._upload(take), segment: await this._upload(segment) }, o); return { video: await this._file(r.video, o) }; } async conform(video, o) { const r = await this._call("/conform", { video: await this._upload(video) }, o); return { video: await this._file(r.video, o), note: r.note }; } async trim(video, startFrame, endFrame, o) { const r = await this._call("/trim", { video: await this._upload(video), startFrame: startFrame || 0, endFrame: endFrame || 0 }, o); return { video: await this._file(r.video, o) }; } async trainBegin(p, o) { const s = 0; o?.onProgress?.({ stage: "uploading inputs", step: 0, total: 0, elapsedSeconds: s, stageSeconds: s, stalled: false }); const params = { images: await Promise.all(p.images.map((f) => this._upload(f))), videos: await Promise.all(p.videos.map((f) => this._upload(f))), framesPerClip: p.framesPerClip, caption: p.caption, name: p.name, ratio: p.ratio, rank: p.rank, megapixels: p.megapixels, steps: p.steps, startFrom: await this._upload(p.startFrom), }; return this._call("/train_begin", { params }, o); } async trainStep(run, o) { o?.onProgress?.({ stage: run.phase === "encoding" ? "encoding images" : "training", step: run.phase === "encoding" ? run.encoded : run.step, total: run.phase === "encoding" ? run.encodeTotal : run.steps, elapsedSeconds: 0, stageSeconds: 0, stalled: false, loss: run.loss?.at(-1) }); return this._call("/train_step", { run_id: run.runId }, o); } async trainEnd(run, o) { const r = await this._call("/train_end", { run_id: run.runId }, o); return { lora: await this._file(r.lora, o), report: r.report }; } async trainResume(runId) { const c = await this._client(); try { return (await c.predict("/train_resume", { run_id: runId })).data[0]; } catch (e) { throw mapGradioError(e); } } async prepareLora(slot) { const c = await this._client(); try { return (await c.predict("/prepare_lora", { slot: { id: slot.id, name: slot.name, url: slot.url || null } })).data[0]; } catch (e) { throw mapGradioError(e); } } async addLoraFile(file) { const c = await this._client(); let r; try { r = (await c.predict("/add_lora_file", { file: await this._upload(file) })).data[0]; } catch (e) { throw mapGradioError(e); } if (r.error) return { error: r.error }; this._loraSources.set(file, { source: r.slot_source, boot: this.bootId }); return { slotSource: r.slot_source, label: r.label, trigger: r.trigger || undefined, caption: r.caption, rank: r.rank, steps: r.steps, sizeMb: r.size_mb }; } } function stripFiles(o) { const out = {}; for (const [k, v] of Object.entries(o || {})) out[k] = v instanceof Blob ? true : Array.isArray(v) ? v.map((x) => (x instanceof Blob ? true : x && typeof x === "object" ? stripFiles(x) : x)) : v && typeof v === "object" ? stripFiles(v) : v; return out; } /** The backend raises gr.Error("CODE: text"), quota errors with "[retry_after=N]". */ function mapGradioError(msg) { if (msg instanceof ApiError) return msg; const t = String(msg?.message || msg || ""); const retry = t.match(/\[retry_after=(\d+)\]/); const guest = /\[guest\]/.test(t); const clean = t.replace(/\s*\[retry_after=\d+\]/, "").replace(/\s*\[guest\]/, ""); const m = clean.match(/^([A-Z_]+):\s*([\s\S]*)$/); if (m) { const err = new ApiError(m[1], m[2], { retryAfterSeconds: retry ? +retry[1] : null }); err.guest = guest; // ZeroGPU says how much the request asked for and how much is left: "(146s requested vs. 65s left)". const need = clean.match(/\((\d+)s requested vs\.? (\d+)s left\)/); if (need) { err.requestedSeconds = +need[1]; err.leftSeconds = +need[2]; } return err; } if (/proxy token/i.test(t) && /expired/i.test(t)) return new ApiError("TOKEN_EXPIRED", clean); if (/quota/i.test(t)) return new ApiError("QUOTA", clean); if (/larger than the maximum|exceed/i.test(t)) return new ApiError("TOO_LONG", clean); if (/fetch|network|connection/i.test(t)) return new ApiError("NETWORK", clean); return new ApiError("UNKNOWN", clean || "Something went wrong on the server."); } /* ============================================================================================ */ /** @returns {Api & {configure?:Function, restartNow?:Function, cfg?:Object}} */ export function createApi({ mode = "mock", space } = {}) { return mode === "gradio" ? new GradioApi({ space }) : new MockApi(); }