arcacolab commited on
Commit
ef73cd4
Β·
verified Β·
1 Parent(s): 2f137db

Upload 2 files

Browse files
Files changed (2) hide show
  1. modal/launch_trainer.py +474 -0
  2. modal/prepare.py +451 -0
modal/launch_trainer.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Launch Anima Training UI and expose it through Gradio and Cloudflare quick tunnels."""
3
+
4
+ import atexit
5
+ import os
6
+ import platform
7
+ import queue
8
+ import re
9
+ import secrets
10
+ import shutil
11
+ import signal
12
+ import stat
13
+ import subprocess
14
+ import sys
15
+ import threading
16
+ import time
17
+ from pathlib import Path
18
+ from typing import List, Optional
19
+
20
+ import requests
21
+
22
+ # -----------------------------------------------------------------------------
23
+ # Configuration
24
+ # -----------------------------------------------------------------------------
25
+ REPO_DIR = Path("/content/Anima-Standalone-Trainer")
26
+ START_SCRIPT = REPO_DIR / "training-ui" / "start_linux.sh"
27
+ LOCAL_HOST = "127.0.0.1"
28
+ LOCAL_PORT = 3000
29
+
30
+ GRADIO_VERSION = "0.2"
31
+ GRADIO_API_SERVER = "https://api.gradio.app/v2/tunnel-request"
32
+ GRADIO_SHARE_SERVER_ADDRESS = None
33
+ TUNNEL_TIMEOUT_SECONDS = 30
34
+ UI_START_TIMEOUT_SECONDS = 120
35
+
36
+ CURRENT_TUNNELS: List["GradioTunnel"] = []
37
+ cloudflared_proc: Optional[subprocess.Popen] = None
38
+ cloudflared_url: Optional[str] = None
39
+ ui_proc: Optional[subprocess.Popen] = None
40
+ _shutdown_started = False
41
+ _shutdown_lock = threading.Lock()
42
+
43
+
44
+ # -----------------------------------------------------------------------------
45
+ # Gradio tunnel
46
+ # -----------------------------------------------------------------------------
47
+ machine = platform.machine().lower()
48
+ if machine in ("x86_64", "x64", "amd64"):
49
+ machine = "amd64"
50
+ elif machine in ("aarch64", "arm64"):
51
+ machine = "arm64"
52
+
53
+ BINARY_REMOTE_NAME = f"frpc_{platform.system().lower()}_{machine}"
54
+ EXTENSION = ".exe" if os.name == "nt" else ""
55
+ BINARY_URL = (
56
+ f"https://cdn-media.huggingface.co/frpc-gradio-{GRADIO_VERSION}/"
57
+ f"{BINARY_REMOTE_NAME}{EXTENSION}"
58
+ )
59
+
60
+ SCRIPT_DIR = Path(__file__).resolve().parent
61
+
62
+
63
+ def _resolve_frpc_path() -> Path:
64
+ filename = f"{BINARY_REMOTE_NAME}_v{GRADIO_VERSION}{EXTENSION}"
65
+ for candidate in (SCRIPT_DIR / filename, REPO_DIR / filename):
66
+ if candidate.exists():
67
+ return candidate
68
+ return SCRIPT_DIR / filename
69
+
70
+
71
+ BINARY_PATH = _resolve_frpc_path()
72
+
73
+
74
+ class GradioTunnel:
75
+ def __init__(self, remote_host, remote_port, local_host, local_port, share_token):
76
+ self.proc = None
77
+ self.url = None
78
+ self.remote_host = remote_host
79
+ self.remote_port = remote_port
80
+ self.local_host = local_host
81
+ self.local_port = local_port
82
+ self.share_token = share_token
83
+
84
+ @staticmethod
85
+ def download_binary():
86
+ if BINARY_PATH.exists() and os.access(BINARY_PATH, os.X_OK):
87
+ return
88
+
89
+ print("[Gradio] frpc λ°”μ΄λ„ˆλ¦¬ λ‹€μš΄λ‘œλ“œ 쀑...")
90
+ response = requests.get(BINARY_URL, timeout=30)
91
+ if response.status_code == 403:
92
+ raise OSError(
93
+ "ν˜„μž¬ ν”Œλž«νΌμš© Gradio frpc λ°”μ΄λ„ˆλ¦¬λ₯Ό 내렀받을 수 μ—†μ–΄. "
94
+ f"ν”Œλž«νΌ: {platform.uname()}"
95
+ )
96
+ response.raise_for_status()
97
+ BINARY_PATH.write_bytes(response.content)
98
+ BINARY_PATH.chmod(
99
+ BINARY_PATH.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
100
+ )
101
+
102
+ def start(self) -> str:
103
+ self.download_binary()
104
+ command = [
105
+ str(BINARY_PATH), "http", "-n", self.share_token,
106
+ "-l", str(self.local_port), "-i", self.local_host,
107
+ "--uc", "--sd", "random", "--ue", "--server_addr",
108
+ f"{self.remote_host}:{self.remote_port}", "--disable_log_color",
109
+ ]
110
+ self.proc = subprocess.Popen(
111
+ command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
112
+ text=True, bufsize=1,
113
+ )
114
+ CURRENT_TUNNELS.append(self)
115
+ atexit.register(self.stop)
116
+
117
+ output_queue = queue.Queue()
118
+
119
+ def read_output():
120
+ assert self.proc is not None and self.proc.stdout is not None
121
+ for output_line in self.proc.stdout:
122
+ output_queue.put(output_line)
123
+ output_queue.put(None)
124
+
125
+ threading.Thread(target=read_output, daemon=True).start()
126
+ logs = []
127
+ deadline = time.monotonic() + TUNNEL_TIMEOUT_SECONDS
128
+
129
+ while time.monotonic() < deadline:
130
+ try:
131
+ line = output_queue.get(timeout=0.25)
132
+ except queue.Empty:
133
+ if self.proc.poll() is not None:
134
+ break
135
+ continue
136
+ if line is None:
137
+ break
138
+
139
+ line = line.rstrip()
140
+ logs.append(line)
141
+ match = re.search(r"start proxy success:\s*(https?://\S+)", line)
142
+ if match:
143
+ self.url = match.group(1)
144
+ return self.url
145
+ if "login to server failed" in line.lower():
146
+ break
147
+
148
+ self.stop()
149
+ raise RuntimeError(
150
+ "Gradio 곡유 ν„°λ„μ—μ„œ 접속 URL을 λ°›μ§€ λͺ»ν–ˆμ–΄.\n"
151
+ + ("\n".join(logs[-30:]) if logs else "(frpc λ‘œκ·Έκ°€ μ—†μ–΄)")
152
+ )
153
+
154
+ def stop(self):
155
+ if self.proc is not None:
156
+ if self.proc.poll() is None:
157
+ print(
158
+ f"[Gradio] 터널 μ’…λ£Œ: {self.local_host}:{self.local_port} "
159
+ f"<> {self.url or 'URL 미확인'}"
160
+ )
161
+ self.proc.terminate()
162
+ try:
163
+ self.proc.wait(timeout=5)
164
+ except subprocess.TimeoutExpired:
165
+ self.proc.kill()
166
+ self.proc.wait()
167
+ self.proc = None
168
+
169
+
170
+ def setup_gradio_tunnel(
171
+ local_host=LOCAL_HOST,
172
+ local_port=LOCAL_PORT,
173
+ share_server_address=GRADIO_SHARE_SERVER_ADDRESS,
174
+ ):
175
+ if share_server_address is None:
176
+ response = requests.get(GRADIO_API_SERVER, timeout=10)
177
+ response.raise_for_status()
178
+ payload = response.json()
179
+ if not payload:
180
+ raise RuntimeError("Gradio APIμ—μ„œ 터널 μ„œλ²„ 정보λ₯Ό λ°›μ§€ λͺ»ν–ˆμ–΄.")
181
+ remote_host = payload[0]["host"]
182
+ remote_port = int(payload[0]["port"])
183
+ else:
184
+ remote_host, port_text = share_server_address.rsplit(":", 1)
185
+ remote_port = int(port_text)
186
+
187
+ tunnel = GradioTunnel(
188
+ remote_host, remote_port, local_host, local_port, secrets.token_urlsafe(32)
189
+ )
190
+ return tunnel.start()
191
+
192
+
193
+ # -----------------------------------------------------------------------------
194
+ # Cloudflare quick tunnel
195
+ # -----------------------------------------------------------------------------
196
+ def _resolve_cloudflared_binary() -> str:
197
+ if shutil.which("cloudflared"):
198
+ return "cloudflared"
199
+
200
+ for candidate in (SCRIPT_DIR / "cloudflared", REPO_DIR / "cloudflared"):
201
+ if candidate.exists():
202
+ if not os.access(candidate, os.X_OK):
203
+ candidate.chmod(
204
+ candidate.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
205
+ )
206
+ return str(candidate)
207
+
208
+ raise FileNotFoundError(
209
+ "cloudflared λ°”μ΄λ„ˆλ¦¬λ₯Ό μ°Ύμ§€ λͺ»ν–ˆμ–΄. PATH에 μ„€μΉ˜ν•˜κ±°λ‚˜ "
210
+ f"{REPO_DIR / 'cloudflared'} κ²½λ‘œμ— μ€€λΉ„ν•΄ 쀘."
211
+ )
212
+
213
+
214
+ def start_cloudflared_tunnel(port):
215
+ global cloudflared_proc, cloudflared_url
216
+
217
+ cf_bin = _resolve_cloudflared_binary()
218
+ print("[Cloudflare] 터널 μ‹œμž‘ 쀑...")
219
+ cloudflared_proc = subprocess.Popen(
220
+ [
221
+ cf_bin, "tunnel", "--no-autoupdate", "--url",
222
+ f"http://{LOCAL_HOST}:{port}",
223
+ ],
224
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
225
+ text=True, bufsize=1,
226
+ )
227
+ atexit.register(stop_cloudflared)
228
+
229
+ output_queue = queue.Queue()
230
+
231
+ def read_output():
232
+ assert cloudflared_proc is not None and cloudflared_proc.stdout is not None
233
+ for output_line in cloudflared_proc.stdout:
234
+ output_queue.put(output_line)
235
+ output_queue.put(None)
236
+
237
+ threading.Thread(target=read_output, daemon=True).start()
238
+ logs = []
239
+ deadline = time.monotonic() + TUNNEL_TIMEOUT_SECONDS
240
+
241
+ while time.monotonic() < deadline:
242
+ try:
243
+ line = output_queue.get(timeout=0.25)
244
+ except queue.Empty:
245
+ if cloudflared_proc.poll() is not None:
246
+ break
247
+ continue
248
+ if line is None:
249
+ break
250
+
251
+ line = line.rstrip()
252
+ logs.append(line)
253
+ match = re.search(r"https://[a-zA-Z0-9.-]+\.trycloudflare\.com", line)
254
+ if match:
255
+ cloudflared_url = match.group(0)
256
+ return cloudflared_url
257
+
258
+ stop_cloudflared()
259
+ raise RuntimeError(
260
+ "Cloudflare URL을 κ°€μ Έμ˜€μ§€ λͺ»ν–ˆμ–΄.\n"
261
+ + ("\n".join(logs[-30:]) if logs else "(cloudflared λ‘œκ·Έκ°€ μ—†μ–΄)")
262
+ )
263
+
264
+
265
+ def stop_cloudflared():
266
+ global cloudflared_proc
267
+ if cloudflared_proc is not None:
268
+ if cloudflared_proc.poll() is None:
269
+ print(
270
+ f"[Cloudflare] 터널 μ’…λ£Œ: {LOCAL_HOST}:{LOCAL_PORT} "
271
+ f"<> {cloudflared_url or 'URL 미확인'}"
272
+ )
273
+ cloudflared_proc.terminate()
274
+ try:
275
+ cloudflared_proc.wait(timeout=5)
276
+ except subprocess.TimeoutExpired:
277
+ cloudflared_proc.kill()
278
+ cloudflared_proc.wait()
279
+ cloudflared_proc = None
280
+
281
+
282
+ # -----------------------------------------------------------------------------
283
+ # Anima Training UI lifecycle
284
+ # -----------------------------------------------------------------------------
285
+ def _terminate_process_group(proc: subprocess.Popen, label: str, timeout: float = 10.0):
286
+ if proc.poll() is not None:
287
+ return
288
+ print(f"[{label}] ν”„λ‘œμ„ΈμŠ€ μ’…λ£Œ 쀑...")
289
+ try:
290
+ pgid = os.getpgid(proc.pid)
291
+ os.killpg(pgid, signal.SIGTERM)
292
+ except (ProcessLookupError, OSError):
293
+ proc.terminate()
294
+
295
+ try:
296
+ proc.wait(timeout=timeout)
297
+ except subprocess.TimeoutExpired:
298
+ try:
299
+ pgid = os.getpgid(proc.pid)
300
+ os.killpg(pgid, signal.SIGKILL)
301
+ except (ProcessLookupError, OSError):
302
+ proc.kill()
303
+ proc.wait()
304
+
305
+
306
+ def wait_for_ui(timeout=UI_START_TIMEOUT_SECONDS) -> bool:
307
+ """Wait until Anima Training UI responds over HTTP on LOCAL_PORT."""
308
+ deadline = time.monotonic() + timeout
309
+ test_url = f"http://{LOCAL_HOST}:{LOCAL_PORT}/"
310
+
311
+ while time.monotonic() < deadline:
312
+ if ui_proc is None or ui_proc.poll() is not None:
313
+ return False
314
+ try:
315
+ response = requests.get(test_url, timeout=2)
316
+ if response.status_code < 500:
317
+ return True
318
+ except requests.RequestException:
319
+ pass
320
+ time.sleep(0.5)
321
+ return False
322
+
323
+
324
+ def shutdown():
325
+ global _shutdown_started, ui_proc
326
+ with _shutdown_lock:
327
+ if _shutdown_started:
328
+ return
329
+ _shutdown_started = True
330
+
331
+ print("\nπŸ›‘ Anima Training UI와 터널을 μ’…λ£Œν•˜λŠ” 쀑...")
332
+ stop_cloudflared()
333
+ for tunnel in reversed(CURRENT_TUNNELS):
334
+ tunnel.stop()
335
+
336
+ if ui_proc is not None:
337
+ _terminate_process_group(ui_proc, "Anima UI")
338
+ ui_proc = None
339
+ print("βœ… λͺ¨λ“  ν”„λ‘œμ„ΈμŠ€λ₯Ό μ’…λ£Œν–ˆμ–΄.")
340
+
341
+
342
+ def main():
343
+ global ui_proc
344
+
345
+ if not START_SCRIPT.is_file():
346
+ print(
347
+ f"❌ μ‹œμž‘ 슀크립트λ₯Ό 찾을 수 μ—†μ–΄: {START_SCRIPT}\n"
348
+ "λ ˆν¬κ°€ μ˜¬λ°”λ₯΄κ²Œ ν΄λ‘ λ˜μ—ˆλŠ”μ§€ 확인해 쀘.",
349
+ file=sys.stderr,
350
+ )
351
+ return 1
352
+
353
+ if not os.access(START_SCRIPT, os.X_OK):
354
+ START_SCRIPT.chmod(
355
+ START_SCRIPT.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
356
+ )
357
+
358
+ print("\n" + "=" * 60)
359
+ print("πŸš€ Anima Training UI (Port 3000) + 이쀑 터널 μ‹œμž‘")
360
+ print("=" * 60 + "\n")
361
+
362
+ print("[Anima UI] start_linux.sh μ‹€ν–‰ 쀑...")
363
+ ui_proc = subprocess.Popen(
364
+ ["bash", str(START_SCRIPT)] + sys.argv[1:],
365
+ cwd=str(REPO_DIR),
366
+ stdout=subprocess.PIPE,
367
+ stderr=subprocess.STDOUT,
368
+ text=True,
369
+ bufsize=1,
370
+ start_new_session=True,
371
+ )
372
+
373
+ ui_log_queue: queue.Queue = queue.Queue()
374
+
375
+ def stream_ui_logs():
376
+ assert ui_proc is not None and ui_proc.stdout is not None
377
+ for line in ui_proc.stdout:
378
+ ui_log_queue.put(line.rstrip())
379
+ ui_log_queue.put(None)
380
+
381
+ threading.Thread(target=stream_ui_logs, daemon=True).start()
382
+
383
+ print("[Anima UI] μ›Ή μ„œλ²„ μ€€λΉ„ λŒ€κΈ° 쀑...")
384
+ if not wait_for_ui():
385
+ recent_logs = []
386
+ while not ui_log_queue.empty():
387
+ item = ui_log_queue.get_nowait()
388
+ if item is not None:
389
+ recent_logs.append(item)
390
+ if ui_proc.poll() is not None:
391
+ print(
392
+ f"❌ Anima UI ν”„λ‘œμ„ΈμŠ€κ°€ μ’…λ£Œλμ–΄. μ’…λ£Œ μ½”λ“œ: {ui_proc.returncode}",
393
+ file=sys.stderr,
394
+ )
395
+ else:
396
+ print(
397
+ f"❌ {UI_START_TIMEOUT_SECONDS}초 μ•ˆμ— Anima UIκ°€ μ€€λΉ„λ˜μ§€ μ•Šμ•˜μ–΄.",
398
+ file=sys.stderr,
399
+ )
400
+ if recent_logs:
401
+ print("\n[졜근 Anima UI 둜그]\n" + "\n".join(recent_logs[-30:]), file=sys.stderr)
402
+ return 1
403
+
404
+ print(f"βœ… Anima Training UI μ€€λΉ„ μ™„λ£Œ! (http://{LOCAL_HOST}:{LOCAL_PORT})\n")
405
+
406
+ gradio_url = None
407
+ cloudflare_url_result = None
408
+
409
+ def run_gradio():
410
+ nonlocal gradio_url
411
+ try:
412
+ print("[Gradio] 터널 μ‹œμž‘ 쀑...")
413
+ gradio_url = setup_gradio_tunnel()
414
+ except Exception as exc:
415
+ print(f"⚠️ [Gradio] 터널 생성 μ‹€νŒ¨: {exc}", file=sys.stderr)
416
+
417
+ def run_cloudflare():
418
+ nonlocal cloudflare_url_result
419
+ try:
420
+ cloudflare_url_result = start_cloudflared_tunnel(LOCAL_PORT)
421
+ except Exception as exc:
422
+ print(f"⚠️ [Cloudflare] 터널 생성 μ‹€νŒ¨: {exc}", file=sys.stderr)
423
+
424
+ gradio_thread = threading.Thread(target=run_gradio, daemon=True)
425
+ cloudflare_thread = threading.Thread(target=run_cloudflare, daemon=True)
426
+ gradio_thread.start()
427
+ cloudflare_thread.start()
428
+ gradio_thread.join(TUNNEL_TIMEOUT_SECONDS + 15)
429
+ cloudflare_thread.join(TUNNEL_TIMEOUT_SECONDS + 15)
430
+
431
+ print("\n🌐 Anima Training UI 접속 URL:")
432
+ print(f" β€’ Gradio: {gradio_url or '❌ 생성 μ‹€νŒ¨'}")
433
+ print(f" β€’ Cloudflare: {cloudflare_url_result or '❌ 생성 μ‹€νŒ¨'}")
434
+
435
+ if not gradio_url and not cloudflare_url_result:
436
+ print(
437
+ "\n⚠️ 두 터널 λͺ¨λ‘ μƒμ„±λ˜μ§€ μ•Šμ•˜μ–΄. 둜컬 UI μ„œλ²„λŠ” 계속 μ‹€ν–‰ν• κ²Œ.",
438
+ file=sys.stderr,
439
+ )
440
+
441
+ print("\nπŸ’‘ 생성에 μ„±κ³΅ν•œ URL을 ν΄λ¦­ν•΄μ„œ μ ‘μ†ν•˜λ©΄ 돼.")
442
+ print("πŸ’‘ 이 셀을 μ€‘λ‹¨ν•˜λ©΄ Anima UI와 λͺ¨λ“  터널이 μ’…λ£ŒλΌ.")
443
+ print("\n" + "-" * 60)
444
+ print("πŸ“œ Anima Training UI μ‹€ν–‰ 둜그")
445
+ print("-" * 60 + "\n")
446
+
447
+ try:
448
+ while ui_proc is not None and ui_proc.poll() is None:
449
+ try:
450
+ line = ui_log_queue.get(timeout=0.25)
451
+ if line is not None:
452
+ print(line)
453
+ except queue.Empty:
454
+ continue
455
+ except KeyboardInterrupt:
456
+ pass
457
+ finally:
458
+ shutdown()
459
+ return 0
460
+
461
+
462
+ if __name__ == "__main__":
463
+ try:
464
+ exit_code = main()
465
+ except KeyboardInterrupt:
466
+ exit_code = 130
467
+ shutdown()
468
+ except Exception as exc:
469
+ print(f"❌ μ‹€ν–‰ 쀑 예기치 μ•Šμ€ 였λ₯˜: {exc}", file=sys.stderr)
470
+ exit_code = 1
471
+ shutdown()
472
+
473
+ if exit_code:
474
+ sys.exit(exit_code)
modal/prepare.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Anima Standalone Trainer - Setup & Download Tools
3
+ - Installs Node.js 22, system tools (aria2, curl, git), repo, venv/requirements, and UI deps.
4
+ - Registers IPython line magic: %download URL [filename]
5
+
6
+ Usage in Jupyter:
7
+ hf_token = "hf_..."
8
+ civitai_token = "..."
9
+
10
+ %cd /content/dataset
11
+ %download https://huggingface.co/datasets/arcacolab/for_lora/tree/main/realskin_v5_redo
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import re
18
+ import shutil
19
+ import stat
20
+ import subprocess
21
+ import sys
22
+ import urllib.parse
23
+ from pathlib import Path
24
+
25
+ # ---------------------------------------------------------------------
26
+ # Installation settings
27
+ # ---------------------------------------------------------------------
28
+
29
+ CONTENT_DIR = Path("/content")
30
+ TRAINER_DIR = CONTENT_DIR / "Anima-Standalone-Trainer"
31
+ TRAINER_REPO = "https://github.com/gazingstars123/Anima-Standalone-Trainer.git"
32
+ DEFAULT_DATASET_DIR = CONTENT_DIR / "dataset"
33
+
34
+
35
+ # ---------------------------------------------------------------------
36
+ # Output helpers
37
+ # ---------------------------------------------------------------------
38
+
39
+ def _status(message: str) -> None:
40
+ print(f" {message}", flush=True)
41
+
42
+
43
+ def _run_quiet(command: list[str], *, label: str, cwd: Path | None = None) -> None:
44
+ """Run a command quietly, printing output if it fails."""
45
+ result = subprocess.run(
46
+ command,
47
+ cwd=str(cwd) if cwd else None,
48
+ stdout=subprocess.PIPE,
49
+ stderr=subprocess.STDOUT,
50
+ text=True,
51
+ )
52
+ if result.returncode != 0:
53
+ _status(f"❌ {label} μ‹€νŒ¨ (μ’…λ£Œ μ½”λ“œ: {result.returncode})")
54
+ if result.stdout:
55
+ print(result.stdout.rstrip())
56
+ raise RuntimeError(f"{label} failed")
57
+
58
+
59
+ # ---------------------------------------------------------------------
60
+ # Environment setup
61
+ # ---------------------------------------------------------------------
62
+
63
+ def _install_system_packages() -> None:
64
+ """Ensure aria2, curl, git, and ca-certificates/gnupg are available."""
65
+ required = {
66
+ "aria2c": "aria2",
67
+ "curl": "curl",
68
+ "git": "git",
69
+ }
70
+ missing = [pkg for exe, pkg in required.items() if not shutil.which(exe)]
71
+ if not missing:
72
+ return
73
+
74
+ if not shutil.which("apt-get"):
75
+ raise RuntimeError(
76
+ "ν•„μˆ˜ μ‹œμŠ€ν…œ 도ꡬ가 μ—†κ³  apt-get도 μ‚¬μš©ν•  수 μ—†μ–΄: " + ", ".join(missing)
77
+ )
78
+
79
+ _status("aria2, curl, git μ„€μΉ˜ 쀑...")
80
+ _run_quiet(["apt-get", "update", "-qq"], label="apt νŒ¨ν‚€μ§€ λͺ©λ‘ κ°±μ‹ ")
81
+ _run_quiet(["apt-get", "install", "-y", "-qq", *missing], label="μ‹œμŠ€ν…œ 도ꡬ μ„€μΉ˜")
82
+
83
+ still_missing = [exe for exe in required if not shutil.which(exe)]
84
+ if still_missing:
85
+ raise RuntimeError("μ„€μΉ˜ 후에도 μ‹€ν–‰ νŒŒμΌμ„ 찾을 수 μ—†μ–΄: " + ", ".join(still_missing))
86
+
87
+
88
+ def _install_nodejs() -> None:
89
+ """Ensure Node.js 22.x and npm are available for training-ui."""
90
+ if shutil.which("node") and shutil.which("npm"):
91
+ ver = subprocess.check_output(["node", "-v"], text=True).strip()
92
+ _status(f"β†ͺ Node.js 이미 μ„€μΉ˜λ¨ ({ver}).")
93
+ return
94
+
95
+ if not shutil.which("apt-get"):
96
+ raise RuntimeError("Node.js/npm이 μ—†κ³  apt-get도 μ‚¬μš©ν•  수 μ—†μ–΄.")
97
+
98
+ _status("Node.js 22.x 및 npm μ„€μΉ˜ 쀑...")
99
+ _run_quiet(["apt-get", "update", "-qq"], label="apt νŒ¨ν‚€μ§€ λͺ©λ‘ κ°±μ‹ ")
100
+ _run_quiet(
101
+ ["apt-get", "install", "-y", "-qq", "ca-certificates", "curl", "gnupg"],
102
+ label="Node μ €μž₯μ†Œμš© νŒ¨ν‚€μ§€ μ„€μΉ˜",
103
+ )
104
+ Path("/etc/apt/keyrings").mkdir(parents=True, exist_ok=True)
105
+ _run_quiet(
106
+ [
107
+ "bash",
108
+ "-c",
109
+ "curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key "
110
+ "| gpg --dearmor --yes -o /etc/apt/keyrings/nodesource.gpg",
111
+ ],
112
+ label="NodeSource GPG ν‚€ 등둝",
113
+ )
114
+ _run_quiet(
115
+ [
116
+ "bash",
117
+ "-c",
118
+ 'echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] '
119
+ 'https://deb.nodesource.com/node_22.x nodistro main" '
120
+ "| tee /etc/apt/sources.list.d/nodesource.list > /dev/null",
121
+ ],
122
+ label="NodeSource μ €μž₯μ†Œ μΆ”κ°€",
123
+ )
124
+ _run_quiet(["apt-get", "update", "-qq"], label="NodeSource λͺ©λ‘ κ°±μ‹ ")
125
+ _run_quiet(["apt-get", "install", "-y", "-qq", "nodejs"], label="Node.js 22 μ„€μΉ˜")
126
+
127
+ if not (shutil.which("node") and shutil.which("npm")):
128
+ raise RuntimeError("Node.js/npm μ„€μΉ˜ ν›„ μ‹€ν–‰ νŒŒμΌμ„ 찾을 수 μ—†μ–΄.")
129
+
130
+
131
+ def _install_python_packages() -> None:
132
+ packages = ["requests", "huggingface_hub"]
133
+ _status("Python 헬퍼 νŒ¨ν‚€μ§€ 확인 쀑...")
134
+ _run_quiet(
135
+ [sys.executable, "-m", "pip", "install", "-q", *packages],
136
+ label="Python 헬퍼 νŒ¨ν‚€μ§€ μ„€μΉ˜",
137
+ )
138
+
139
+
140
+ def _clone_or_update_repo(repo_url: str, destination: Path, *, label: str) -> None:
141
+ if destination.exists():
142
+ if (destination / ".git").is_dir():
143
+ _status(f"β†ͺ {label} 이미 μ‘΄μž¬ν•¨. μ΅œμ‹  변경사항 반영 μ‹œλ„...")
144
+ try:
145
+ _run_quiet(["git", "pull", "--ff-only"], label=f"{label} μ—…λ°μ΄νŠΈ", cwd=destination)
146
+ except RuntimeError:
147
+ _status(f"β†ͺ {label}: git pull μƒλž΅ (둜컬 μƒνƒœ μœ μ§€).")
148
+ return
149
+ raise RuntimeError(f"{label} κ²½λ‘œκ°€ 이미 μ‘΄μž¬ν•˜μ§€λ§Œ Git μ €μž₯μ†Œκ°€ μ•„λ‹ˆμ•Ό: {destination}")
150
+
151
+ _status(f"{label} Clone 쀑...")
152
+ _run_quiet(["git", "clone", "--depth", "1", repo_url, str(destination)], label=f"{label} Clone")
153
+
154
+
155
+ def _run_trainer_setup() -> None:
156
+ setup_sh = TRAINER_DIR / "setup_env.sh"
157
+ start_sh = TRAINER_DIR / "training-ui" / "start_linux.sh"
158
+
159
+ for script in (setup_sh, start_sh):
160
+ if script.is_file():
161
+ script.chmod(script.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
162
+
163
+ if not setup_sh.is_file():
164
+ raise RuntimeError(f"setup_env.shλ₯Ό 찾을 수 μ—†μ–΄: {setup_sh}")
165
+
166
+ _status("Anima Standalone Trainer ν™˜κ²½(venv, νŒ¨ν‚€μ§€, UI) ꡬ성 쀑...")
167
+ _run_quiet(["bash", str(setup_sh)], label="setup_env.sh μ‹€ν–‰", cwd=TRAINER_DIR)
168
+
169
+
170
+ def setup() -> None:
171
+ CONTENT_DIR.mkdir(parents=True, exist_ok=True)
172
+ DEFAULT_DATASET_DIR.mkdir(parents=True, exist_ok=True)
173
+
174
+ _status("ν•„μˆ˜ 도ꡬ 확인 쀑...")
175
+ _install_system_packages()
176
+ _install_nodejs()
177
+ _install_python_packages()
178
+
179
+ _status("Anima Standalone Trainer μ„€μΉ˜ 쀑...")
180
+ _clone_or_update_repo(TRAINER_REPO, TRAINER_DIR, label="Anima-Standalone-Trainer")
181
+ _run_trainer_setup()
182
+
183
+ _status("ν™˜κ²½ ꡬ좕 μ™„λ£Œ.")
184
+
185
+
186
+ # ---------------------------------------------------------------------
187
+ # Download helpers (aria2c + Hugging Face /tree/ folder support)
188
+ # ---------------------------------------------------------------------
189
+
190
+ def _get_notebook_token(name: str) -> str:
191
+ """Read a token from IPython user namespace or environment variables."""
192
+ try:
193
+ from IPython import get_ipython
194
+
195
+ shell = get_ipython()
196
+ if shell is not None:
197
+ value = shell.user_ns.get(name, "")
198
+ if value:
199
+ return str(value).strip()
200
+ except Exception:
201
+ pass
202
+
203
+ env_val = os.environ.get(name, "") or os.environ.get(name.upper(), "")
204
+ return env_val.strip()
205
+
206
+
207
+ def _parse_hf_tree_url(url: str) -> tuple[str, str, str, str] | None:
208
+ """
209
+ Parse URLs like:
210
+ https://huggingface.co/datasets/<owner>/<repo>/tree/<branch>/<subpath>
211
+ https://huggingface.co/<owner>/<repo>/tree/<branch>/<subpath>
212
+ Returns (repo_id, repo_type, revision, subpath) or None if not a /tree/ URL.
213
+ """
214
+ parsed = urllib.parse.urlparse(url)
215
+ host = (parsed.hostname or "").lower()
216
+ if host != "huggingface.co" and not host.endswith(".huggingface.co"):
217
+ return None
218
+
219
+ parts = [urllib.parse.unquote(p) for p in parsed.path.strip("/").split("/") if p]
220
+ if len(parts) < 4:
221
+ return None
222
+
223
+ if parts[0] == "datasets":
224
+ if len(parts) < 5 or parts[3] != "tree":
225
+ return None
226
+ repo_type = "dataset"
227
+ repo_id = f"{parts[1]}/{parts[2]}"
228
+ revision = parts[4]
229
+ subpath = "/".join(parts[5:])
230
+ return repo_id, repo_type, revision, subpath
231
+
232
+ if parts[2] == "tree":
233
+ repo_type = "model"
234
+ repo_id = f"{parts[0]}/{parts[1]}"
235
+ revision = parts[3]
236
+ subpath = "/".join(parts[4:])
237
+ return repo_id, repo_type, revision, subpath
238
+
239
+ return None
240
+
241
+
242
+ def _download_hf_tree(
243
+ repo_id: str,
244
+ repo_type: str,
245
+ revision: str,
246
+ subpath: str,
247
+ target_name: str | None = None,
248
+ ) -> None:
249
+ try:
250
+ from huggingface_hub import snapshot_download
251
+ except ImportError:
252
+ _status("huggingface_hub μ„€μΉ˜ 쀑...")
253
+ _run_quiet([sys.executable, "-m", "pip", "install", "-q", "huggingface_hub"], label="huggingface_hub μ„€μΉ˜")
254
+ from huggingface_hub import snapshot_download
255
+
256
+ token = _get_notebook_token("hf_token") or None
257
+ cwd = Path.cwd()
258
+ folder_name = target_name or (Path(subpath).name if subpath else repo_id.split("/")[-1])
259
+ dest_dir = cwd / folder_name
260
+ dest_dir.mkdir(parents=True, exist_ok=True)
261
+
262
+ allow_patterns = [f"{subpath}/**", subpath] if subpath else None
263
+ _status(f"⬇️ HF {repo_type} 폴더 λ‹€μš΄λ‘œλ“œ 쀑: {repo_id} [{revision}] -> {dest_dir}")
264
+
265
+ try:
266
+ snapshot_download(
267
+ repo_id=repo_id,
268
+ repo_type=repo_type,
269
+ revision=revision,
270
+ local_dir=str(dest_dir),
271
+ allow_patterns=allow_patterns,
272
+ token=token,
273
+ )
274
+ # If subpath is nested (e.g. a/b/dataset), flatten into dest_dir if desired
275
+ nested = dest_dir / subpath if subpath else None
276
+ if nested and nested.is_dir() and nested != dest_dir:
277
+ for item in nested.iterdir():
278
+ target_item = dest_dir / item.name
279
+ if target_item.exists():
280
+ if target_item.is_dir():
281
+ shutil.rmtree(target_item)
282
+ else:
283
+ target_item.unlink()
284
+ shutil.move(str(item), str(target_item))
285
+ # Clean up empty parent directories created under dest_dir
286
+ top_prefix = subpath.split("/")[0]
287
+ top_dir = dest_dir / top_prefix
288
+ if top_dir.exists() and top_dir.is_dir():
289
+ shutil.rmtree(top_dir, ignore_errors=True)
290
+
291
+ _status(f"βœ… λ‹€μš΄λ‘œλ“œ μ™„λ£Œ: {dest_dir}")
292
+ except Exception as exc:
293
+ _status(f"❌ HF 폴더 λ‹€μš΄λ‘œλ“œ μ‹€νŒ¨: {exc}")
294
+
295
+
296
+ def _build_download_command(url: str, filename: str | None) -> list[str]:
297
+ parsed = urllib.parse.urlparse(url)
298
+ host = (parsed.hostname or "").lower()
299
+ headers: list[str] = []
300
+
301
+ if host == "huggingface.co" or host.endswith(".huggingface.co"):
302
+ token = _get_notebook_token("hf_token")
303
+ if token:
304
+ headers.append(f"Authorization: Bearer {token}")
305
+
306
+ elif host in ("civitai.com", "civitai.red") or host.endswith(".civitai.com") or host.endswith(".civitai.red"):
307
+ token = _get_notebook_token("civitai_token")
308
+ if token and "/api/download/models/" in parsed.path:
309
+ query = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
310
+ if not any(key.lower() == "token" for key, _ in query):
311
+ query.append(("token", token))
312
+ url = urllib.parse.urlunparse(
313
+ parsed._replace(query=urllib.parse.urlencode(query))
314
+ )
315
+
316
+ command = [
317
+ "aria2c",
318
+ "--continue=true",
319
+ "--allow-overwrite=true",
320
+ "--auto-file-renaming=false",
321
+ "--max-tries=5",
322
+ "--retry-wait=3",
323
+ "--connect-timeout=30",
324
+ "--timeout=60",
325
+ "--console-log-level=notice",
326
+ "--summary-interval=1",
327
+ "--download-result=hide",
328
+ "-x", "8",
329
+ "-s", "8",
330
+ "-k", "1M",
331
+ ]
332
+
333
+ for header in headers:
334
+ command.extend(["--header", header])
335
+
336
+ if filename:
337
+ command.extend(["--out", filename])
338
+
339
+ command.append(url)
340
+ return command
341
+
342
+
343
+ def _download(url: str, filename: str | None = None) -> None:
344
+ url = url.strip()
345
+ if not url:
346
+ _status("⚠️ λ‹€μš΄λ‘œλ“œ μ£Όμ†Œκ°€ λΉ„μ–΄ μžˆμ–΄.")
347
+ return
348
+
349
+ parsed = urllib.parse.urlparse(url)
350
+ if parsed.scheme not in ("http", "https") or not parsed.netloc:
351
+ _status("❌ μ˜¬λ°”λ₯Έ HTTP/HTTPS μ£Όμ†Œκ°€ μ•„λ‹ˆμ•Ό.")
352
+ return
353
+
354
+ hf_tree = _parse_hf_tree_url(url)
355
+ if hf_tree is not None:
356
+ repo_id, repo_type, revision, subpath = hf_tree
357
+ _download_hf_tree(repo_id, repo_type, revision, subpath, target_name=filename)
358
+ return
359
+
360
+ if not shutil.which("aria2c"):
361
+ _status("❌ aria2cκ°€ μ—†μ–΄. λ¨Όμ € prepare.pyλ₯Ό μ‹€ν–‰ν•΄ 쀘.")
362
+ return
363
+
364
+ if filename:
365
+ filename = Path(filename).name
366
+ else:
367
+ filename = Path(urllib.parse.unquote(parsed.path)).name or "downloaded_file"
368
+
369
+ command = _build_download_command(url, filename)
370
+
371
+ _status(f"⬇️ {filename} λ‹€μš΄λ‘œλ“œ 쀑...")
372
+ process = None
373
+ try:
374
+ process = subprocess.Popen(
375
+ command,
376
+ stdout=subprocess.PIPE,
377
+ stderr=subprocess.STDOUT,
378
+ text=True,
379
+ bufsize=1,
380
+ )
381
+
382
+ last_progress = ""
383
+ assert process.stdout is not None
384
+
385
+ for raw_line in process.stdout:
386
+ line = raw_line.strip()
387
+ if not line:
388
+ continue
389
+
390
+ if line.startswith("[#"):
391
+ progress = re.sub(r"\s+", " ", line)
392
+ if progress != last_progress:
393
+ print(f"\r ⬇️ {filename} {progress[:180]}", end="", flush=True)
394
+ last_progress = progress
395
+
396
+ return_code = process.wait()
397
+ if return_code == 0:
398
+ print(f"\r βœ… {filename} λ‹€μš΄λ‘œλ“œ μ™„λ£Œ.{' ' * 30}")
399
+ else:
400
+ print()
401
+ _status(f"❌ {filename} λ‹€μš΄λ‘œλ“œ μ‹€νŒ¨ (aria2 μ’…λ£Œ μ½”λ“œ: {return_code})")
402
+ except KeyboardInterrupt:
403
+ if process is not None and process.poll() is None:
404
+ process.terminate()
405
+ process.wait()
406
+ print()
407
+ _status("λ‹€μš΄λ‘œλ“œ μ·¨μ†Œλ¨.")
408
+ except Exception as exc:
409
+ print()
410
+ _status(f"❌ λ‹€μš΄λ‘œλ“œ 쀑 였λ₯˜ λ°œμƒ: {exc}")
411
+
412
+
413
+ # ---------------------------------------------------------------------
414
+ # IPython magic registration
415
+ # ---------------------------------------------------------------------
416
+
417
+ def register_download_magic() -> None:
418
+ from IPython import get_ipython
419
+
420
+ shell = get_ipython()
421
+ if shell is None:
422
+ raise RuntimeError("이 νŒŒμΌμ€ Jupyter/IPython μ»€λ„μ—μ„œ μ‹€ν–‰ν•΄μ•Ό ν•΄.")
423
+
424
+ def download_magic(line: str) -> None:
425
+ import shlex
426
+
427
+ try:
428
+ args = shlex.split(line)
429
+ except ValueError as exc:
430
+ _status(f"❌ λͺ…λ Ήμ–΄ ν˜•μ‹ 였λ₯˜: {exc}")
431
+ return
432
+
433
+ if not args or len(args) > 2:
434
+ _status("μ‚¬μš©λ²•: %download URL [filename]")
435
+ return
436
+
437
+ _download(args[0], args[1] if len(args) == 2 else None)
438
+
439
+ shell.register_magic_function(download_magic, "line", "download")
440
+
441
+
442
+ # ---------------------------------------------------------------------
443
+ # Run setup and register the magic when executed with %run.
444
+ # ---------------------------------------------------------------------
445
+
446
+ try:
447
+ setup()
448
+ register_download_magic()
449
+ except Exception as error:
450
+ print(f"\n❌ prepare.py μ΄ˆκΈ°ν™” μ‹€νŒ¨: {error}")
451
+ raise