Download modal/prepare.py from arcacolab/data: direct link, hf CLI and curl.
- Browser
- Download file 18.6 kB
-
https://huggingface.co/arcacolab/data/resolve/main/modal/prepare.py
- Command line
-
hf download hf://arcacolab/data/modal/prepare.py
-
curl -L -o prepare.py https://huggingface.co/arcacolab/data/resolve/main/modal/prepare.py
18.6 kB
| """ | |
| Anima Standalone Trainer - Setup & Download Tools | |
| - Installs Node.js 22, system tools (aria2, curl, git, libgl1, libglib2.0-0), | |
| repo, venv/requirements, and UI deps. | |
| - Registers IPython line magic: %download URL [filename] [--force] | |
| Usage in Jupyter: | |
| hf_token = "hf_..." | |
| civitai_token = "..." | |
| %cd /content/dataset | |
| %download https://huggingface.co/datasets/arcacolab/for_lora/tree/main/realskin_v5_redo | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import re | |
| import shutil | |
| import stat | |
| import subprocess | |
| import sys | |
| import urllib.parse | |
| from pathlib import Path | |
| # --------------------------------------------------------------------- | |
| # Installation settings | |
| # --------------------------------------------------------------------- | |
| CONTENT_DIR = Path("/content") | |
| TRAINER_DIR = CONTENT_DIR / "Anima-Standalone-Trainer" | |
| TRAINER_REPO = "https://github.com/gazingstars123/Anima-Standalone-Trainer.git" | |
| DEFAULT_DATASET_DIR = CONTENT_DIR / "dataset" | |
| # --------------------------------------------------------------------- | |
| # Output helpers | |
| # --------------------------------------------------------------------- | |
| def _status(message: str) -> None: | |
| print(f" {message}", flush=True) | |
| def _run_quiet(command: list[str], *, label: str, cwd: Path | None = None) -> None: | |
| """Run a command quietly, printing output if it fails.""" | |
| result = subprocess.run( | |
| command, | |
| cwd=str(cwd) if cwd else None, | |
| 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} failed") | |
| # --------------------------------------------------------------------- | |
| # Environment setup | |
| # --------------------------------------------------------------------- | |
| def _has_shared_lib(lib_name: str) -> bool: | |
| """Check whether a shared library (e.g. libGL.so.1) exists in linker cache or common paths.""" | |
| if shutil.which("ldconfig"): | |
| try: | |
| out = subprocess.check_output(["ldconfig", "-p"], text=True, stderr=subprocess.DEVNULL) | |
| if lib_name in out: | |
| return True | |
| except Exception: | |
| pass | |
| common_dirs = [ | |
| Path("/lib"), | |
| Path("/usr/lib"), | |
| Path("/lib/x86_64-linux-gnu"), | |
| Path("/usr/lib/x86_64-linux-gnu"), | |
| Path("/lib/aarch64-linux-gnu"), | |
| Path("/usr/lib/aarch64-linux-gnu"), | |
| ] | |
| for base in common_dirs: | |
| if base.is_dir() and any(base.rglob(f"{lib_name}*")): | |
| return True | |
| return False | |
| def _install_system_packages() -> None: | |
| """Ensure aria2, curl, git, libgl1, and libglib2.0-0 are available.""" | |
| cli_checks = { | |
| "aria2c": "aria2", | |
| "curl": "curl", | |
| "git": "git", | |
| } | |
| lib_checks = { | |
| "libGL.so.1": "libgl1", | |
| "libgthread-2.0.so.0": "libglib2.0-0", | |
| } | |
| missing_pkgs: list[str] = [] | |
| for exe, pkg in cli_checks.items(): | |
| if not shutil.which(exe) and pkg not in missing_pkgs: | |
| missing_pkgs.append(pkg) | |
| for lib_name, pkg in lib_checks.items(): | |
| if not _has_shared_lib(lib_name) and pkg not in missing_pkgs: | |
| missing_pkgs.append(pkg) | |
| if not missing_pkgs: | |
| _status("โช ํ์ ์์คํ ํจํค์ง(aria2, curl, git, libgl1, libglib2.0-0) ์ด๋ฏธ ์ค๋น๋จ.") | |
| return | |
| if not shutil.which("apt-get"): | |
| raise RuntimeError( | |
| "ํ์ ์์คํ ํจํค์ง๊ฐ ์๊ณ apt-get๋ ์ฌ์ฉํ ์ ์์ด: " + ", ".join(missing_pkgs) | |
| ) | |
| _status("ํ์ ์์คํ ํจํค์ง ์ค์น ์ค: " + ", ".join(missing_pkgs)) | |
| _run_quiet(["apt-get", "update", "-qq"], label="apt ํจํค์ง ๋ชฉ๋ก ๊ฐฑ์ ") | |
| _run_quiet(["apt-get", "install", "-y", "-qq", *missing_pkgs], label="์์คํ ํจํค์ง ์ค์น") | |
| still_missing: list[str] = [] | |
| for exe, pkg in cli_checks.items(): | |
| if not shutil.which(exe) and pkg not in still_missing: | |
| still_missing.append(pkg) | |
| for lib_name, pkg in lib_checks.items(): | |
| if not _has_shared_lib(lib_name) and pkg not in still_missing: | |
| still_missing.append(pkg) | |
| if still_missing: | |
| raise RuntimeError("์ค์น ํ์๋ ๋๋ฝ๋ ํจํค์ง๊ฐ ์์ด: " + ", ".join(still_missing)) | |
| def _install_nodejs() -> None: | |
| """Ensure Node.js 22.x and npm are available for training-ui.""" | |
| if shutil.which("node") and shutil.which("npm"): | |
| ver = subprocess.check_output(["node", "-v"], text=True).strip() | |
| _status(f"โช Node.js ์ด๋ฏธ ์ค์น๋จ ({ver}).") | |
| return | |
| if not shutil.which("apt-get"): | |
| raise RuntimeError("Node.js/npm์ด ์๊ณ apt-get๋ ์ฌ์ฉํ ์ ์์ด.") | |
| _status("Node.js 22.x ๋ฐ npm ์ค์น ์ค...") | |
| _run_quiet(["apt-get", "update", "-qq"], label="apt ํจํค์ง ๋ชฉ๋ก ๊ฐฑ์ ") | |
| _run_quiet( | |
| ["apt-get", "install", "-y", "-qq", "ca-certificates", "curl", "gnupg"], | |
| label="Node ์ ์ฅ์์ฉ ํจํค์ง ์ค์น", | |
| ) | |
| Path("/etc/apt/keyrings").mkdir(parents=True, exist_ok=True) | |
| _run_quiet( | |
| [ | |
| "bash", | |
| "-c", | |
| "curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key " | |
| "| gpg --dearmor --yes -o /etc/apt/keyrings/nodesource.gpg", | |
| ], | |
| label="NodeSource GPG ํค ๋ฑ๋ก", | |
| ) | |
| _run_quiet( | |
| [ | |
| "bash", | |
| "-c", | |
| 'echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] ' | |
| 'https://deb.nodesource.com/node_22.x nodistro main" ' | |
| "| tee /etc/apt/sources.list.d/nodesource.list > /dev/null", | |
| ], | |
| label="NodeSource ์ ์ฅ์ ์ถ๊ฐ", | |
| ) | |
| _run_quiet(["apt-get", "update", "-qq"], label="NodeSource ๋ชฉ๋ก ๊ฐฑ์ ") | |
| _run_quiet(["apt-get", "install", "-y", "-qq", "nodejs"], label="Node.js 22 ์ค์น") | |
| if not (shutil.which("node") and shutil.which("npm")): | |
| raise RuntimeError("Node.js/npm ์ค์น ํ ์คํ ํ์ผ์ ์ฐพ์ ์ ์์ด.") | |
| def _install_python_packages() -> None: | |
| packages = ["requests", "huggingface_hub"] | |
| _status("Python ํฌํผ ํจํค์ง ํ์ธ ์ค...") | |
| _run_quiet( | |
| [sys.executable, "-m", "pip", "install", "-q", *packages], | |
| label="Python ํฌํผ ํจํค์ง ์ค์น", | |
| ) | |
| def _clone_or_update_repo(repo_url: str, destination: Path, *, label: str) -> None: | |
| if destination.exists(): | |
| if (destination / ".git").is_dir(): | |
| _status(f"โช {label} ์ด๋ฏธ ์กด์ฌํจ. ์ต์ ๋ณ๊ฒฝ์ฌํญ ๋ฐ์ ์๋...") | |
| try: | |
| _run_quiet(["git", "pull", "--ff-only"], label=f"{label} ์ ๋ฐ์ดํธ", cwd=destination) | |
| except RuntimeError: | |
| _status(f"โช {label}: git pull ์๋ต (๋ก์ปฌ ์ํ ์ ์ง).") | |
| 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 _run_trainer_setup() -> None: | |
| setup_sh = TRAINER_DIR / "setup_env.sh" | |
| start_sh = TRAINER_DIR / "training-ui" / "start_linux.sh" | |
| for script in (setup_sh, start_sh): | |
| if script.is_file(): | |
| script.chmod(script.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) | |
| if not setup_sh.is_file(): | |
| raise RuntimeError(f"setup_env.sh๋ฅผ ์ฐพ์ ์ ์์ด: {setup_sh}") | |
| _status("Anima Standalone Trainer ํ๊ฒฝ(venv, ํจํค์ง, UI) ๊ตฌ์ฑ ์ค...") | |
| _run_quiet(["bash", str(setup_sh)], label="setup_env.sh ์คํ", cwd=TRAINER_DIR) | |
| def setup() -> None: | |
| CONTENT_DIR.mkdir(parents=True, exist_ok=True) | |
| DEFAULT_DATASET_DIR.mkdir(parents=True, exist_ok=True) | |
| _status("ํ์ ๋๊ตฌ ํ์ธ ์ค...") | |
| _install_system_packages() | |
| _install_nodejs() | |
| _install_python_packages() | |
| _status("Anima Standalone Trainer ์ค์น ์ค...") | |
| _clone_or_update_repo(TRAINER_REPO, TRAINER_DIR, label="Anima-Standalone-Trainer") | |
| _run_trainer_setup() | |
| _status("ํ๊ฒฝ ๊ตฌ์ถ ์๋ฃ.") | |
| # --------------------------------------------------------------------- | |
| # Download helpers (aria2c + Hugging Face /tree/ folder + dedup skip) | |
| # --------------------------------------------------------------------- | |
| def _get_notebook_token(name: str) -> str: | |
| """Read a token from IPython user namespace or environment variables.""" | |
| try: | |
| from IPython import get_ipython | |
| shell = get_ipython() | |
| if shell is not None: | |
| value = shell.user_ns.get(name, "") | |
| if value: | |
| return str(value).strip() | |
| except Exception: | |
| pass | |
| env_val = os.environ.get(name, "") or os.environ.get(name.upper(), "") | |
| return env_val.strip() | |
| def _parse_hf_tree_url(url: str) -> tuple[str, str, str, str] | None: | |
| """ | |
| Parse URLs like: | |
| https://huggingface.co/datasets/<owner>/<repo>/tree/<branch>/<subpath> | |
| https://huggingface.co/<owner>/<repo>/tree/<branch>/<subpath> | |
| Returns (repo_id, repo_type, revision, subpath) or None if not a /tree/ URL. | |
| """ | |
| parsed = urllib.parse.urlparse(url) | |
| host = (parsed.hostname or "").lower() | |
| if host != "huggingface.co" and not host.endswith(".huggingface.co"): | |
| return None | |
| parts = [urllib.parse.unquote(p) for p in parsed.path.strip("/").split("/") if p] | |
| if len(parts) < 4: | |
| return None | |
| if parts[0] == "datasets": | |
| if len(parts) < 5 or parts[3] != "tree": | |
| return None | |
| repo_type = "dataset" | |
| repo_id = f"{parts[1]}/{parts[2]}" | |
| revision = parts[4] | |
| subpath = "/".join(parts[5:]) | |
| return repo_id, repo_type, revision, subpath | |
| if parts[2] == "tree": | |
| repo_type = "model" | |
| repo_id = f"{parts[0]}/{parts[1]}" | |
| revision = parts[3] | |
| subpath = "/".join(parts[4:]) | |
| return repo_id, repo_type, revision, subpath | |
| return None | |
| def _download_hf_tree( | |
| repo_id: str, | |
| repo_type: str, | |
| revision: str, | |
| subpath: str, | |
| target_name: str | None = None, | |
| *, | |
| force: bool = False, | |
| ) -> None: | |
| try: | |
| from huggingface_hub import snapshot_download | |
| except ImportError: | |
| _status("huggingface_hub ์ค์น ์ค...") | |
| _run_quiet([sys.executable, "-m", "pip", "install", "-q", "huggingface_hub"], label="huggingface_hub ์ค์น") | |
| from huggingface_hub import snapshot_download | |
| token = _get_notebook_token("hf_token") or None | |
| cwd = Path.cwd() | |
| folder_name = target_name or (Path(subpath).name if subpath else repo_id.split("/")[-1]) | |
| dest_dir = cwd / folder_name | |
| if dest_dir.exists() and not force: | |
| existing_files = [ | |
| p for p in dest_dir.rglob("*") | |
| if p.is_file() and not p.name.startswith(".") | |
| ] | |
| if existing_files: | |
| _status( | |
| f"โช ์ด๋ฏธ ๋ค์ด๋ก๋๋ ํด๋ ๊ฐ์ง๋จ ({len(existing_files)}๊ฐ ํ์ผ): " | |
| f"{dest_dir} (์คํต, ๊ฐ์ ์ฌ๋ค์ด๋ก๋๋ --force)" | |
| ) | |
| return | |
| if force and dest_dir.exists(): | |
| shutil.rmtree(dest_dir) | |
| dest_dir.mkdir(parents=True, exist_ok=True) | |
| allow_patterns = [f"{subpath}/**", subpath] if subpath else None | |
| _status(f"โฌ๏ธ HF {repo_type} ํด๋ ๋ค์ด๋ก๋ ์ค: {repo_id} [{revision}] -> {dest_dir}") | |
| try: | |
| snapshot_download( | |
| repo_id=repo_id, | |
| repo_type=repo_type, | |
| revision=revision, | |
| local_dir=str(dest_dir), | |
| allow_patterns=allow_patterns, | |
| token=token, | |
| ) | |
| nested = dest_dir / subpath if subpath else None | |
| if nested and nested.is_dir() and nested != dest_dir: | |
| for item in nested.iterdir(): | |
| target_item = dest_dir / item.name | |
| if target_item.exists(): | |
| if target_item.is_dir(): | |
| shutil.rmtree(target_item) | |
| else: | |
| target_item.unlink() | |
| shutil.move(str(item), str(target_item)) | |
| top_prefix = subpath.split("/")[0] | |
| top_dir = dest_dir / top_prefix | |
| if top_dir.exists() and top_dir.is_dir(): | |
| shutil.rmtree(top_dir, ignore_errors=True) | |
| _status(f"โ ๋ค์ด๋ก๋ ์๋ฃ: {dest_dir}") | |
| except Exception as exc: | |
| _status(f"โ HF ํด๋ ๋ค์ด๋ก๋ ์คํจ: {exc}") | |
| 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 in ("civitai.com", "civitai.red") or host.endswith(".civitai.com") or host.endswith(".civitai.red"): | |
| token = _get_notebook_token("civitai_token") | |
| if token and "/api/download/models/" in parsed.path: | |
| 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, *, force: bool = False) -> 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 | |
| hf_tree = _parse_hf_tree_url(url) | |
| if hf_tree is not None: | |
| repo_id, repo_type, revision, subpath = hf_tree | |
| _download_hf_tree(repo_id, repo_type, revision, subpath, target_name=filename, force=force) | |
| return | |
| if not shutil.which("aria2c"): | |
| _status("โ aria2c๊ฐ ์์ด. ๋จผ์ prepare.py๋ฅผ ์คํํด ์ค.") | |
| return | |
| if filename: | |
| filename = Path(filename).name | |
| else: | |
| filename = Path(urllib.parse.unquote(parsed.path)).name or "downloaded_file" | |
| out_path = Path.cwd() / filename | |
| aria2_ctrl = Path(f"{out_path}.aria2") | |
| if out_path.is_file() and out_path.stat().st_size > 0 and not aria2_ctrl.exists() and not force: | |
| _status( | |
| f"โช ์ด๋ฏธ ์กด์ฌํ๋ ํ์ผ ๊ฐ์ง๋จ ({out_path.stat().st_size:,} bytes): " | |
| f"{filename} (์คํต, ๊ฐ์ ์ฌ๋ค์ด๋ก๋๋ --force)" | |
| ) | |
| return | |
| command = _build_download_command(url, filename) | |
| _status(f"โฌ๏ธ {filename} ๋ค์ด๋ก๋ ์ค...") | |
| process = None | |
| 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 | |
| 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: | |
| if process is not None and process.poll() is None: | |
| 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: | |
| import shlex | |
| try: | |
| tokens = shlex.split(line) | |
| except ValueError as exc: | |
| _status(f"โ ๋ช ๋ น์ด ํ์ ์ค๋ฅ: {exc}") | |
| return | |
| force = "--force" in tokens | |
| args = [t for t in tokens if t != "--force"] | |
| if not args or len(args) > 2: | |
| _status("์ฌ์ฉ๋ฒ: %download URL [filename] [--force]") | |
| return | |
| _download(args[0], args[1] if len(args) == 2 else None, force=force) | |
| shell.register_magic_function(download_magic, "line", "download") | |
| # --------------------------------------------------------------------- | |
| # Run setup and register the magic when executed with %run. | |
| # --------------------------------------------------------------------- | |
| try: | |
| setup() | |
| register_download_magic() | |
| except Exception as error: | |
| print(f"\nโ prepare.py ์ด๊ธฐํ ์คํจ: {error}") | |
| raise | |
| # --------------------------------------------------------------------- | |
| # ๊ธฐ๋ณธ py๋ค์ด๋ก๋ | |
| # --------------------------------------------------------------------- | |
| #import os, urllib.request as r | |
| #os.makedirs("/content", exist_ok=True) | |
| #r.urlretrieve("https://huggingface.co/arcacolab/data/resolve/main/modal/launch_trainer.py", "/content/launch_trainer.py") | |
| #r.urlretrieve("https://huggingface.co/arcacolab/data/resolve/main/modal/prepare.py", "/content/prepare.py") | |
| #๋ฐ๋ณด ์ด์ |