comfyUi 触ってみる

ローカルLLMを触る中で画像の作成も試してみたくなった。
ollamaで画像の生成もできるという情報を見たが、AppleSiliconのMacでないと動かないそうな。

最近の画像生成は、ComfyUI というものを使うらしい。
Xのタイムラインで、グラフノードでワークフローが組まれているもののスクショで流れてきていたりしていた。

Dockerで動かせるようなので、試してみる。

参考

環境構築

環境構築は、Copilot と共に実施して以下のようにしていきます。
ソースの大部分は、作らせています。

docker-compose.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# docker-compose.yml
version: '3.8'
services:
comfyui:
build:
context: .
dockerfile: Dockerfile.comfyui
container_name: comfyui-service
ports:
- "8188:8188"
restart: unless-stopped
volumes:
- ./models:/app/ComfyUI/models
- ./data/output:/app/ComfyUI/output
- ./data/workflows:/app/ComfyUI/user/default/workflows
Dockerfile.comfyui
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
# ComfyUI Dockerfile (CPU version)
FROM pytorch/pytorch:2.4.0-cuda12.1-cudnn9-runtime

WORKDIR /app

# 必要なパッケージをインストール
RUN apt-get update && apt-get install -y --no-install-recommends \
git \
&& rm -rf /var/lib/apt/lists/*

# ComfyUI をクローン
RUN git clone https://github.com/comfyanonymous/ComfyUI.git
WORKDIR /app/ComfyUI

# 依存パッケージをインストール
RUN pip install --no-cache-dir -r requirements.txt

# ユーザー設定
RUN groupadd -g 1000 appuser && \
useradd -m -u 1000 -g 1000 appuser && \
mkdir -p /app/ComfyUI/user/default/workflows /app/ComfyUI/output && \
chown -R appuser:appuser /app

USER appuser

EXPOSE 8188

# ComfyUI 起動コマンド(CPU モード)
ENTRYPOINT ["python", "main.py", "--cpu", "--listen", "0.0.0.0", "--port", "8188"]
comfyui_client_generate_image.ts
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
const apiHost = Deno.env.get("COMFYUI_API_HOST") ?? "127.0.0.1:8188";
const apiBase = apiHost.startsWith("http://") || apiHost.startsWith("https://") ? apiHost : `http://${apiHost}`;
const prompt = Deno.args[0] ?? "cute anime girl, cinematic lighting, highly detailed";
const negative = Deno.env.get("COMFYUI_NEGATIVE_PROMPT") ?? " ";
const width = Number(Deno.env.get("COMFYUI_WIDTH") ?? "1024");
const height = Number(Deno.env.get("COMFYUI_HEIGHT") ?? "1024");
const steps = Number(Deno.env.get("COMFYUI_STEPS") ?? "20");
const cfg = Number(Deno.env.get("COMFYUI_CFG") ?? "2.5");
const seed = Number(Deno.env.get("COMFYUI_SEED") ?? `${Math.floor(Math.random() * 2 ** 30)}`);
const sampler = Deno.env.get("COMFYUI_SAMPLER") ?? "euler";
const scheduler = Deno.env.get("COMFYUI_SCHEDULER") ?? "simple";
const outputDir = Deno.env.get("COMFYUI_OUTPUT_DIR") ?? "outputs";
// CPU実行は時間がかかるため、デフォルト12時間(環境変数で上書き可能)
const timeoutMs = Number(Deno.env.get("COMFYUI_TIMEOUT_MS") ?? `${12 * 60 * 60 * 1000}`);
const pollingMs = Number(Deno.env.get("COMFYUI_POLLING_MS") ?? "5000");
const maxAttempts = Number(Deno.env.get("COMFYUI_MAX_ATTEMPTS") ?? "3");
const retryDelayMs = Number(Deno.env.get("COMFYUI_RETRY_DELAY_MS") ?? "10000");

const unetName = Deno.env.get("COMFYUI_UNET") ?? "qwen_image_fp8_e4m3fn.safetensors";
const vaeName = Deno.env.get("COMFYUI_VAE") ?? "qwen_image_vae.safetensors";
const clipName = Deno.env.get("COMFYUI_CLIP") ?? "qwen_2.5_vl_7b_fp8_scaled.safetensors";

type ComfyHistoryImage = {
filename: string;
subfolder?: string;
type?: string;
};

type ComfyHistoryNodeOutput = {
images?: ComfyHistoryImage[];
};

type ComfyHistoryEntry = {
outputs?: Record<string, ComfyHistoryNodeOutput>;
};

type ComfyQueueResponse = {
queue_running?: Array<[number, string, ...unknown[]]>;
queue_pending?: Array<[number, string, ...unknown[]]>;
};

function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}

function isRetriableError(error: unknown): boolean {
const message = String((error as { message?: unknown })?.message ?? error).toLowerCase();
return (
message.includes("os error 10053") ||
message.includes("os error 10054") ||
message.includes("connection error") ||
message.includes("error reading a body from connection") ||
message.includes("failed to fetch") ||
message.includes("connection reset") ||
message.includes("sendrequest") ||
message.includes("not found in history")
);
}

async function fetchJson<T>(path: string, init?: RequestInit, retries = 3): Promise<T> {
for (let attempt = 1; ; attempt++) {
try {
const response = await fetch(`${apiBase}${path}`, {
...init,
headers: {
"Content-Type": "application/json",
"Connection": "close",
...(init?.headers ?? {}),
},
});

if (!response.ok) {
throw new Error(`HTTP ${response.status} ${response.statusText} for ${path}`);
}

return await response.json() as T;
} catch (error) {
const shouldRetry = attempt < retries && isRetriableError(error);
if (!shouldRetry) {
throw error;
}
await sleep(retryDelayMs);
}
}
}

function pickFirstImage(entry: ComfyHistoryEntry | undefined): ComfyHistoryImage | null {
if (!entry?.outputs) {
return null;
}

for (const nodeOutput of Object.values(entry.outputs)) {
const image = nodeOutput.images?.[0];
if (image) {
return image;
}
}

return null;
}

async function downloadImage(image: ComfyHistoryImage): Promise<Uint8Array> {
const params = new URLSearchParams({
filename: image.filename,
subfolder: image.subfolder ?? "",
type: image.type ?? "output",
});

const response = await fetch(`${apiBase}/view?${params.toString()}`, {
headers: { "Connection": "close" },
});
if (!response.ok) {
throw new Error(`Failed to download image: HTTP ${response.status} ${response.statusText}`);
}

return new Uint8Array(await response.arrayBuffer());
}

async function waitForHistory(promptId: string): Promise<ComfyHistoryEntry> {
const deadline = Date.now() + timeoutMs;

while (Date.now() < deadline) {
const history = await fetchJson<Record<string, ComfyHistoryEntry>>(`/history/${promptId}`, undefined, 3);
const entry = history[promptId];
if (entry?.outputs) {
return entry;
}

const queue = await fetchJson<ComfyQueueResponse>("/queue", undefined, 3);
const running = queue.queue_running ?? [];
const pending = queue.queue_pending ?? [];
const isStillQueued = [...running, ...pending].some((item) => item[1] === promptId);
if (!isStillQueued) {
throw new Error(`Prompt ${promptId} disappeared from queue/history (likely ComfyUI restart or dropped job)`);
}

await sleep(pollingMs);
}

throw new Error(`Prompt ${promptId} timed out after ${timeoutMs} ms`);
}

// Qwen-Image ワークフロー (https://comfyanonymous.github.io/ComfyUI_examples/qwen_image/)
const workflowPrompt = {
"3": {
inputs: {
seed,
steps,
cfg,
sampler_name: sampler,
scheduler,
denoise: 1.0,
model: ["66", 0],
positive: ["6", 0],
negative: ["7", 0],
latent_image: ["58", 0],
},
class_type: "KSampler",
},
"6": {
inputs: {
text: prompt,
clip: ["38", 0],
},
class_type: "CLIPTextEncode",
},
"7": {
inputs: {
text: negative,
clip: ["38", 0],
},
class_type: "CLIPTextEncode",
},
"8": {
inputs: {
samples: ["3", 0],
vae: ["39", 0],
},
class_type: "VAEDecode",
},
"37": {
inputs: {
unet_name: unetName,
weight_dtype: "default",
},
class_type: "UNETLoader",
},
"38": {
inputs: {
clip_name: clipName,
type: "qwen_image",
device: "default",
},
class_type: "CLIPLoader",
},
"39": {
inputs: {
vae_name: vaeName,
},
class_type: "VAELoader",
},
"58": {
inputs: {
width,
height,
batch_size: 1,
},
class_type: "EmptySD3LatentImage",
},
"60": {
inputs: {
filename_prefix: "ComfyUI",
images: ["8", 0],
},
class_type: "SaveImage",
},
"66": {
inputs: {
shift: 3.1,
model: ["37", 0],
},
class_type: "ModelSamplingAuraFlow",
},
};

try {
await fetchJson("/system_stats", undefined, 3);

console.log(
`ComfyUI generation settings: ${width}x${height}, steps=${steps}, cfg=${cfg}, timeout_ms=${timeoutMs}, polling_ms=${pollingMs}, max_attempts=${maxAttempts}`,
);

let imageBytes: Uint8Array | null = null;

for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const clientId = crypto.randomUUID();
const enqueueResult = await fetchJson<{ prompt_id?: string; node_errors?: unknown }>(
"/prompt",
{
method: "POST",
body: JSON.stringify({ prompt: workflowPrompt, client_id: clientId }),
},
3,
);

if (!enqueueResult.prompt_id) {
throw new Error(`ComfyUI did not return prompt_id: ${JSON.stringify(enqueueResult)}`);
}

const historyEntry = await waitForHistory(enqueueResult.prompt_id);
const imageInfo = pickFirstImage(historyEntry);
if (!imageInfo) {
throw new Error(`Prompt ${enqueueResult.prompt_id} completed but no images were found in history output.`);
}

imageBytes = await downloadImage(imageInfo);
break;
} catch (error) {
const shouldRetry = attempt < maxAttempts && isRetriableError(error);
if (!shouldRetry) {
throw error;
}
console.warn(
`Attempt ${attempt}/${maxAttempts} failed with transient error; retrying in ${retryDelayMs} ms...`,
);
await sleep(retryDelayMs);
}
}

if (!imageBytes) {
throw new Error("ComfyUI returned no images.");
}

await Deno.mkdir(outputDir, { recursive: true });
const outPath = `${outputDir}/qwen_image_${crypto.randomUUID()}.png`;
await Deno.writeFile(outPath, imageBytes);

console.log(`Saved image: ${outPath}`);
} catch (error) {
console.error("Failed to generate image with Qwen-Image on ComfyUI:", error);
const nodeErrors = (error as { json?: { node_errors?: unknown } })?.json?.node_errors;
if (nodeErrors) {
console.error("ComfyUI node errors:", JSON.stringify(nodeErrors, null, 2));
}
console.error(
"Place these files in ComfyUI models: diffusion_models/qwen_image_fp8_e4m3fn.safetensors, text_encoders/qwen_2.5_vl_7b_fp8_scaled.safetensors, vae/qwen_image_vae.safetensors",
);
Deno.exit(1);
}

これを使い、以下のように使います。

1
$ docker compose up -d

ここで、localhost:8188 にComfyUIのAPIが立ち上がるのを確認できます。

1
$ deno run --allow-net --allow-write --allow-env comfyui_client_generate_image.ts "20代 女性"

ここから出力を待つのが、生成に時間がかかるため、気長に待ちます。
この時は4時間待っています。
CPUのみで構築しているのでおそらく時間がかかるだろうなと感じたわけですが、

ワークフローもコード上で表現しています。
タイムラインに流れてくる線でつながれるようなノードグラフはこういうもの、ソースに起こすとこういうものなのだなあと納得していました。

で作成されたものが以下のもの

なんかボヤっとしている。
ある種のモナリザ的平均値っぽいものになったが、生成結果に癖がつくようなプロンプトを投げてないので当然でもある。
後ろがいい具合でボケているのもあって、広告で使われていたら違和感も持たないかもしれない。


というわけで、ComfyUIを触ってみた。
ollamaを使う中で、「別にGPU積んでなくてもかなりやれる」と感じていたが、画像生成に関しては、全く話が違うのを感じる。
ちゃんとGPU積んでやるもんだというのがわかるところです。

では。