""" 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")