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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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
"""
ComfyUI Tools
- Installs the small set of utilities used by this notebook.
- Registers the IPython line magic: %download URL [filename]

Usage:
    hf_token = ""
    civitai_token = ""

    %cd /content/ComfyUI/models/diffusion_models
    %download https://huggingface.co/owner/repo/resolve/main/model.safetensors
"""

from __future__ import annotations

import os
import platform
import re
import shutil
import subprocess
import sys
import urllib.parse
from pathlib import Path


# ---------------------------------------------------------------------
# Installation settings
# ---------------------------------------------------------------------

CONTENT_DIR = Path("/content")
COMFYUI_DIR = CONTENT_DIR / "ComfyUI"
COMFYUI_REPO = "https://github.com/Comfy-Org/ComfyUI.git"

# ์—ฌ๊ธฐ์— ์ปค์Šคํ…€ ๋…ธ๋“œ Git ์ €์žฅ์†Œ ์ฃผ์†Œ๋ฅผ ์ถ”๊ฐ€ํ•˜๋ฉด ๋ผ.
CUSTOM_NODES: list[str] = [
    "https://github.com/Comfy-Org/ComfyUI-Manager.git",
    "https://github.com/pythongosssss/ComfyUI-Custom-Scripts.git",
    "https://github.com/bedovyy/chibi-client",
    "https://github.com/cosmicbuffalo/comfyui-mobile-frontend.git",
    "https://github.com/rgthree/rgthree-comfy.git",
    "https://github.com/ruwwww/comfyui-spectrum-sdxl",
    "https://github.com/kijai/ComfyUI-KJNodes.git",
    #"https://github.com/BobJohnson24/ComfyUI-INT8-Fast.git",
    "https://github.com/Anzhc/anzhc-qwen2d-comfyui.git",
    "https://github.com/arcacolab/honey_client.git",
    "https://github.com/kohya-ss/ComfyUI-Anima-LLLite.git",
    #"https://github.com/ClownsharkBatwing/RES4LYF.git", ์ด์ƒˆ๋ผ ์™œ ์˜ค๋ฅ˜๋‚˜์ง€??
    "https://github.com/ssitu/ComfyUI_UltimateSDUpscale",
    "https://github.com/namemechan/ComfyUI-DCW.git",
    "https://github.com/ElectronGirl/ComfyUI-Anima-Ref-Adapter.git",
    "https://github.com/arcacolab/snapref",
    "https://github.com/iljung1106/comfyui-anima-safe-pag.git",
    "https://github.com/crystian/ComfyUI-Crystools.git",
    "https://github.com/AlekPet/ComfyUI_Custom_Nodes_AlekPet.git",
    "https://github.com/pamparamm/ComfyUI-ppm.git",
    "https://github.com/ltdrdata/was-node-suite-comfyui.git",
    "https://github.com/sorryhyun/ComfyUI-Spectrum-KSampler.git",
    "https://github.com/1lch2/ComfyUI-AnimaPromptFormatter.git",
    # "https://github.com/owner/custom-node.git",
]


# ---------------------------------------------------------------------
# Output helpers
# ---------------------------------------------------------------------

def _status(message: str) -> None:
    print(f"  {message}", flush=True)


def _run_quiet(command: list[str], *, label: str) -> None:
    """Run an installer command quietly, but show its log if it fails."""
    result = subprocess.run(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
    )
    if result.returncode != 0:
        _status(f"โŒ {label} ์‹คํŒจ (์ข…๋ฃŒ ์ฝ”๋“œ: {result.returncode})")
        if result.stdout:
            print(result.stdout.rstrip())
        raise RuntimeError(f"{label} installation failed")


# ---------------------------------------------------------------------
# Environment setup
# ---------------------------------------------------------------------

def _install_system_packages() -> None:
    """Ensure aria2, curl, and git are available."""
    required = {
        "aria2c": "aria2",
        "curl": "curl",
        "git": "git",
    }
    missing = [package for executable, package in required.items() if not shutil.which(executable)]
    if not missing:
        return

    if not shutil.which("apt-get"):
        raise RuntimeError(
            "ํ•„์ˆ˜ ์‹œ์Šคํ…œ ๋„๊ตฌ๊ฐ€ ์—†์–ด: " + ", ".join(missing)
            + " (apt-get๋„ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์–ด.)"
        )

    _status("aria2, curl, git ์„ค์น˜ ์ค‘...")
    _run_quiet(["apt-get", "update", "-qq"], label="apt ํŒจํ‚ค์ง€ ๋ชฉ๋ก ๊ฐฑ์‹ ")
    _run_quiet(
        ["apt-get", "install", "-y", "-qq", *missing],
        label="์‹œ์Šคํ…œ ๋„๊ตฌ ์„ค์น˜",
    )

    still_missing = [name for name in required if not shutil.which(name)]
    if still_missing:
        raise RuntimeError("์„ค์น˜ ํ›„์—๋„ ์‹คํ–‰ ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์–ด: " + ", ".join(still_missing))


