File size: 8,379 Bytes
3429714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import { buildTokens, findVideoDescriptor, parseWorkflow, renderWorkflow } from "./core.js";

const $ = (id) => document.getElementById(id);
const state = {
  stopRequested: false,
  objectUrl: null,
};

function cleanBaseUrl() {
  const raw = $("backend-url").value.trim().replace(/\/+$/, "");
  let url;
  try {
    url = new URL(raw);
  } catch {
    throw new Error("Enter a valid ComfyUI API URL.");
  }
  if (!["http:", "https:"].includes(url.protocol)) {
    throw new Error("The ComfyUI URL must use HTTP or HTTPS.");
  }
  if (window.location.protocol === "https:" && url.protocol !== "https:") {
    throw new Error("This HTTPS Space cannot call an HTTP backend because browsers block mixed content.");
  }
  return raw;
}

function requestHeaders(includeJson = false) {
  const headers = {};
  const token = $("backend-token").value.trim();
  if (token) headers.Authorization = `Bearer ${token}`;
  if (includeJson) headers["Content-Type"] = "application/json";
  return headers;
}

async function apiFetch(path, options = {}) {
  const base = cleanBaseUrl();
  try {
    return await fetch(`${base}${path}`, options);
  } catch (error) {
    throw new Error(
      `Browser could not reach the backend. Check HTTPS, DNS and CORS for ${window.location.origin}. ${error.message}`,
    );
  }
}

function setBadge(element, text, kind) {
  element.textContent = text;
  element.className = `badge ${kind}`;
}

function setStatus(message, progress = null, kind = "working") {
  $("status").textContent = message;
  setBadge($("output-state"), kind === "error" ? "Error" : kind === "success" ? "Ready" : "Working", kind);
  if (progress !== null) $("progress-bar").style.width = `${Math.max(0, Math.min(100, progress))}%`;
}

function validateResponse(response, label) {
  if (!response.ok) throw new Error(`${label} failed: HTTP ${response.status} ${response.statusText}`);
  return response;
}

async function testBackend() {
  const button = $("test-backend");
  button.disabled = true;
  setBadge($("connection-badge"), "Testing", "working");
  try {
    parseWorkflow($("workflow-json").value);
    const response = await apiFetch("/system_stats", {
      headers: requestHeaders(),
      mode: "cors",
    });
    validateResponse(response, "Backend test");
    await response.json();
    setBadge($("connection-badge"), "Connected", "success");
    setStatus("Backend and API-format workflow are ready.", 0, "success");
  } catch (error) {
    setBadge($("connection-badge"), "Failed", "error");
    setStatus(error.message, 0, "error");
  } finally {
    button.disabled = false;
  }
}

function valuesFromForm() {
  const prompt = $("prompt").value.trim();
  if (!prompt) throw new Error("Enter a prompt.");
  const duration = Number($("duration").value);
  const loraStrength = Number($("lora-strength").value);
  const steps = Number($("steps").value);
  const cfg = Number($("cfg").value);
  if (duration < 4 || duration > 15) throw new Error("Duration must be between 4 and 15 seconds.");
  if (loraStrength < 0 || loraStrength > 1.5) throw new Error("LoRA strength must be between 0 and 1.5.");
  if (steps < 4 || steps > 30) throw new Error("Steps must be between 4 and 30.");
  if (cfg < 1 || cfg > 8) throw new Error("CFG must be between 1 and 8.");
  let seed = Number($("seed").value);
  if ($("randomize-seed").checked) {
    const random = new Uint32Array(2);
    crypto.getRandomValues(random);
    seed = random[0] * 2 ** 21 + (random[1] & (2 ** 21 - 1));
    $("seed").value = String(seed);
  }
  return {
    prompt,
    negativePrompt: $("negative-prompt").value,
    loraName: $("lora-file").value,
    loraStrength,
    resolution: $("resolution").value,
    duration,
    steps,
    cfg,
    seed,
  };
}

async function queuePrompt(workflow) {
  const response = await apiFetch("/prompt", {
    method: "POST",
    headers: requestHeaders(true),
    mode: "cors",
    body: JSON.stringify({ prompt: workflow, client_id: crypto.randomUUID() }),
  });
  validateResponse(response, "Workflow submission");
  const payload = await response.json();
  if (!payload.prompt_id) {
    throw new Error(`ComfyUI returned no prompt_id: ${JSON.stringify(payload.node_errors ?? payload.error ?? payload)}`);
  }
  return String(payload.prompt_id);
}

