arcacolab commited on
Commit
a8b82fa
Β·
verified Β·
1 Parent(s): 81fa9a3

Upload 2 files

Browse files
modal/launch_comfy.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Launch ComfyUI and expose it through Gradio and Cloudflare quick tunnels."""
3
+
4
+ import atexit
5
+ import os
6
+ import platform
7
+ import queue
8
+ import re
9
+ import secrets
10
+ import stat
11
+ import subprocess
12
+ import sys
13
+ import threading
14
+ import time
15
+ from pathlib import Path
16
+ from typing import List, Optional
17
+
18
+ import requests
19
+
20
+ # -----------------------------------------------------------------------------
21
+ # Configuration
22
+ # -----------------------------------------------------------------------------
23
+ COMFYUI_DIR = Path("/content/ComfyUI")
24
+ COMFYUI_MAIN = COMFYUI_DIR / "main.py"
25
+ LOCAL_HOST = "127.0.0.1"
26
+ LOCAL_PORT = 8188
27
+
28
+ GRADIO_VERSION = "0.2"
29
+ GRADIO_API_SERVER = "https://api.gradio.app/v2/tunnel-request"
30
+ GRADIO_SHARE_SERVER_ADDRESS = None
31
+ TUNNEL_TIMEOUT_SECONDS = 30
32
+ COMFYUI_START_TIMEOUT_SECONDS = 180
33
+
34
+ CURRENT_TUNNELS: List["GradioTunnel"] = []
35
+ cloudflared_proc: Optional[subprocess.Popen] = None
36
+ cloudflared_url: Optional[str] = None
37
+ comfyui_proc: Optional[subprocess.Popen] = None
38
+ _shutdown_started = False
39
+ _shutdown_lock = threading.Lock()
40
+
41
+
42
+ # -----------------------------------------------------------------------------
43
+ # Gradio tunnel
44
+ # -----------------------------------------------------------------------------
45
+ machine = platform.machine().lower()
46
+ if machine in ("x86_64", "x64"):
47
+ machine = "amd64"
48
+ elif machine in ("aarch64", "arm64"):
49
+ machine = "arm64"
50
+
51
+ BINARY_REMOTE_NAME = f"frpc_{platform.system().lower()}_{machine}"
52
+ EXTENSION = ".exe" if os.name == "nt" else ""
53
+ BINARY_URL = (
54
+ f"https://cdn-media.huggingface.co/frpc-gradio-{GRADIO_VERSION}/"
55
+ f"{BINARY_REMOTE_NAME}{EXTENSION}"
56
+ )
57
+ BINARY_PATH = Path(__file__).resolve().parent / (
58
+ f"{BINARY_REMOTE_NAME}_v{GRADIO_VERSION}{EXTENSION}"
59
+ )
60
+
61
+
62
+ class GradioTunnel:
63
+ def __init__(self, remote_host, remote_port, local_host, local_port, share_token):
64
+ self.proc = None
65
+ self.url = None
66
+ self.remote_host = remote_host
67
+ self.remote_port = remote_port
68
+ self.local_host = local_host
69
+ self.local_port = local_port
70
+ self.share_token = share_token
71
+
72
+ @staticmethod
73
+ def download_binary():
74
+ if BINARY_PATH.exists() and os.access(BINARY_PATH, os.X_OK):
75
+ return
76
+
77
+ print("[Gradio] frpc λ°”μ΄λ„ˆλ¦¬ λ‹€μš΄λ‘œλ“œ 쀑...")
78
+ response = requests.get(BINARY_URL, timeout=30)
79
+ if response.status_code == 403:
80
+ raise OSError(
81
+ "ν˜„μž¬ ν”Œλž«νΌμš© Gradio frpc λ°”μ΄λ„ˆλ¦¬λ₯Ό 내렀받을 수 μ—†μ–΄. "
82
+ f"ν”Œλž«νΌ: {platform.uname()}"
83
+ )
84
+ response.raise_for_status()
85
+ BINARY_PATH.write_bytes(response.content)
86
+ BINARY_PATH.chmod(
87
+ BINARY_PATH.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
88
+ )
89
+
90
+ def start(self) -> str:
91
+ self.download_binary()
92
+ command = [
93
+ str(BINARY_PATH), "http", "-n", self.share_token,
94
+ "-l", str(self.local_port), "-i", self.local_host,
95
+ "--uc", "--sd", "random", "--ue", "--server_addr",
96
+ f"{self.remote_host}:{self.remote_port}", "--disable_log_color",
97
+ ]
98
+ self.proc = subprocess.Popen(
99
+ command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
100
+ text=True, bufsize=1,
101
+ )
102
+ CURRENT_TUNNELS.append(self)
103
+ atexit.register(self.stop)
104
+
105
+ output_queue = queue.Queue()
106
+
107
+ def read_output():
108
+ assert self.proc is not None and self.proc.stdout is not None
109
+ for output_line in self.proc.stdout:
110
+ output_queue.put(output_line)
111
+ output_queue.put(None)
112
+
113
+ threading.Thread(target=read_output, daemon=True).start()
114
+ logs = []
115
+ deadline = time.monotonic() + TUNNEL_TIMEOUT_SECONDS
116
+
117
+ while time.monotonic() < deadline:
118
+ try:
119
+ line = output_queue.get(timeout=0.25)
120
+ except queue.Empty:
121
+ if self.proc.poll() is not None:
122
+ break
123
+ continue
124
+ if line is None:
125
+ break
126
+
127
+ line = line.rstrip()
128
+ logs.append(line)
129
+ match = re.search(r"start proxy success:\s*(https?://\S+)", line)
130
+ if match:
131
+ self.url = match.group(1)
132
+ return self.url
133
+ if "login to server failed" in line.lower():
134
+ break
135
+
136
+ self.stop()
137
+ raise RuntimeError(
138
+ "Gradio 곡유 ν„°λ„μ—μ„œ 접속 URL을 λ°›μ§€ λͺ»ν–ˆμ–΄.\n"
139
+ + ("\n".join(logs[-30:]) if logs else "(frpc λ‘œκ·Έκ°€ μ—†μ–΄)")
140
+ )
141
+
142
+ def stop(self):
143
+ if self.proc is not None:
144
+ if self.proc.poll() is None:
145
+ print(
146
+ f"[Gradio] 터널 μ’…λ£Œ: {self.local_host}:{self.local_port} "
147
+ f"<> {self.url or 'URL 미확인'}"
148
+ )
149
+ self.proc.terminate()
150
+ try:
151
+ self.proc.wait(timeout=5)
152
+ except subprocess.TimeoutExpired:
153
+ self.proc.kill()
154
+ self.proc.wait()
155
+ self.proc = None
156
+
157
+
158
+ def setup_gradio_tunnel(
159
+ local_host=LOCAL_HOST,
160
+ local_port=LOCAL_PORT,
161
+ share_server_address=GRADIO_SHARE_SERVER_ADDRESS,
162
+ ):
163
+ if share_server_address is None:
164
+ response = requests.get(GRADIO_API_SERVER, timeout=10)
165
+ response.raise_for_status()
166
+ payload = response.json()
167
+ if not payload:
168
+ raise RuntimeError("Gradio APIμ—μ„œ 터널 μ„œλ²„ 정보λ₯Ό λ°›μ§€ λͺ»ν–ˆμ–΄.")
169
+ remote_host = payload[0]["host"]
170
+ remote_port = int(payload[0]["port"])
171
+ else:
172
+ remote_host, port_text = share_server_address.rsplit(":", 1)
173
+ remote_port = int(port_text)
174
+
175
+ tunnel = GradioTunnel(
176
+ remote_host, remote_port, local_host, local_port, secrets.token_urlsafe(32)
177
+ )
178
+ return tunnel.start()
179
+
180
+
181
+ # -----------------------------------------------------------------------------
182
+ # Cloudflare quick tunnel
183
+ # -----------------------------------------------------------------------------
184
+ def start_cloudflared_tunnel(port):
185
+ global cloudflared_proc, cloudflared_url
186
+
187
+ print("[Cloudflare] 터널 μ‹œμž‘ 쀑...")
188
+ cloudflared_proc = subprocess.Popen(
189
+ [
190
+ "cloudflared", "tunnel", "--no-autoupdate", "--url",
191
+ f"http://{LOCAL_HOST}:{port}",
192
+ ],
193
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
194
+ text=True, bufsize=1,
195
+ )
196
+ atexit.register(stop_cloudflared)
197
+
198
+ output_queue = queue.Queue()
199
+
200
+ def read_output():
201
+ assert cloudflared_proc is not None and cloudflared_proc.stdout is not None
202
+ for output_line in cloudflared_proc.stdout:
203
+ output_queue.put(output_line)
204
+ output_queue.put(None)
205
+
206
+ threading.Thread(target=read_output, daemon=True).start()
207
+ logs = []
208
+ deadline = time.monotonic() + TUNNEL_TIMEOUT_SECONDS
209
+
210
+ while time.monotonic() < deadline:
211
+ try:
212
+ line = output_queue.get(timeout=0.25)
213
+ except queue.Empty:
214
+ if cloudflared_proc.poll() is not None:
215
+ break
216
+ continue
217
+ if line is None:
218
+ break
219
+
220
+ line = line.rstrip()
221
+ logs.append(line)
222
+ match = re.search(r"https://[a-zA-Z0-9.-]+\.trycloudflare\.com", line)
223
+ if match:
224
+ cloudflared_url = match.group(0)
225
+ return cloudflared_url
226
+
227
+ stop_cloudflared()
228
+ raise RuntimeError(
229
+ "Cloudflare URL을 κ°€μ Έμ˜€μ§€ λͺ»ν–ˆμ–΄.\n"
230
+ + ("\n".join(logs[-30:]) if logs else "(cloudflared λ‘œκ·Έκ°€ μ—†μ–΄)")
231
+ )
232
+
233
+
234
+ def stop_cloudflared():
235
+ global cloudflared_proc
236
+ if cloudflared_proc is not None:
237
+ if cloudflared_proc.poll() is None:
238
+ print(
239
+ f"[Cloudflare] 터널 μ’…λ£Œ: {LOCAL_HOST}:{LOCAL_PORT} "
240
+ f"<> {cloudflared_url or 'URL 미확인'}"
241
+ )
242
+ cloudflared_proc.terminate()
243
+ try:
244
+ cloudflared_proc.wait(timeout=5)
245
+ except subprocess.TimeoutExpired:
246
+ cloudflared_proc.kill()
247
+ cloudflared_proc.wait()
248
+ cloudflared_proc = None
249
+
250
+
251
+ # -----------------------------------------------------------------------------
252
+ # ComfyUI lifecycle
253
+ # -----------------------------------------------------------------------------
254
+ def wait_for_comfyui(timeout=COMFYUI_START_TIMEOUT_SECONDS):
255
+ """Wait until ComfyUI's local HTTP endpoint responds."""
256
+ deadline = time.monotonic() + timeout
257
+ test_url = f"http://{LOCAL_HOST}:{LOCAL_PORT}/system_stats"
258
+
259
+ while time.monotonic() < deadline:
260
+ if comfyui_proc is None or comfyui_proc.poll() is not None:
261
+ return False
262
+ try:
263
+ response = requests.get(test_url, timeout=2)
264
+ if response.ok:
265
+ return True
266
+ except requests.RequestException:
267
+ pass
268
+ time.sleep(1)
269
+ return False
270
+
271
+
272
+ def shutdown():
273
+ global _shutdown_started, comfyui_proc
274
+ with _shutdown_lock:
275
+ if _shutdown_started:
276
+ return
277
+ _shutdown_started = True
278
+
279
+ print("\nπŸ›‘ ComfyUI와 터널을 μ’…λ£Œν•˜λŠ” 쀑...")
280
+ stop_cloudflared()
281
+ for tunnel in reversed(CURRENT_TUNNELS):
282
+ tunnel.stop()
283
+
284
+ if comfyui_proc is not None:
285
+ if comfyui_proc.poll() is None:
286
+ comfyui_proc.terminate()
287
+ try:
288
+ comfyui_proc.wait(timeout=10)
289
+ except subprocess.TimeoutExpired:
290
+ comfyui_proc.kill()
291
+ comfyui_proc.wait()
292
+ comfyui_proc = None
293
+ print("βœ… λͺ¨λ“  ν”„λ‘œμ„ΈμŠ€λ₯Ό μ’…λ£Œν–ˆμ–΄.")
294
+
295
+
296
+ def main():
297
+ global comfyui_proc
298
+
299
+ if not COMFYUI_MAIN.is_file():
300
+ print(
301
+ f"❌ ComfyUIλ₯Ό 찾을 수 μ—†μ–΄: {COMFYUI_MAIN}\n"
302
+ "Cell 1μ—μ„œ ComfyUI μ„€μΉ˜κ°€ μ™„λ£ŒλλŠ”μ§€ 확인해 쀘.",
303
+ file=sys.stderr,
304
+ )
305
+ return 1
306
+
307
+ print("\n" + "=" * 60)
308
+ print("πŸš€ ComfyUI + 이쀑 터널 μ‹œμž‘")
309
+ print("=" * 60 + "\n")
310
+
311
+ # launch_comfy.py 뒀에 μ „λ‹¬λœ μΈμžλŠ” ComfyUI main.py둜 κ·ΈλŒ€λ‘œ μ „λ‹¬ν•œλ‹€.
312
+ comfyui_command = [
313
+ sys.executable, str(COMFYUI_MAIN),
314
+ "--listen", LOCAL_HOST, "--port", str(LOCAL_PORT),
315
+ ] + sys.argv[1:]
316
+
317
+ print("[ComfyUI] μ‹€ν–‰ 쀑...")
318
+ print(f"[ComfyUI] μΆ”κ°€ 인자: {sys.argv[1:] or '(μ—†μŒ)'}")
319
+ comfyui_proc = subprocess.Popen(comfyui_command, cwd=str(COMFYUI_DIR))
320
+
321
+ print("[ComfyUI] μ„œλ²„ μ€€λΉ„ λŒ€κΈ° 쀑...")
322
+ if not wait_for_comfyui():
323
+ if comfyui_proc.poll() is not None:
324
+ print(
325
+ f"❌ ComfyUI ν”„λ‘œμ„ΈμŠ€κ°€ μ’…λ£Œλμ–΄. μ’…λ£Œ μ½”λ“œ: {comfyui_proc.returncode}",
326
+ file=sys.stderr,
327
+ )
328
+ else:
329
+ print(
330
+ f"❌ {COMFYUI_START_TIMEOUT_SECONDS}초 μ•ˆμ— ComfyUIκ°€ μ€€λΉ„λ˜μ§€ μ•Šμ•˜μ–΄.",
331
+ file=sys.stderr,
332
+ )
333
+ return 1
334
+
335
+ print("βœ… ComfyUI μ„œλ²„ μ€€λΉ„ μ™„λ£Œ!\n")
336
+
337
+ gradio_url = None
338
+ cloudflare_url_result = None
339
+
340
+ def run_gradio():
341
+ nonlocal gradio_url
342
+ try:
343
+ print("[Gradio] 터널 μ‹œμž‘ 쀑...")
344
+ gradio_url = setup_gradio_tunnel()
345
+ except Exception as exc:
346
+ print(f"⚠️ [Gradio] 터널 생성 μ‹€νŒ¨: {exc}", file=sys.stderr)
347
+
348
+ def run_cloudflare():
349
+ nonlocal cloudflare_url_result
350
+ try:
351
+ cloudflare_url_result = start_cloudflared_tunnel(LOCAL_PORT)
352
+ except Exception as exc:
353
+ print(f"⚠️ [Cloudflare] 터널 생성 μ‹€νŒ¨: {exc}", file=sys.stderr)
354
+
355
+ gradio_thread = threading.Thread(target=run_gradio, daemon=True)
356
+ cloudflare_thread = threading.Thread(target=run_cloudflare, daemon=True)
357
+ gradio_thread.start()
358
+ cloudflare_thread.start()
359
+ gradio_thread.join(TUNNEL_TIMEOUT_SECONDS + 15)
360
+ cloudflare_thread.join(TUNNEL_TIMEOUT_SECONDS + 15)
361
+
362
+ print("\n🌐 ComfyUI 접속 URL:")
363
+ print(f" β€’ Gradio: {gradio_url or '❌ 생성 μ‹€νŒ¨'}")
364
+ print(f" β€’ Cloudflare: {cloudflare_url_result or '❌ 생성 μ‹€νŒ¨'}")
365
+
366
+ if not gradio_url and not cloudflare_url_result:
367
+ print(
368
+ "\n⚠️ 두 터널 λͺ¨λ‘ μƒμ„±λ˜μ§€ μ•Šμ•˜μ–΄. 둜컬 ComfyUIλŠ” 계속 μ‹€ν–‰ν• κ²Œ.",
369
+ file=sys.stderr,
370
+ )
371
+
372
+ print("\nπŸ’‘ 생성에 μ„±κ³΅ν•œ URL을 ν΄λ¦­ν•΄μ„œ μ ‘μ†ν•˜λ©΄ 돼.")
373
+ print("πŸ’‘ 이 셀을 μ€‘λ‹¨ν•˜λ©΄ ComfyUI와 λͺ¨λ“  터널이 μ’…λ£ŒλΌ.")
374
+ print("\n" + "-" * 60)
375
+ print("πŸ“œ ComfyUI μ‹€ν–‰ 둜그")
376
+ print("-" * 60 + "\n")
377
+
378
+ try:
379
+ while comfyui_proc is not None and comfyui_proc.poll() is None:
380
+ time.sleep(0.5)
381
+ except KeyboardInterrupt:
382
+ pass
383
+ finally:
384
+ shutdown()
385
+ return 0
386
+
387
+
388
+ if __name__ == "__main__":
389
+ try:
390
+ exit_code = main()
391
+ except KeyboardInterrupt:
392
+ exit_code = 130
393
+ shutdown()
394
+ except Exception as exc:
395
+ print(f"❌ μ‹€ν–‰ 쀑 예기치 μ•Šμ€ 였λ₯˜: {exc}", file=sys.stderr)
396
+ exit_code = 1
397
+ shutdown()
398
+
399
+ if exit_code:
400
+ sys.exit(exit_code)
modal/tools_org_초기본.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ComfyUI Tools
3
+ - Installs the small set of utilities used by this notebook.
4
+ - Registers the IPython line magic: %download URL [filename]
5
+
6
+ Usage:
7
+ hf_token = ""
8
+ civitai_token = ""
9
+
10
+ %cd /content/ComfyUI/models/diffusion_models
11
+ %download https://huggingface.co/owner/repo/resolve/main/model.safetensors
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import platform
18
+ import re
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ import urllib.parse
23
+ from pathlib import Path
24
+
25
+
26
+ # ---------------------------------------------------------------------
27
+ # Installation settings
28
+ # ---------------------------------------------------------------------
29
+
30
+ CONTENT_DIR = Path("/content")
31
+ COMFYUI_DIR = CONTENT_DIR / "ComfyUI"
32
+ COMFYUI_REPO = "https://github.com/Comfy-Org/ComfyUI.git"
33
+
34
+ # 여기에 μ»€μŠ€ν…€ λ…Έλ“œ Git μ €μž₯μ†Œ μ£Όμ†Œλ₯Ό μΆ”κ°€ν•˜λ©΄ 돼.
35
+ CUSTOM_NODES: list[str] = [
36
+ # "https://github.com/owner/custom-node.git",
37
+ ]
38
+
39
+
40
+ # ---------------------------------------------------------------------
41
+ # Output helpers
42
+ # ---------------------------------------------------------------------
43
+
44
+ def _status(message: str) -> None:
45
+ print(f" {message}", flush=True)
46
+
47
+
48
+ def _run_quiet(command: list[str], *, label: str) -> None:
49
+ """Run an installer command quietly, but show its log if it fails."""
50
+ result = subprocess.run(
51
+ command,
52
+ stdout=subprocess.PIPE,
53
+ stderr=subprocess.STDOUT,
54
+ text=True,
55
+ )
56
+ if result.returncode != 0:
57
+ _status(f"❌ {label} μ‹€νŒ¨ (μ’…λ£Œ μ½”λ“œ: {result.returncode})")
58
+ if result.stdout:
59
+ print(result.stdout.rstrip())
60
+ raise RuntimeError(f"{label} installation failed")
61
+
62
+
63
+ # ---------------------------------------------------------------------
64
+ # Environment setup
65
+ # ---------------------------------------------------------------------
66
+
67
+ def _install_system_packages() -> None:
68
+ """Ensure aria2, curl, and git are available."""
69
+ required = {
70
+ "aria2c": "aria2",
71
+ "curl": "curl",
72
+ "git": "git",
73
+ }
74
+ missing = [package for executable, package in required.items() if not shutil.which(executable)]
75
+ if not missing:
76
+ return
77
+
78
+ if not shutil.which("apt-get"):
79
+ raise RuntimeError(
80
+ "ν•„μˆ˜ μ‹œμŠ€ν…œ 도ꡬ가 μ—†μ–΄: " + ", ".join(missing)
81
+ + " (apt-get도 μ‚¬μš©ν•  수 μ—†μ–΄.)"
82
+ )
83
+
84
+ _status("aria2, curl, git μ„€μΉ˜ 쀑...")
85
+ _run_quiet(["apt-get", "update", "-qq"], label="apt νŒ¨ν‚€μ§€ λͺ©λ‘ κ°±μ‹ ")
86
+ _run_quiet(
87
+ ["apt-get", "install", "-y", "-qq", *missing],
88
+ label="μ‹œμŠ€ν…œ 도ꡬ μ„€μΉ˜",
89
+ )
90
+
91
+ still_missing = [name for name in required if not shutil.which(name)]
92
+ if still_missing:
93
+ raise RuntimeError("μ„€μΉ˜ 후에도 μ‹€ν–‰ νŒŒμΌμ„ 찾을 수 μ—†μ–΄: " + ", ".join(still_missing))
94
+
95
+
96
+ def _install_cloudflared() -> None:
97
+ if shutil.which("cloudflared"):
98
+ return
99
+
100
+ if not shutil.which("apt-get"):
101
+ raise RuntimeError(
102
+ "cloudflaredκ°€ μ—†κ³  apt-get도 μ‚¬μš©ν•  수 μ—†μ–΄. "
103
+ "cloudflaredλ₯Ό 이미지에 미리 μ„€μΉ˜ν•΄μ•Ό ν•΄."
104
+ )
105
+
106
+ machine = platform.machine().lower()
107
+ arch_map = {
108
+ "x86_64": "amd64",
109
+ "amd64": "amd64",
110
+ "aarch64": "arm64",
111
+ "arm64": "arm64",
112
+ }
113
+ arch = arch_map.get(machine)
114
+ if not arch:
115
+ raise RuntimeError(f"μ§€μ›ν•˜μ§€ μ•ŠλŠ” CPU μ•„ν‚€ν…μ²˜μ•Ό: {machine}")
116
+
117
+ package_url = (
118
+ "https://github.com/cloudflare/cloudflared/releases/latest/download/"
119
+ f"cloudflared-linux-{arch}.deb"
120
+ )
121
+ package_path = Path("/tmp/cloudflared.deb")
122
+
123
+ _status("cloudflared μ„€μΉ˜ 쀑...")
124
+ _run_quiet(
125
+ ["curl", "-fsSL", package_url, "-o", str(package_path)],
126
+ label="cloudflared λ‹€μš΄λ‘œλ“œ",
127
+ )
128
+ _run_quiet(
129
+ ["dpkg", "-i", str(package_path)],
130
+ label="cloudflared μ„€μΉ˜",
131
+ )
132
+ package_path.unlink(missing_ok=True)
133
+
134
+ if not shutil.which("cloudflared"):
135
+ raise RuntimeError("cloudflared μ„€μΉ˜ ν›„ μ‹€ν–‰ νŒŒμΌμ„ 찾을 수 μ—†μ–΄.")
136
+
137
+
138
+ def _install_python_packages() -> None:
139
+ packages = ["requests", "huggingface_hub"]
140
+ _status("Python νŒ¨ν‚€μ§€ 확인 쀑...")
141
+ _run_quiet(
142
+ [sys.executable, "-m", "pip", "install", "-q", *packages],
143
+ label="Python νŒ¨ν‚€μ§€ μ„€μΉ˜",
144
+ )
145
+
146
+
147
+ def _run_git_clone(repo_url: str, destination: Path, *, label: str) -> None:
148
+ if destination.exists():
149
+ if (destination / ".git").is_dir():
150
+ _status(f"β†ͺ {label} 이미 μ‘΄μž¬ν•¨. Clone μƒλž΅.")
151
+ return
152
+ raise RuntimeError(
153
+ f"{label} κ²½λ‘œκ°€ 이미 μ‘΄μž¬ν•˜μ§€λ§Œ Git μ €μž₯μ†Œκ°€ μ•„λ‹ˆμ•Ό: {destination}"
154
+ )
155
+
156
+ _status(f"{label} Clone 쀑...")
157
+ _run_quiet(
158
+ ["git", "clone", "--depth", "1", repo_url, str(destination)],
159
+ label=f"{label} Clone",
160
+ )
161
+
162
+
163
+ def _install_requirements(requirements_file: Path, *, label: str) -> None:
164
+ if not requirements_file.is_file():
165
+ _status(f"β†ͺ {label}: requirements.txt μ—†μŒ. μƒλž΅.")
166
+ return
167
+
168
+ _status(f"{label} μ˜μ‘΄μ„± μ„€μΉ˜ 쀑...")
169
+ _run_quiet(
170
+ [sys.executable, "-m", "pip", "install", "-q", "-r", str(requirements_file)],
171
+ label=f"{label} μ˜μ‘΄μ„± μ„€μΉ˜",
172
+ )
173
+
174
+
175
+ def _install_comfyui() -> None:
176
+ # /content λ””λ ‰ν„°λ¦¬λ§Œ μƒμ„±ν•˜κ³ , ComfyUI λ””λ ‰ν„°λ¦¬λŠ” git clone이 μƒμ„±ν•˜κ²Œ λ‘”λ‹€.
177
+ CONTENT_DIR.mkdir(parents=True, exist_ok=True)
178
+
179
+ _run_git_clone(COMFYUI_REPO, COMFYUI_DIR, label="ComfyUI")
180
+ if not (COMFYUI_DIR / "main.py").is_file():
181
+ raise RuntimeError(f"ComfyUI main.pyλ₯Ό 찾을 수 μ—†μ–΄: {COMFYUI_DIR}")
182
+
183
+ _install_requirements(COMFYUI_DIR / "requirements.txt", label="ComfyUI")
184
+
185
+
186
+ def _install_custom_nodes() -> None:
187
+ if not CUSTOM_NODES:
188
+ _status("μ»€μŠ€ν…€ λ…Έλ“œ λͺ©λ‘μ΄ λΉ„μ–΄ μžˆμ–΄. Clone μƒλž΅.")
189
+ return
190
+
191
+ custom_nodes_dir = COMFYUI_DIR / "custom_nodes"
192
+ custom_nodes_dir.mkdir(parents=True, exist_ok=True)
193
+
194
+ for repo_url in CUSTOM_NODES:
195
+ repo_url = repo_url.strip()
196
+ if not repo_url:
197
+ continue
198
+
199
+ repo_name = repo_url.rstrip("/").rsplit("/", 1)[-1]
200
+ if repo_name.endswith(".git"):
201
+ repo_name = repo_name[:-4]
202
+ if not repo_name:
203
+ raise RuntimeError(f"μ˜¬λ°”λ₯΄μ§€ μ•Šμ€ μ»€μŠ€ν…€ λ…Έλ“œ μ €μž₯μ†Œ μ£Όμ†Œμ•Ό: {repo_url}")
204
+
205
+ node_dir = custom_nodes_dir / repo_name
206
+ _run_git_clone(repo_url, node_dir, label=f"μ»€μŠ€ν…€ λ…Έλ“œ {repo_name}")
207
+ _install_requirements(node_dir / "requirements.txt", label=repo_name)
208
+
209
+
210
+ def setup() -> None:
211
+ _status("ν•„μˆ˜ 도ꡬ 확인 쀑...")
212
+ _install_system_packages()
213
+ _install_cloudflared()
214
+ _install_python_packages()
215
+
216
+ _status("ComfyUI μ„€μΉ˜ 쀑...")
217
+ _install_comfyui()
218
+ _install_custom_nodes()
219
+
220
+ _status("ν™˜κ²½ ꡬ좕 μ™„λ£Œ.")
221
+
222
+
223
+ # ---------------------------------------------------------------------
224
+ # Download helpers
225
+ # ---------------------------------------------------------------------
226
+
227
+ def _get_notebook_token(name: str) -> str:
228
+ """Read a token from the active IPython user namespace."""
229
+ try:
230
+ from IPython import get_ipython
231
+
232
+ shell = get_ipython()
233
+ if shell is not None:
234
+ value = shell.user_ns.get(name, "")
235
+ return str(value).strip() if value else ""
236
+ except Exception:
237
+ pass
238
+ return ""
239
+
240
+
241
+ def _build_download_command(url: str, filename: str | None) -> list[str]:
242
+ parsed = urllib.parse.urlparse(url)
243
+ host = (parsed.hostname or "").lower()
244
+ headers: list[str] = []
245
+
246
+ if host == "huggingface.co" or host.endswith(".huggingface.co"):
247
+ token = _get_notebook_token("hf_token")
248
+ if token:
249
+ headers.append(f"Authorization: Bearer {token}")
250
+
251
+ elif host == "civitai.com" or host.endswith(".civitai.com") or host == "civitai.red" or host.endswith(".civitai.red"):
252
+ token = _get_notebook_token("civitai_token")
253
+ if token and "/api/download/models/" in parsed.path:
254
+ # Civitai's direct model-download endpoint accepts token as a query parameter.
255
+ query = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
256
+ if not any(key.lower() == "token" for key, _ in query):
257
+ query.append(("token", token))
258
+ url = urllib.parse.urlunparse(
259
+ parsed._replace(query=urllib.parse.urlencode(query))
260
+ )
261
+
262
+ command = [
263
+ "aria2c",
264
+ "--continue=true",
265
+ "--allow-overwrite=true",
266
+ "--auto-file-renaming=false",
267
+ "--max-tries=5",
268
+ "--retry-wait=3",
269
+ "--connect-timeout=30",
270
+ "--timeout=60",
271
+ "--console-log-level=notice",
272
+ "--summary-interval=1",
273
+ "--download-result=hide",
274
+ "-x", "8",
275
+ "-s", "8",
276
+ "-k", "1M",
277
+ ]
278
+
279
+ for header in headers:
280
+ command.extend(["--header", header])
281
+
282
+ if filename:
283
+ command.extend(["--out", filename])
284
+
285
+ command.append(url)
286
+ return command
287
+
288
+
289
+ def _download(url: str, filename: str | None = None) -> None:
290
+ url = url.strip()
291
+ if not url:
292
+ _status("⚠️ λ‹€μš΄λ‘œλ“œ μ£Όμ†Œκ°€ λΉ„μ–΄ μžˆμ–΄.")
293
+ return
294
+
295
+ parsed = urllib.parse.urlparse(url)
296
+ if parsed.scheme not in ("http", "https") or not parsed.netloc:
297
+ _status("❌ μ˜¬λ°”λ₯Έ HTTP/HTTPS μ£Όμ†Œκ°€ μ•„λ‹ˆμ•Ό.")
298
+ return
299
+
300
+ if not shutil.which("aria2c"):
301
+ _status("❌ aria2cκ°€ μ—†μ–΄. λ¨Όμ € tools.py μ„€μΉ˜ 셀을 μ‹€ν–‰ν•΄ 쀘.")
302
+ return
303
+
304
+ if filename:
305
+ filename = Path(filename).name
306
+ else:
307
+ filename = Path(urllib.parse.unquote(parsed.path)).name or "downloaded_file"
308
+
309
+ command = _build_download_command(url, filename)
310
+
311
+ _status(f"⬇️ {filename} λ‹€μš΄λ‘œλ“œ 쀑...")
312
+ try:
313
+ process = subprocess.Popen(
314
+ command,
315
+ stdout=subprocess.PIPE,
316
+ stderr=subprocess.STDOUT,
317
+ text=True,
318
+ bufsize=1,
319
+ )
320
+
321
+ last_progress = ""
322
+ assert process.stdout is not None
323
+
324
+ for raw_line in process.stdout:
325
+ line = raw_line.strip()
326
+ if not line:
327
+ continue
328
+
329
+ # aria2 progress lines usually begin with [#...].
330
+ if line.startswith("[#"):
331
+ progress = re.sub(r"\s+", " ", line)
332
+ if progress != last_progress:
333
+ print(f"\r ⬇️ {filename} {progress[:180]}", end="", flush=True)
334
+ last_progress = progress
335
+
336
+ return_code = process.wait()
337
+ if return_code == 0:
338
+ print(f"\r βœ… {filename} λ‹€μš΄λ‘œλ“œ μ™„λ£Œ.{' ' * 30}")
339
+ else:
340
+ print()
341
+ _status(f"❌ {filename} λ‹€μš΄λ‘œλ“œ μ‹€νŒ¨ (aria2 μ’…λ£Œ μ½”λ“œ: {return_code})")
342
+ except KeyboardInterrupt:
343
+ process.terminate()
344
+ process.wait()
345
+ print()
346
+ _status("λ‹€μš΄λ‘œλ“œ μ·¨μ†Œλ¨.")
347
+ except Exception as exc:
348
+ print()
349
+ _status(f"❌ λ‹€μš΄λ‘œλ“œ 쀑 였λ₯˜ λ°œμƒ: {exc}")
350
+
351
+
352
+ # ---------------------------------------------------------------------
353
+ # IPython magic registration
354
+ # ---------------------------------------------------------------------
355
+
356
+ def register_download_magic() -> None:
357
+ from IPython import get_ipython
358
+
359
+ shell = get_ipython()
360
+ if shell is None:
361
+ raise RuntimeError("이 νŒŒμΌμ€ Jupyter/IPython μ»€λ„μ—μ„œ μ‹€ν–‰ν•΄μ•Ό ν•΄.")
362
+
363
+ def download_magic(line: str) -> None:
364
+ # shlex handles quoted URLs/filenames and keeps the command simple.
365
+ import shlex
366
+
367
+ try:
368
+ args = shlex.split(line)
369
+ except ValueError as exc:
370
+ _status(f"❌ λͺ…λ Ήμ–΄ ν˜•μ‹ 였λ₯˜: {exc}")
371
+ return
372
+
373
+ if not args:
374
+ _status("μ‚¬μš©λ²•: %download URL [filename]")
375
+ return
376
+
377
+ if len(args) > 2:
378
+ _status("μ‚¬μš©λ²•: %download URL [filename]")
379
+ return
380
+
381
+ _download(args[0], args[1] if len(args) == 2 else None)
382
+
383
+ shell.register_magic_function(download_magic, "line", "download")
384
+
385
+
386
+ # ---------------------------------------------------------------------
387
+ # Run setup and register the magic when this file is executed with %run.
388
+ # ---------------------------------------------------------------------
389
+
390
+ try:
391
+ setup()
392
+ register_download_magic()
393
+ except Exception as error:
394
+ print(f"\n❌ tools.py μ΄ˆκΈ°ν™” μ‹€νŒ¨: {error}")
395
+ raise