Update modal/prepare.py
Browse files123456752 unmodified lines606162636465666768697071727374757677787980818283848586878895 unmodified lines18418518618718818919054 unmodified lines2452462472482492506 unmodified lines2572582592602612622632646 unmodified lines2712722732742752762774 unmodified lines28228328428528628728851 unmodified lines3403413423433443453467 unmodified lines3543553563573583593605 unmodified lines36636736836937037153 unmodified lines4254264274284294304314324334344354364374384394407 unmodified lines448449450451"""Anima Standalone Trainer - Setup & Download Tools- Installs Node.js 22, system tools (aria2, curl, git), repo, venv/requirements, and UI deps.- Registers IPython line magic: %download URL [filename]Usage in Jupyter:hf_token = "hf_..."52 unmodified lines# Environment setup# ---------------------------------------------------------------------def _install_system_packages() -> None:"""Ensure aria2, curl, git, and ca-certificates/gnupg are available."""required = {"aria2c": "aria2","curl": "curl","git": "git",}missing = [pkg for exe, pkg in required.items() if not shutil.which(exe)]if not missing:returnif not shutil.which("apt-get"):raise RuntimeError("νμ μμ€ν λκ΅¬κ° μκ³ apt-getλ μ¬μ©ν μ μμ΄: " + ", ".join(missing))_status("aria2, curl, git μ€μΉ μ€...")_run_quiet(["apt-get", "update", "-qq"], label="apt ν¨ν€μ§ λͺ©λ‘ κ°±μ ")_run_quiet(["apt-get", "install", "-y", "-qq", *missing], label="μμ€ν λꡬ μ€μΉ")still_missing = [exe for exe in required if not shutil.which(exe)]if still_missing:raise RuntimeError("μ€μΉ νμλ μ€ν νμΌμ μ°Ύμ μ μμ΄: " + ", ".join(still_missing))def _install_nodejs() -> None:95 unmodified lines# ---------------------------------------------------------------------# Download helpers (aria2c + Hugging Face /tree/ folder support)# ---------------------------------------------------------------------def _get_notebook_token(name: str) -> str:54 unmodified linesrevision: str,subpath: str,target_name: str | None = None,) -> None:try:from huggingface_hub import snapshot_download6 unmodified linescwd = Path.cwd()folder_name = target_name or (Path(subpath).name if subpath else repo_id.split("/")[-1])dest_dir = cwd / folder_namedest_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}")6 unmodified linesallow_patterns=allow_patterns,token=token,)# If subpath is nested (e.g. a/b/dataset), flatten into dest_dir if desirednested = dest_dir / subpath if subpath else Noneif nested and nested.is_dir() and nested != dest_dir:for item in nested.iterdir():4 unmodified lineselse:target_item.unlink()shutil.move(str(item), str(target_item))# Clean up empty parent directories created under dest_dirtop_prefix = subpath.split("/")[0]top_dir = dest_dir / top_prefixif top_dir.exists() and top_dir.is_dir():51 unmodified linesreturn commanddef _download(url: str, filename: str | None = None) -> None:url = url.strip()if not url:_status("β οΈ λ€μ΄λ‘λ μ£Όμκ° λΉμ΄ μμ΄.")7 unmodified lineshf_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)returnif not shutil.which("aria2c"):5 unmodified lineselse:filename = Path(urllib.parse.unquote(parsed.path)).name or "downloaded_file"command = _build_download_command(url, filename)_status(f"β¬οΈ {filename} λ€μ΄λ‘λ μ€...")53 unmodified linesimport shlextry:args = shlex.split(line)except ValueError as exc:_status(f"β λͺ λ Ήμ΄ νμ μ€λ₯: {exc}")returnif not args or 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")7 unmodified linesregister_download_magic()except Exception as error:print(f"\nβ prepare.py μ΄κΈ°ν μ€ν¨: {error}")raise1234567852 unmodified lines61626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213395 unmodified lines22923023123223323423554 unmodified lines2902912922932942952962976 unmodified lines3043053063073083093103113123133143153163173183193203213223233243253266 unmodified lines3333343353363373384 unmodified lines34334434534634734851 unmodified lines4004014024034044054067 unmodified lines4144154164174184194205 unmodified lines42642742842943043143243343443543643743843944053 unmodified lines4944954964974984995005015025035045055065075085095105115127 unmodified lines520521522523524525526527528529530531"""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_..."52 unmodified lines# 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 Trueexcept Exception:passcommon_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 Truereturn Falsedef _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) μ΄λ―Έ μ€λΉλ¨.")returnif 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:95 unmodified lines# ---------------------------------------------------------------------# Download helpers (aria2c + Hugging Face /tree/ folder + dedup skip)# ---------------------------------------------------------------------def _get_notebook_token(name: str) -> str:54 unmodified linesrevision: str,subpath: str,target_name: str | None = None,*,force: bool = False,) -> None:try:from huggingface_hub import snapshot_download6 unmodified linescwd = Path.cwd()folder_name = target_name or (Path(subpath).name if subpath else repo_id.split("/")[-1])dest_dir = cwd / folder_nameif 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)")returnif 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}")6 unmodified linesallow_patterns=allow_patterns,token=token,)nested = dest_dir / subpath if subpath else Noneif nested and nested.is_dir() and nested != dest_dir:for item in nested.iterdir():4 unmodified lineselse:target_item.unlink()shutil.move(str(item), str(target_item))top_prefix = subpath.split("/")[0]top_dir = dest_dir / top_prefixif top_dir.exists() and top_dir.is_dir():51 unmodified linesreturn commanddef _download(url: str, filename: str | None = None, *, force: bool = False) -> None:url = url.strip()if not url:_status("β οΈ λ€μ΄λ‘λ μ£Όμκ° λΉμ΄ μμ΄.")7 unmodified lineshf_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)returnif not shutil.which("aria2c"):5 unmodified lineselse:filename = Path(urllib.parse.unquote(parsed.path)).name or "downloaded_file"out_path = Path.cwd() / filenamearia2_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)")returncommand = _build_download_command(url, filename)_status(f"β¬οΈ {filename} λ€μ΄λ‘λ μ€...")53 unmodified linesimport shlextry:tokens = shlex.split(line)except ValueError as exc:_status(f"β λͺ λ Ήμ΄ νμ μ€λ₯: {exc}")returnforce = "--force" in tokensargs = [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")7 unmodified linesregister_download_magic()except Exception as error:print(f"\nβ prepare.py μ΄κΈ°ν μ€ν¨: {error}")raise# ---------------------------------------------------------------------# κΈ°λ³Έ pyλ€μ΄λ‘λ# ---------------------------------------------------------------------import os, urllib.request as ros.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")
modal/prepare.py+101-21