def _install_cloudflared() -> None:
    if shutil.which("cloudflared"):
        return

    if not shutil.which("apt-get"):
        raise RuntimeError(
            "cloudflared๊ฐ€ ์—†๊ณ  apt-get๋„ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์–ด. "
            "cloudflared๋ฅผ ์ด๋ฏธ์ง€์— ๋ฏธ๋ฆฌ ์„ค์น˜ํ•ด์•ผ ํ•ด."
        )

    machine = platform.machine().lower()
    arch_map = {
        "x86_64": "amd64",
        "amd64": "amd64",
        "aarch64": "arm64",
        "arm64": "arm64",
    }
    arch = arch_map.get(machine)
    if not arch:
        raise RuntimeError(f"์ง€์›ํ•˜์ง€ ์•Š๋Š” CPU ์•„ํ‚คํ…์ฒ˜์•ผ: {machine}")

    package_url = (
        "https://github.com/cloudflare/cloudflared/releases/latest/download/"
        f"cloudflared-linux-{arch}.deb"
    )
    package_path = Path("/tmp/cloudflared.deb")

    _status("cloudflared ์„ค์น˜ ์ค‘...")
    _run_quiet(
        ["curl", "-fsSL", package_url, "-o", str(package_path)],
        label="cloudflared ๋‹ค์šด๋กœ๋“œ",
    )
    _run_quiet(
        ["dpkg", "-i", str(package_path)],
        label="cloudflared ์„ค์น˜",
    )
    package_path.unlink(missing_ok=True)

    if not shutil.which("cloudflared"):
        raise RuntimeError("cloudflared ์„ค์น˜ ํ›„ ์‹คํ–‰ ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์–ด.")


def _install_python_packages() -> None:
    packages = ["requests", "huggingface_hub"]
    _status("Python ํŒจํ‚ค์ง€ ํ™•์ธ ์ค‘...")
    _run_quiet(
        [sys.executable, "-m", "pip", "install", "-q", *packages],
        label="Python ํŒจํ‚ค์ง€ ์„ค์น˜",
    )


def _run_git_clone(repo_url: str, destination: Path, *, label: str) -> None:
    if destination.exists():
        if (destination / ".git").is_dir():
            _status(f"โ†ช {label} ์ด๋ฏธ ์กด์žฌํ•จ. Clone ์ƒ๋žต.")
            return
        raise RuntimeError(
            f"{label} ๊ฒฝ๋กœ๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•˜์ง€๋งŒ Git ์ €์žฅ์†Œ๊ฐ€ ์•„๋‹ˆ์•ผ: {destination}"
        )

    _status(f"{label} Clone ์ค‘...")
    _run_quiet(
        ["git", "clone", "--depth", "1", repo_url, str(destination)],
        label=f"{label} Clone",
    )


def _install_requirements(requirements_file: Path, *, label: str) -> None:
    if not requirements_file.is_file():
        _status(f"โ†ช {label}: requirements.txt ์—†์Œ. ์ƒ๋žต.")
        return

    _status(f"{label} ์˜์กด์„ฑ ์„ค์น˜ ์ค‘...")
    _run_quiet(
        [sys.executable, "-m", "pip", "install", "-q", "-r", str(requirements_file)],
        label=f"{label} ์˜์กด์„ฑ ์„ค์น˜",
    )


def _install_comfyui() -> None:
    # /content ๋””๋ ‰ํ„ฐ๋ฆฌ๋งŒ ์ƒ์„ฑํ•˜๊ณ , ComfyUI ๋””๋ ‰ํ„ฐ๋ฆฌ๋Š” git clone์ด ์ƒ์„ฑํ•˜๊ฒŒ ๋‘”๋‹ค.
    CONTENT_DIR.mkdir(parents=True, exist_ok=True)

    _run_git_clone(COMFYUI_REPO, COMFYUI_DIR, label="ComfyUI")
    if not (COMFYUI_DIR / "main.py").is_file():
        raise RuntimeError(f"ComfyUI main.py๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์–ด: {COMFYUI_DIR}")

    _install_requirements(COMFYUI_DIR / "requirements.txt", label="ComfyUI")