const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));

async function waitForHistory(promptId, timeoutMilliseconds = 30 * 60 * 1000) {
  const started = Date.now();
  while (Date.now() - started < timeoutMilliseconds) {
    if (state.stopRequested) throw new Error("Polling stopped. The ComfyUI task may still be running.");
    const response = await apiFetch(`/history/${encodeURIComponent(promptId)}`, {
      headers: requestHeaders(),
      mode: "cors",
    });
    validateResponse(response, "History request");
    const payload = await response.json();
    const entry = payload[promptId];
    const elapsed = Date.now() - started;
    setStatus(`ComfyUI task ${promptId.slice(0, 8)} is running…`, 8 + (elapsed / timeoutMilliseconds) * 82);
    if (entry) {
      const status = entry.status ?? {};
      if (status.status_str === "error" || status.completed === false) {
        throw new Error(`ComfyUI execution failed: ${JSON.stringify(status.messages ?? status)}`);
      }
      if (entry.outputs && Object.keys(entry.outputs).length) return entry;
    }
    await sleep(3000);
  }
  throw new Error("ComfyUI task timed out after 30 minutes.");
}

async function downloadVideo(descriptor) {
  const params = new URLSearchParams(descriptor);
  const response = await apiFetch(`/view?${params}`, {
    headers: requestHeaders(),
    mode: "cors",
  });
  validateResponse(response, "Video download");
  return response.blob();
}

function showVideo(blob, descriptor) {
  if (state.objectUrl) URL.revokeObjectURL(state.objectUrl);
  state.objectUrl = URL.createObjectURL(blob);
  const video = $("output-video");
  video.src = state.objectUrl;
  video.hidden = false;
  $("empty-state").hidden = true;
  const download = $("download");
  download.href = state.objectUrl;
  download.download = descriptor.filename.split("/").pop() || "pinkfluffybunny-h3.mp4";
  download.hidden = false;
}

async function generate() {
  const generateButton = $("generate");
  try {
    if (!$("authorization-confirmed").checked) {
      throw new Error("Confirm the backend's MiniMax H3 license authorization before submitting.");
    }
    cleanBaseUrl();
    const workflow = parseWorkflow($("workflow-json").value);
    const values = valuesFromForm();
    const tokens = buildTokens(values);
    const rendered = renderWorkflow(workflow, tokens);
    state.stopRequested = false;
    generateButton.disabled = true;
    $("stop").disabled = false;
    setStatus("Submitting the parameterized workflow…", 3);
    const promptId = await queuePrompt(rendered);
    setStatus(`Queued as ${promptId}. Waiting for ComfyUI…`, 7);
    const entry = await waitForHistory(promptId);
    $("history-output").textContent = JSON.stringify(entry, null, 2);
    const descriptor = findVideoDescriptor(entry);
    if (!descriptor) {
      throw new Error("ComfyUI finished but no MP4/WebM/MOV/MKV output was found. End the workflow with SaveVideo.");
    }
    setStatus("Downloading the generated video…", 95);
    const blob = await downloadVideo(descriptor);
    showVideo(blob, descriptor);
    setStatus(
      `Video ready · seed ${tokens["{{SEED}}"]} · ${tokens["{{LENGTH}}"]} frames · LoRA ${tokens["{{LORA_STRENGTH}}"]}`,
      100,
      "success",
    );
  } catch (error) {
    setStatus(error.message, 0, "error");
  } finally {
    generateButton.disabled = false;
    $("stop").disabled = true;
  }
}

$("workflow-file").addEventListener("change", async (event) => {
  const [file] = event.target.files;
  if (!file) return;
  try {
    $("workflow-json").value = await file.text();
    parseWorkflow($("workflow-json").value);
    setBadge($("connection-badge"), "Workflow loaded", "working");
    setStatus(`Loaded ${file.name}. Test the backend next.`, 0, "working");
  } catch (error) {
    setStatus(error.message, 0, "error");
  }
});

$("test-backend").addEventListener("click", testBackend);
$("generate").addEventListener("click", generate);
$("stop").addEventListener("click", () => {
  state.stopRequested = true;
  $("stop").disabled = true;
});