Download modal/launch_comfy.py from arcacolab/data: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/arcacolab/data/resolve/main/modal/launch_comfy.py
- Command line
-
hf download hf://arcacolab/data/modal/launch_comfy.py
-
curl -L -o launch_comfy.py https://huggingface.co/arcacolab/data/resolve/main/modal/launch_comfy.py
13.1 kB
| #!/usr/bin/env python3 | |
| """Launch ComfyUI and expose it through Gradio and Cloudflare quick tunnels.""" | |
| import atexit | |
| import os | |
| import platform | |
| import queue | |
| import re | |
| import secrets | |
| import stat | |
| import subprocess | |
| import sys | |
| import threading | |
| import time | |
| from pathlib import Path | |
| from typing import List, Optional | |
| import requests | |
| # ----------------------------------------------------------------------------- | |
| # Configuration | |
| # ----------------------------------------------------------------------------- | |
| COMFYUI_DIR = Path("/content/ComfyUI") | |
| COMFYUI_MAIN = COMFYUI_DIR / "main.py" | |
| LOCAL_HOST = "127.0.0.1" | |
| LOCAL_PORT = 8188 | |
| GRADIO_VERSION = "0.2" | |
| GRADIO_API_SERVER = "https://api.gradio.app/v2/tunnel-request" | |
| GRADIO_SHARE_SERVER_ADDRESS = None | |
| TUNNEL_TIMEOUT_SECONDS = 30 | |
| COMFYUI_START_TIMEOUT_SECONDS = 180 | |
| CURRENT_TUNNELS: List["GradioTunnel"] = [] | |
| cloudflared_proc: Optional[subprocess.Popen] = None | |
| cloudflared_url: Optional[str] = None | |
| comfyui_proc: Optional[subprocess.Popen] = None | |
| _shutdown_started = False | |
| _shutdown_lock = threading.Lock() | |
| # ----------------------------------------------------------------------------- | |
| # Gradio tunnel | |
| # ----------------------------------------------------------------------------- | |
| machine = platform.machine().lower() | |
| if machine in ("x86_64", "x64"): | |
| 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}" | |
| ) | |
| BINARY_PATH = Path(__file__).resolve().parent / ( | |
| f"{BINARY_REMOTE_NAME}_v{GRADIO_VERSION}{EXTENSION}" | |
| ) | |
| 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 | |
| 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 start_cloudflared_tunnel(port): | |
| global cloudflared_proc, cloudflared_url | |
| print("[Cloudflare] ν°λ μμ μ€...") | |
| cloudflared_proc = subprocess.Popen( | |
| [ | |
| "cloudflared", "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 | |
| # ----------------------------------------------------------------------------- | |
| # ComfyUI lifecycle | |
| # ----------------------------------------------------------------------------- | |
| def wait_for_comfyui(timeout=COMFYUI_START_TIMEOUT_SECONDS): | |
| """Wait until ComfyUI's local HTTP endpoint responds.""" | |
| deadline = time.monotonic() + timeout | |
| test_url = f"http://{LOCAL_HOST}:{LOCAL_PORT}/system_stats" | |
| while time.monotonic() < deadline: | |
| if comfyui_proc is None or comfyui_proc.poll() is not None: | |
| return False | |
| try: | |
| response = requests.get(test_url, timeout=2) | |
| if response.ok: | |
| return True | |
| except requests.RequestException: | |
| pass | |
| time.sleep(1) | |
| return False | |
| def shutdown(): | |
| global _shutdown_started, comfyui_proc | |
| with _shutdown_lock: | |
| if _shutdown_started: | |
| return | |
| _shutdown_started = True | |
| print("\nπ ComfyUIμ ν°λμ μ’ λ£νλ μ€...") | |
| stop_cloudflared() | |
| for tunnel in reversed(CURRENT_TUNNELS): | |
| tunnel.stop() | |
| if comfyui_proc is not None: | |
| if comfyui_proc.poll() is None: | |
| comfyui_proc.terminate() | |
| try: | |
| comfyui_proc.wait(timeout=10) | |
| except subprocess.TimeoutExpired: | |
| comfyui_proc.kill() | |
| comfyui_proc.wait() | |
| comfyui_proc = None | |
| print("β λͺ¨λ νλ‘μΈμ€λ₯Ό μ’ λ£νμ΄.") | |
| def main(): | |
| global comfyui_proc | |
| if not COMFYUI_MAIN.is_file(): | |
| print( | |
| f"β ComfyUIλ₯Ό μ°Ύμ μ μμ΄: {COMFYUI_MAIN}\n" | |
| "Cell 1μμ ComfyUI μ€μΉκ° μλ£λλμ§ νμΈν΄ μ€.", | |
| file=sys.stderr, | |
| ) | |
| return 1 | |
| print("\n" + "=" * 60) | |
| print("π ComfyUI + μ΄μ€ ν°λ μμ") | |
| print("=" * 60 + "\n") | |
| # launch_comfy.py λ€μ μ λ¬λ μΈμλ ComfyUI main.pyλ‘ κ·Έλλ‘ μ λ¬νλ€. | |
| comfyui_command = [ | |
| sys.executable, str(COMFYUI_MAIN), | |
| "--listen", LOCAL_HOST, "--port", str(LOCAL_PORT), | |
| ] + sys.argv[1:] | |
| print("[ComfyUI] μ€ν μ€...") | |
| print(f"[ComfyUI] μΆκ° μΈμ: {sys.argv[1:] or '(μμ)'}") | |
| comfyui_proc = subprocess.Popen(comfyui_command, cwd=str(COMFYUI_DIR)) | |
| print("[ComfyUI] μλ² μ€λΉ λκΈ° μ€...") | |
| if not wait_for_comfyui(): | |
| if comfyui_proc.poll() is not None: | |
| print( | |
| f"β ComfyUI νλ‘μΈμ€κ° μ’ λ£λμ΄. μ’ λ£ μ½λ: {comfyui_proc.returncode}", | |
| file=sys.stderr, | |
| ) | |
| else: | |
| print( | |
| f"β {COMFYUI_START_TIMEOUT_SECONDS}μ΄ μμ ComfyUIκ° μ€λΉλμ§ μμμ΄.", | |
| file=sys.stderr, | |
| ) | |
| return 1 | |
| print("β ComfyUI μλ² μ€λΉ μλ£!\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π ComfyUI μ μ 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β οΈ λ ν°λ λͺ¨λ μμ±λμ§ μμμ΄. λ‘컬 ComfyUIλ κ³μ μ€νν κ².", | |
| file=sys.stderr, | |
| ) | |
| print("\nπ‘ μμ±μ μ±κ³΅ν URLμ ν΄λ¦ν΄μ μ μνλ©΄ λΌ.") | |
| print("π‘ μ΄ μ μ μ€λ¨νλ©΄ ComfyUIμ λͺ¨λ ν°λμ΄ μ’ λ£λΌ.") | |
| print("\n" + "-" * 60) | |
| print("π ComfyUI μ€ν λ‘κ·Έ") | |
| print("-" * 60 + "\n") | |
| try: | |
| while comfyui_proc is not None and comfyui_proc.poll() is None: | |
| time.sleep(0.5) | |
| 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) | |