data / modal /tools_org.py
arcacolab's picture
Update modal/tools_org.py
b95327b verified
Raw History Blame Contribute Delete
14.6 kB
"""
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")