def _install_custom_nodes() -> None:
    if not CUSTOM_NODES:
        _status("์ปค์Šคํ…€ ๋…ธ๋“œ ๋ชฉ๋ก์ด ๋น„์–ด ์žˆ์–ด. Clone ์ƒ๋žต.")
        return

    custom_nodes_dir = COMFYUI_DIR / "custom_nodes"
    custom_nodes_dir.mkdir(parents=True, exist_ok=True)

    for repo_url in CUSTOM_NODES:
        repo_url = repo_url.strip()
        if not repo_url:
            continue

        repo_name = repo_url.rstrip("/").rsplit("/", 1)[-1]
        if repo_name.endswith(".git"):
            repo_name = repo_name[:-4]
        if not repo_name:
            raise RuntimeError(f"์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ์ปค์Šคํ…€ ๋…ธ๋“œ ์ €์žฅ์†Œ ์ฃผ์†Œ์•ผ: {repo_url}")

        node_dir = custom_nodes_dir / repo_name
        _run_git_clone(repo_url, node_dir, label=f"์ปค์Šคํ…€ ๋…ธ๋“œ {repo_name}")
        _install_requirements(node_dir / "requirements.txt", label=repo_name)


def setup() -> None:
    _status("ํ•„์ˆ˜ ๋„๊ตฌ ํ™•์ธ ์ค‘...")
    _install_system_packages()
    _install_cloudflared()
    _install_python_packages()

    _status("ComfyUI ์„ค์น˜ ์ค‘...")
    _install_comfyui()
    _install_custom_nodes()

    _status("ํ™˜๊ฒฝ ๊ตฌ์ถ• ์™„๋ฃŒ.")


# ---------------------------------------------------------------------
# Download helpers
# ---------------------------------------------------------------------

def _get_notebook_token(name: str) -> str:
    """Read a token from the active IPython user namespace."""
    try:
        from IPython import get_ipython

        shell = get_ipython()
        if shell is not None:
            value = shell.user_ns.get(name, "")
            return str(value).strip() if value else ""
    except Exception:
        pass
    return ""


def _build_download_command(url: str, filename: str | None) -> list[str]:
    parsed = urllib.parse.urlparse(url)
    host = (parsed.hostname or "").lower()
    headers: list[str] = []

    if host == "huggingface.co" or host.endswith(".huggingface.co"):
        token = _get_notebook_token("hf_token")
        if token:
            headers.append(f"Authorization: Bearer {token}")

    elif host == "civitai.com" or host.endswith(".civitai.com") or host == "civitai.red" or host.endswith(".civitai.red"):
        token = _get_notebook_token("civitai_token")
        if token and "/api/download/models/" in parsed.path:
            # Civitai's direct model-download endpoint accepts token as a query parameter.
            query = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
            if not any(key.lower() == "token" for key, _ in query):
                query.append(("token", token))
                url = urllib.parse.urlunparse(
                    parsed._replace(query=urllib.parse.urlencode(query))
                )

    command = [
        "aria2c",
        "--continue=true",
        "--allow-overwrite=true",
        "--auto-file-renaming=false",
        "--max-tries=5",
        "--retry-wait=3",
        "--connect-timeout=30",
        "--timeout=60",
        "--console-log-level=notice",
        "--summary-interval=1",
        "--download-result=hide",
        "-x", "8",
        "-s", "8",
        "-k", "1M",
    ]

    for header in headers:
        command.extend(["--header", header])

    if filename:
        command.extend(["--out", filename])

    command.append(url)
    return command


