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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
#!/usr/bin/env python3
"""Launch Anima Training UI and expose it through Gradio and Cloudflare quick tunnels."""

import atexit
import os
import platform
import queue
import re
import secrets
import shutil
import signal
import stat
import subprocess
import sys
import threading
import time
from pathlib import Path
from typing import List, Optional

import requests

# -----------------------------------------------------------------------------
# Configuration
# -----------------------------------------------------------------------------
REPO_DIR = Path("/content/Anima-Standalone-Trainer")
START_SCRIPT = REPO_DIR / "training-ui" / "start_linux.sh"
LOCAL_HOST = "127.0.0.1"
LOCAL_PORT = 3000

GRADIO_VERSION = "0.2"
GRADIO_API_SERVER = "https://api.gradio.app/v2/tunnel-request"
GRADIO_SHARE_SERVER_ADDRESS = None
TUNNEL_TIMEOUT_SECONDS = 30
UI_START_TIMEOUT_SECONDS = 120

CURRENT_TUNNELS: List["GradioTunnel"] = []
cloudflared_proc: Optional[subprocess.Popen] = None
cloudflared_url: Optional[str] = None
ui_proc: Optional[subprocess.Popen] = None
_shutdown_started = False
_shutdown_lock = threading.Lock()


# -----------------------------------------------------------------------------
# Gradio tunnel
# -----------------------------------------------------------------------------
machine = platform.machine().lower()
if machine in ("x86_64", "x64", "amd64"):
    machine = "amd64"
elif machine in ("aarch64", "arm64"):
    machine = "arm64"

BINARY_REMOTE_NAME = f"frpc_{platform.system().lower()}_{machine}"
EXTENSION = ".exe" if os.name == "nt" else ""
BINARY_URL = (
    f"https://cdn-media.huggingface.co/frpc-gradio-{GRADIO_VERSION}/"
    f"{BINARY_REMOTE_NAME}{EXTENSION}"
)

SCRIPT_DIR = Path(__file__).resolve().parent


def _resolve_frpc_path() -> Path:
    filename = f"{BINARY_REMOTE_NAME}_v{GRADIO_VERSION}{EXTENSION}"
    for candidate in (SCRIPT_DIR / filename, REPO_DIR / filename):
        if candidate.exists():
            return candidate
    return SCRIPT_DIR / filename


BINARY_PATH = _resolve_frpc_path()


class GradioTunnel:
    def __init__(self, remote_host, remote_port, local_host, local_port, share_token):
        self.proc = None
        self.url = None
        self.remote_host = remote_host
        self.remote_port = remote_port
        self.local_host = local_host
        self.local_port = local_port
        self.share_token = share_token

    @staticmethod
    def download_binary():
        if BINARY_PATH.exists() and os.access(BINARY_PATH, os.X_OK):
            return

        print("[Gradio] frpc λ°”μ΄λ„ˆλ¦¬ λ‹€μš΄λ‘œλ“œ 쀑...")
        response = requests.get(BINARY_URL, timeout=30)
        if response.status_code == 403:
            raise OSError(
                "ν˜„μž¬ ν”Œλž«νΌμš© Gradio frpc λ°”μ΄λ„ˆλ¦¬λ₯Ό 내렀받을 수 μ—†μ–΄. "
                f"ν”Œλž«νΌ: {platform.uname()}"
            )
        response.raise_for_status()
        BINARY_PATH.write_bytes(response.content)
        BINARY_PATH.chmod(
            BINARY_PATH.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
        )

    def start(self) -> str:
        self.download_binary()
        command = [
            str(BINARY_PATH), "http", "-n", self.share_token,
            "-l", str(self.local_port), "-i", self.local_host,
            "--uc", "--sd", "random", "--ue", "--server_addr",
            f"{self.remote_host}:{self.remote_port}", "--disable_log_color",
        ]
        self.proc = subprocess.Popen(
            command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
            text=True, bufsize=1,
        )
        CURRENT_TUNNELS.append(self)
        atexit.register(self.stop)

        output_queue = queue.Queue()

        def read_output():
            assert self.proc is not None and self.proc.stdout is not None
            for output_line in self.proc.stdout:
                output_queue.put(output_line)
            output_queue.put(None)

        threading.Thread(target=read_output, daemon=True).start()
        logs = []
        deadline = time.monotonic() + TUNNEL_TIMEOUT_SECONDS

        while time.monotonic() < deadline:
            try:
                line = output_queue.get(timeout=0.25)
            except queue.Empty:
                if self.proc.poll() is not None:
                    break
                continue
            if line is None:
                break

            line = line.rstrip()
            logs.append(line)
            match = re.search(r"start proxy success:\s*(https?://\S+)", line)
            if match:
                self.url = match.group(1)
                return self.url
            if "login to server failed" in line.lower():
                break

        self.stop()
        raise RuntimeError(
            "Gradio 곡유 ν„°λ„μ—μ„œ 접속 URL을 λ°›μ§€ λͺ»ν–ˆμ–΄.\n"
            + ("\n".join(logs[-30:]) if logs else "(frpc λ‘œκ·Έκ°€ μ—†μ–΄)")
        )

    def stop(self):
        if self.proc is not None:
            if self.proc.poll() is None:
                print(
                    f"[Gradio] 터널 μ’…λ£Œ: {self.local_host}:{self.local_port} "
                    f"<> {self.url or 'URL 미확인'}"
                )
                self.proc.terminate()
                try:
                    self.proc.wait(timeout=5)
                except subprocess.TimeoutExpired:
                    self.proc.kill()
                    self.proc.wait()
            self.proc = None


