""" 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///tree// https://huggingface.co///tree// 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") #바보 이슈