def _download(url: str, filename: str | None = None) -> None:
    url = url.strip()
    if not url:
        _status("โš ๏ธ ๋‹ค์šด๋กœ๋“œ ์ฃผ์†Œ๊ฐ€ ๋น„์–ด ์žˆ์–ด.")
        return

    parsed = urllib.parse.urlparse(url)
    if parsed.scheme not in ("http", "https") or not parsed.netloc:
        _status("โŒ ์˜ฌ๋ฐ”๋ฅธ HTTP/HTTPS ์ฃผ์†Œ๊ฐ€ ์•„๋‹ˆ์•ผ.")
        return

    if not shutil.which("aria2c"):
        _status("โŒ aria2c๊ฐ€ ์—†์–ด. ๋จผ์ € tools.py ์„ค์น˜ ์…€์„ ์‹คํ–‰ํ•ด ์ค˜.")
        return

    if filename:
        filename = Path(filename).name
    else:
        filename = Path(urllib.parse.unquote(parsed.path)).name or "downloaded_file"

    command = _build_download_command(url, filename)

    _status(f"โฌ‡๏ธ {filename} ๋‹ค์šด๋กœ๋“œ ์ค‘...")
    try:
        process = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            bufsize=1,
        )

        last_progress = ""
        assert process.stdout is not None

        for raw_line in process.stdout:
            line = raw_line.strip()
            if not line:
                continue

            # aria2 progress lines usually begin with [#...].
            if line.startswith("[#"):
                progress = re.sub(r"\s+", " ", line)
                if progress != last_progress:
                    print(f"\r  โฌ‡๏ธ {filename} {progress[:180]}", end="", flush=True)
                    last_progress = progress

        return_code = process.wait()
        if return_code == 0:
            print(f"\r  โœ… {filename} ๋‹ค์šด๋กœ๋“œ ์™„๋ฃŒ.{' ' * 30}")
        else:
            print()
            _status(f"โŒ {filename} ๋‹ค์šด๋กœ๋“œ ์‹คํŒจ (aria2 ์ข…๋ฃŒ ์ฝ”๋“œ: {return_code})")
    except KeyboardInterrupt:
        process.terminate()
        process.wait()
        print()
        _status("๋‹ค์šด๋กœ๋“œ ์ทจ์†Œ๋จ.")
    except Exception as exc:
        print()
        _status(f"โŒ ๋‹ค์šด๋กœ๋“œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {exc}")


# ---------------------------------------------------------------------
# IPython magic registration
# ---------------------------------------------------------------------

def register_download_magic() -> None:
    from IPython import get_ipython

    shell = get_ipython()
    if shell is None:
        raise RuntimeError("์ด ํŒŒ์ผ์€ Jupyter/IPython ์ปค๋„์—์„œ ์‹คํ–‰ํ•ด์•ผ ํ•ด.")

    def download_magic(line: str) -> None:
        # shlex handles quoted URLs/filenames and keeps the command simple.
        import shlex

        try:
            args = shlex.split(line)
        except ValueError as exc:
            _status(f"โŒ ๋ช…๋ น์–ด ํ˜•์‹ ์˜ค๋ฅ˜: {exc}")
            return

        if not args:
            _status("์‚ฌ์šฉ๋ฒ•: %download URL [filename]")
            return

        if len(args) > 2:
            _status("์‚ฌ์šฉ๋ฒ•: %download URL [filename]")
            return

        _download(args[0], args[1] if len(args) == 2 else None)

    shell.register_magic_function(download_magic, "line", "download")


# ---------------------------------------------------------------------
# Run setup and register the magic when this file is executed with %run.
# ---------------------------------------------------------------------

try:
    setup()
    register_download_magic()
except Exception as error:
    print(f"\nโŒ tools.py ์ดˆ๊ธฐํ™” ์‹คํŒจ: {error}")
    raise

# ---------------------------------------------------------------------
# ๊ธฐ์ดˆ์ ์ธ ์›Œํฌํ”Œ๋กœ์šฐ ๋‹ค์šด๋กœ๋“œ ์ž„ํ”Œ๋ž€ํŠธ
# ---------------------------------------------------------------------

import os, urllib.request as r
os.makedirs("/content/ComfyUI/user/default/workflows", exist_ok=True)
r.urlretrieve("https://huggingface.co/arcacolab/data/resolve/main/modal/workflows/anima_inpaint_lllite_v3_m.json", "/content/ComfyUI/user/default/workflows/anima_inpaint_lllite_v3_m.json")
r.urlretrieve("https://huggingface.co/arcacolab/data/resolve/main/modal/workflows/anima_simple_m.json", "/content/ComfyUI/user/default/workflows/anima_simple_m.json")
r.urlretrieve("https://huggingface.co/arcacolab/data/resolve/main/modal/workflows/sanpref_simple_m.json", "/content/ComfyUI/user/default/workflows/sanpref_simple_m.json")