def setup_gradio_tunnel(
    local_host=LOCAL_HOST,
    local_port=LOCAL_PORT,
    share_server_address=GRADIO_SHARE_SERVER_ADDRESS,
):
    if share_server_address is None:
        response = requests.get(GRADIO_API_SERVER, timeout=10)
        response.raise_for_status()
        payload = response.json()
        if not payload:
            raise RuntimeError("Gradio APIμ—μ„œ 터널 μ„œλ²„ 정보λ₯Ό λ°›μ§€ λͺ»ν–ˆμ–΄.")
        remote_host = payload[0]["host"]
        remote_port = int(payload[0]["port"])
    else:
        remote_host, port_text = share_server_address.rsplit(":", 1)
        remote_port = int(port_text)

    tunnel = GradioTunnel(
        remote_host, remote_port, local_host, local_port, secrets.token_urlsafe(32)
    )
    return tunnel.start()


# -----------------------------------------------------------------------------
# Cloudflare quick tunnel
# -----------------------------------------------------------------------------
def _resolve_cloudflared_binary() -> str:
    if shutil.which("cloudflared"):
        return "cloudflared"

    for candidate in (SCRIPT_DIR / "cloudflared", REPO_DIR / "cloudflared"):
        if candidate.exists():
            if not os.access(candidate, os.X_OK):
                candidate.chmod(
                    candidate.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
                )
            return str(candidate)

    raise FileNotFoundError(
        "cloudflared λ°”μ΄λ„ˆλ¦¬λ₯Ό μ°Ύμ§€ λͺ»ν–ˆμ–΄. PATH에 μ„€μΉ˜ν•˜κ±°λ‚˜ "
        f"{REPO_DIR / 'cloudflared'} κ²½λ‘œμ— μ€€λΉ„ν•΄ 쀘."
    )


def start_cloudflared_tunnel(port):
    global cloudflared_proc, cloudflared_url

    cf_bin = _resolve_cloudflared_binary()
    print("[Cloudflare] 터널 μ‹œμž‘ 쀑...")
    cloudflared_proc = subprocess.Popen(
        [
            cf_bin, "tunnel", "--no-autoupdate", "--url",
            f"http://{LOCAL_HOST}:{port}",
        ],
        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
        text=True, bufsize=1,
    )
    atexit.register(stop_cloudflared)

    output_queue = queue.Queue()

    def read_output():
        assert cloudflared_proc is not None and cloudflared_proc.stdout is not None
        for output_line in cloudflared_proc.stdout:
            output_queue.put(output_line)
        output_queue.put(None)

    threading.Thread(target=read_output, daemon=True).start()
    logs = []
    deadline = time.monotonic() + TUNNEL_TIMEOUT_SECONDS

    while time.monotonic() < deadline:
        try:
            line = output_queue.get(timeout=0.25)
        except queue.Empty:
            if cloudflared_proc.poll() is not None:
                break
            continue
        if line is None:
            break

        line = line.rstrip()
        logs.append(line)
        match = re.search(r"https://[a-zA-Z0-9.-]+\.trycloudflare\.com", line)
        if match:
            cloudflared_url = match.group(0)
            return cloudflared_url

    stop_cloudflared()
    raise RuntimeError(
        "Cloudflare URL을 κ°€μ Έμ˜€μ§€ λͺ»ν–ˆμ–΄.\n"
        + ("\n".join(logs[-30:]) if logs else "(cloudflared λ‘œκ·Έκ°€ μ—†μ–΄)")
    )


