File size: 18,569 Bytes
ef73cd4
 
1914b26
 
 
ef73cd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1914b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef73cd4
1914b26
 
ef73cd4
 
 
 
1914b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef73cd4
 
 
 
1914b26
ef73cd4
 
1914b26
ef73cd4
1914b26
 
 
 
 
 
 
 
 
ef73cd4
 
1914b26
ef73cd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1914b26
ef73cd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1914b26
 
ef73cd4
 
 
 
 
 
 
 
 
 
 
 
 
1914b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef73cd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1914b26
ef73cd4
 
 
 
 
 
 
 
 
 
 
 
 
1914b26
ef73cd4
 
 
 
 
 
 
 
 
 
 
1914b26
 
 
 
 
 
 
 
 
ef73cd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1914b26
ef73cd4
 
 
 
1914b26
 
 
ef73cd4
1914b26
ef73cd4
 
1914b26
ef73cd4
 
 
 
 
 
 
 
 
 
 
 
 
1914b26
 
 
 
 
c5a5fd8
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
"""
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")
#바보 이슈