-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun-workflow-http.ts
More file actions
343 lines (305 loc) · 9.35 KB
/
run-workflow-http.ts
File metadata and controls
343 lines (305 loc) · 9.35 KB
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import * as fs from "fs";
import * as https from "https";
import FormData from "form-data";
// Types
interface WanAnimateInputs {
positive_prompt: string;
negative_prompt?: string;
video_width?: number;
video_height?: number;
video_length_frames?: number;
seed?: number;
steps?: number;
cfg_scale?: number;
}
// API Client
class ComfyUIApiClient {
private hostname: string;
private port: number;
constructor(baseUrl: string) {
const url = new URL(baseUrl);
this.hostname = url.hostname;
this.port = parseInt(url.port) || 443;
}
async uploadFile(fileBuffer: Buffer, filename: string): Promise<string> {
return new Promise((resolve, reject) => {
const form = new FormData();
form.append("image", fileBuffer, {
filename,
contentType: "image/png",
});
console.log(`📤 Uploading ${filename}...`);
const options = {
hostname: this.hostname,
port: this.port,
path: "/upload/image",
method: "POST",
headers: form.getHeaders(),
};
const req = https.request(options, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
if (res.statusCode === 200) {
try {
const result = JSON.parse(data);
console.log(`✅ Uploaded: ${result.name || filename}`);
resolve(result.name || filename);
} catch (e) {
console.log(`✅ Uploaded: ${filename}`);
resolve(filename);
}
} else {
reject(new Error(`Upload failed: ${res.statusCode} - ${data}`));
}
});
});
req.on("error", (error) => {
reject(error);
});
form.pipe(req);
});
}
async queueWorkflow(workflow: any): Promise<{ prompt_id: string }> {
return new Promise((resolve, reject) => {
console.log("📤 Sending workflow to queue...");
const data = JSON.stringify({
prompt: workflow,
client_id: "test-client",
});
const options = {
hostname: this.hostname,
port: this.port,
path: "/prompt",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(data),
},
};
const req = https.request(options, (res) => {
let responseData = "";
res.on("data", (chunk) => {
responseData += chunk;
});
res.on("end", () => {
if (res.statusCode === 200) {
const result = JSON.parse(responseData);
console.log(`📋 Queued: ${result.prompt_id}`);
resolve(result);
} else {
reject(new Error(`Queue failed: ${res.statusCode} - ${responseData}`));
}
});
});
req.on("error", (error) => {
reject(error);
});
req.write(data);
req.end();
});
}
async waitForCompletion(promptId: string): Promise<any> {
let lastStatus = "";
console.log("⏳ Waiting 5 seconds for job to initialize...");
await new Promise((r) => setTimeout(r, 5000));
while (true) {
try {
const response = await fetch(`https://${this.hostname}:${this.port}/history/${promptId}`);
const history = await response.json();
const job = history[promptId];
if (!job) {
console.log("⏳ Job not in history yet, waiting...");
await new Promise((r) => setTimeout(r, 5000));
continue;
}
const status = job.status.status_str;
if (status !== lastStatus) {
console.log(`⏳ Status: ${status}`);
lastStatus = status;
}
if (job.status.completed) {
console.log("✅ Job completed!");
return job;
}
if (status === "error") {
console.log("❌ Job error details:", JSON.stringify(job, null, 2));
throw new Error("❌ Job failed");
}
await new Promise((r) => setTimeout(r, 3000));
} catch (error) {
console.log("⏳ Error checking status, retrying...", error);
await new Promise((r) => setTimeout(r, 5000));
}
}
}
getOutputUrl(filename: string): string {
return `https://${this.hostname}:${this.port}/view?filename=${encodeURIComponent(filename)}&type=output`;
}
}
// Workflow Builder
class WanAnimateWorkflowBuilder {
build(inputs: WanAnimateInputs, imageName: string, videoName: string): any {
return {
"311": {
inputs: {
image: imageName,
upload: "image"
},
class_type: "LoadImage",
},
"417": {
inputs: {
video: videoName,
force_rate: 16,
frame_load_cap: inputs.video_length_frames || 176,
format: "Wan",
},
class_type: "VHS_LoadVideo",
},
"224": {
inputs: {
clip_name: "umt5_xxl_fp8_e4m3fn_scaled.safetensors",
type: "wan",
device: "default",
},
class_type: "CLIPLoader",
},
"226": {
inputs: {
unet_name: "wan2.2_animate_14B_bf16.safetensors",
weight_dtype: "default",
},
class_type: "UNETLoader",
},
"225": {
inputs: { vae_name: "wan_2.1_vae.safetensors" },
class_type: "VAELoader",
},
"317": {
inputs: { clip_name: "clip_vision_h.safetensors" },
class_type: "CLIPVisionLoader",
},
"227": {
inputs: {
text: inputs.positive_prompt,
clip: ["224", 0],
},
class_type: "CLIPTextEncode",
},
"228": {
inputs: {
text: inputs.negative_prompt || "blurry, low quality, distorted",
clip: ["224", 0],
},
class_type: "CLIPTextEncode",
},
"326": {
inputs: {
clip_vision: ["317", 0],
image: ["311", 0],
crop: "center",
},
class_type: "CLIPVisionEncode",
},
"370": {
inputs: {
positive: ["227", 0],
negative: ["228", 0],
vae: ["225", 0],
clip_vision_output: ["326", 0],
reference_image: ["311", 0],
width: inputs.video_width || 1080,
height: inputs.video_height || 1920,
length: inputs.video_length_frames || 176,
batch_size: 1,
flicker_scale: 4097,
video_frame_offset: 0,
continue_motion_max_frames: inputs.video_length_frames || 176,
},
class_type: "WanAnimateToVideo",
},
"324": {
inputs: {
model: ["226", 0],
positive: ["370", 0],
negative: ["370", 1],
latent_image: ["370", 2],
seed: inputs.seed || Math.floor(Math.random() * 1e12),
steps: inputs.steps || 20,
cfg: inputs.cfg_scale || 4,
sampler_name: "euler",
scheduler: "simple",
denoise: 1.0,
},
class_type: "KSampler",
},
"269": {
inputs: {
samples: ["324", 0],
vae: ["225", 0],
},
class_type: "VAEDecode",
},
"462": {
inputs: {
images: ["269", 0],
frame_rate: 16,
filename_prefix: "WanComfy",
format: "video/h264-mp4",
crf: 19,
loop_count: 0,
pingpong: false,
save_output: true,
},
class_type: "VHS_VideoCombine",
},
};
}
}
// Main Test
async function run() {
console.log("🚀 Starting Wan Animate Video Generation...");
const client = new ComfyUIApiClient("https://zqyh42lvmsz2qy-8188.proxy.runpod.net");
const builder = new WanAnimateWorkflowBuilder();
console.log("📂 Uploading files to server...");
try {
// Upload files to server first
const imageName = await client.uploadFile(fs.readFileSync("./myimage.png"), "myimage.png");
const videoName = await client.uploadFile(fs.readFileSync("./myvideo.mp4"), "myvideo.mp4");
console.log(`📁 Image ready: ${imageName}`);
console.log(`📹 Video ready: ${videoName}`);
const inputs: WanAnimateInputs = {
positive_prompt: "photorealistic video of blond women wearing navy blue bikini",
video_width: 1080,
video_height: 1920,
video_length_frames: 176, // 16 fps * 11 detik = 176 frames
seed: 123456789,
steps: 20,
};
console.log("📋 Building workflow...");
const workflow = builder.build(inputs, imageName, videoName);
console.log("📤 Queueing workflow...");
const { prompt_id } = await client.queueWorkflow(workflow);
console.log(`⏳ Processing job ${prompt_id}...`);
const result = await client.waitForCompletion(prompt_id);
const outputNode = result.outputs["462"];
if (outputNode?.video?.[0]?.filename) {
const videoUrl = client.getOutputUrl(outputNode.video[0].filename);
console.log("\n✅ SUCCESS! Download your video:");
console.log(videoUrl);
} else if (outputNode?.gifs?.[0]?.filename) {
const videoUrl = client.getOutputUrl(outputNode.gifs[0].filename);
console.log("\n✅ SUCCESS! Download your video:");
console.log(videoUrl);
} else {
console.log("❌ No video output found in result");
console.log("Full result:", JSON.stringify(result, null, 2));
}
} catch (error) {
console.error("❌ Error:", error);
}
}
run();