def stop_cloudflared():
    global cloudflared_proc
    if cloudflared_proc is not None:
        if cloudflared_proc.poll() is None:
            print(
                f"[Cloudflare] 터널 μ’…λ£Œ: {LOCAL_HOST}:{LOCAL_PORT} "
                f"<> {cloudflared_url or 'URL 미확인'}"
            )
            cloudflared_proc.terminate()
            try:
                cloudflared_proc.wait(timeout=5)
            except subprocess.TimeoutExpired:
                cloudflared_proc.kill()
                cloudflared_proc.wait()
        cloudflared_proc = None


# -----------------------------------------------------------------------------
# Anima Training UI lifecycle
# -----------------------------------------------------------------------------
def _terminate_process_group(proc: subprocess.Popen, label: str, timeout: float = 10.0):
    if proc.poll() is not None:
        return
    print(f"[{label}] ν”„λ‘œμ„ΈμŠ€ μ’…λ£Œ 쀑...")
    try:
        pgid = os.getpgid(proc.pid)
        os.killpg(pgid, signal.SIGTERM)
    except (ProcessLookupError, OSError):
        proc.terminate()

    try:
        proc.wait(timeout=timeout)
    except subprocess.TimeoutExpired:
        try:
            pgid = os.getpgid(proc.pid)
            os.killpg(pgid, signal.SIGKILL)
        except (ProcessLookupError, OSError):
            proc.kill()
        proc.wait()


def wait_for_ui(timeout=UI_START_TIMEOUT_SECONDS) -> bool:
    """Wait until Anima Training UI responds over HTTP on LOCAL_PORT."""
    deadline = time.monotonic() + timeout
    test_url = f"http://{LOCAL_HOST}:{LOCAL_PORT}/"

    while time.monotonic() < deadline:
        if ui_proc is None or ui_proc.poll() is not None:
            return False
        try:
            response = requests.get(test_url, timeout=2)
            if response.status_code < 500:
                return True
        except requests.RequestException:
            pass
        time.sleep(0.5)
    return False


def shutdown():
    global _shutdown_started, ui_proc
    with _shutdown_lock:
        if _shutdown_started:
            return
        _shutdown_started = True

    print("\nπŸ›‘ Anima Training UI와 터널을 μ’…λ£Œν•˜λŠ” 쀑...")
    stop_cloudflared()
    for tunnel in reversed(CURRENT_TUNNELS):
        tunnel.stop()

    if ui_proc is not None:
        _terminate_process_group(ui_proc, "Anima UI")
        ui_proc = None
    print("βœ… λͺ¨λ“  ν”„λ‘œμ„ΈμŠ€λ₯Ό μ’…λ£Œν–ˆμ–΄.")


def main():
    global ui_proc

    if not START_SCRIPT.is_file():
        print(
            f"❌ μ‹œμž‘ 슀크립트λ₯Ό 찾을 수 μ—†μ–΄: {START_SCRIPT}\n"
            "λ ˆν¬κ°€ μ˜¬λ°”λ₯΄κ²Œ ν΄λ‘ λ˜μ—ˆλŠ”μ§€ 확인해 쀘.",
            file=sys.stderr,
        )
        return 1

    if not os.access(START_SCRIPT, os.X_OK):
        START_SCRIPT.chmod(
            START_SCRIPT.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
        )

    print("\n" + "=" * 60)
    print("πŸš€ Anima Training UI (Port 3000) + 이쀑 터널 μ‹œμž‘")
    print("=" * 60 + "\n")

    print("[Anima UI] start_linux.sh μ‹€ν–‰ 쀑...")
    ui_proc = subprocess.Popen(
        ["bash", str(START_SCRIPT)] + sys.argv[1:],
        cwd=str(REPO_DIR),
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
        bufsize=1,
        start_new_session=True,
    )

    ui_log_queue: queue.Queue = queue.Queue()

    def stream_ui_logs():
        assert ui_proc is not None and ui_proc.stdout is not None
        for line in ui_proc.stdout:
            ui_log_queue.put(line.rstrip())
        ui_log_queue.put(None)

    threading.Thread(target=stream_ui_logs, daemon=True).start()

    print("[Anima UI] μ›Ή μ„œλ²„ μ€€λΉ„ λŒ€κΈ° 쀑...")
    if not wait_for_ui():
        recent_logs = []
        while not ui_log_queue.empty():
            item = ui_log_queue.get_nowait()
            if item is not None:
                recent_logs.append(item)
        if ui_proc.poll() is not None:
            print(
                f"❌ Anima UI ν”„λ‘œμ„ΈμŠ€κ°€ μ’…λ£Œλμ–΄. μ’…λ£Œ μ½”λ“œ: {ui_proc.returncode}",
                file=sys.stderr,
            )
        else:
            print(
                f"❌ {UI_START_TIMEOUT_SECONDS}초 μ•ˆμ— Anima UIκ°€ μ€€λΉ„λ˜μ§€ μ•Šμ•˜μ–΄.",
                file=sys.stderr,
            )
        if recent_logs:
            print("\n[졜근 Anima UI 둜그]\n" + "\n".join(recent_logs[-30:]), file=sys.stderr)
        return 1

    print(f"βœ… Anima Training UI μ€€λΉ„ μ™„λ£Œ! (http://{LOCAL_HOST}:{LOCAL_PORT})\n")

    gradio_url = None
    cloudflare_url_result = None

    def run_gradio():
        nonlocal gradio_url
        try:
            print("[Gradio] 터널 μ‹œμž‘ 쀑...")
            gradio_url = setup_gradio_tunnel()
        except Exception as exc:
            print(f"⚠️ [Gradio] 터널 생성 μ‹€νŒ¨: {exc}", file=sys.stderr)

    def run_cloudflare():
        nonlocal cloudflare_url_result
        try:
            cloudflare_url_result = start_cloudflared_tunnel(LOCAL_PORT)
        except Exception as exc:
            print(f"⚠️ [Cloudflare] 터널 생성 μ‹€νŒ¨: {exc}", file=sys.stderr)

    gradio_thread = threading.Thread(target=run_gradio, daemon=True)
    cloudflare_thread = threading.Thread(target=run_cloudflare, daemon=True)
    gradio_thread.start()
    cloudflare_thread.start()
    gradio_thread.join(TUNNEL_TIMEOUT_SECONDS + 15)
    cloudflare_thread.join(TUNNEL_TIMEOUT_SECONDS + 15)

    print("\n🌐 Anima Training UI 접속 URL:")
    print(f"   β€’ Gradio:     {gradio_url or '❌ 생성 μ‹€νŒ¨'}")
    print(f"   β€’ Cloudflare: {cloudflare_url_result or '❌ 생성 μ‹€νŒ¨'}")

    if not gradio_url and not cloudflare_url_result:
        print(
            "\n⚠️ 두 터널 λͺ¨λ‘ μƒμ„±λ˜μ§€ μ•Šμ•˜μ–΄. 둜컬 UI μ„œλ²„λŠ” 계속 μ‹€ν–‰ν• κ²Œ.",
            file=sys.stderr,
        )

    print("\nπŸ’‘ 생성에 μ„±κ³΅ν•œ URL을 ν΄λ¦­ν•΄μ„œ μ ‘μ†ν•˜λ©΄ 돼.")
    print("πŸ’‘ 이 셀을 μ€‘λ‹¨ν•˜λ©΄ Anima UI와 λͺ¨λ“  터널이 μ’…λ£ŒλΌ.")
    print("\n" + "-" * 60)
    print("πŸ“œ Anima Training UI μ‹€ν–‰ 둜그")
    print("-" * 60 + "\n")

    try:
        while ui_proc is not None and ui_proc.poll() is None:
            try:
                line = ui_log_queue.get(timeout=0.25)
                if line is not None:
                    print(line)
            except queue.Empty:
                continue
    except KeyboardInterrupt:
        pass
    finally:
        shutdown()
    return 0


if __name__ == "__main__":
    try:
        exit_code = main()
    except KeyboardInterrupt:
        exit_code = 130
        shutdown()
    except Exception as exc:
        print(f"❌ μ‹€ν–‰ 쀑 예기치 μ•Šμ€ 였λ₯˜: {exc}", file=sys.stderr)
        exit_code = 1
        shutdown()

    if exit_code:
        sys.exit(exit_code)