{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ComfyUI on Colab + Pinggy — Ready to Run\n",
    "\n",
    "**Cara pakai:**\n",
    "1. Runtime > Change runtime type > **T4 GPU**\n",
    "2. Jalankan cell dari atas ke bawah (satu-satu, tunggu selesai)\n",
    "3. Di cell terakhir akan muncul URL Pinggy → buka di browser"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Cek GPU & paket sistem\n",
    "!nvidia-smi\n",
    "!apt-get update -qq && apt-get install -y -qq wget aria2 libgl1-mesa-glx > /dev/null\n",
    "print(\"GPU OK\" if __import__('subprocess').run(['nvidia-smi'], capture_output=True).returncode == 0 else \"GPU NOT DETECTED — cek Runtime type!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2. Clone ComfyUI\n",
    "!git clone https://github.com/comfyanonymous/ComfyUI.git 2>&1 | tail -2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3. Install dependencies (skip torch dari requirements — Colab sudah punya torch CUDA)\n",
    "import subprocess, sys\n",
    "req = open('ComfyUI/requirements.txt').read().splitlines()\n",
    "req = [l for l in req if l.strip() and not l.strip().startswith('#') and 'torch' not in l.lower()]\n",
    "open('/tmp/comfy_req.txt','w').write('\\n'.join(req))\n",
    "!pip install -q -r /tmp/comfy_req.txt\n",
    "import torch\n",
    "print(\"torch\", torch.__version__, \"| CUDA:\", torch.cuda.is_available())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 4. (Opsional) Download model SD 1.5 — ganti URL kalau mau model lain\n",
    "# Model masuk ke ComfyUI/models/checkpoints/\n",
    "!mkdir -p ComfyUI/models/checkpoints\n",
    "# Contoh: DreamShaper 8 (bagus buat semua style). ~2GB. Skip kalau mau pakai model sendiri via UI.\n",
    "!wget -q --show-progress -O ComfyUI/models/checkpoints/dreamshaper_8.safetensors \"https://huggingface.co/Lykon/dreamshaper-8/resolve/main/dreamshaper_8.safetensors\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 5. Install Pinggy tunnel\n",
    "!pip install -q pinggy\n",
    "print(\"pinggy siap\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 6. Jalankan ComfyUI di background (port 8188)\n",
    "import subprocess, time, os\n",
    "os.chdir('ComfyUI')\n",
    "log = open('/content/comfy.log','w')\n",
    "p = subprocess.Popen(['python','main.py','--listen','0.0.0.0','--port','8188'],\n",
    "                     stdout=log, stderr=subprocess.STDOUT)\n",
    "print(\"ComfyUI PID:\", p.pid)\n",
    "# tunggu sampai server siap (max 120 detik)\n",
    "import urllib.request\n",
    "ok = False\n",
    "for i in range(120):\n",
    "    time.sleep(1)\n",
    "    try:\n",
    "        urllib.request.urlopen('http://127.0.0.1:8188/system_stats', timeout=2)\n",
    "        ok = True\n",
    "        break\n",
    "    except Exception:\n",
    "        pass\n",
    "print(\"ComfyUI READY\" if ok else \"belum siap — cek log:\")\n",
    "if not ok:\n",
    "    print(open('/content/comfy.log').read()[-2000:])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 7. Buka tunnel Pinggy — URL HTTPS muncul di sini\n",
    "import pinggy, time\n",
    "t = pinggy.start_tunnel(forwardto=\"localhost:8188\")\n",
    "print(\"\\n=== BUKA URL INI DI BROWSER ===\\n\")\n",
    "for u in t.urls:\n",
    "    print(u)\n",
    "print(\"\\nTunnel aktif selama Colab nyala. Kalau UI nggak kebuka langsung, tunggu 1-2 menit.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 8. (Optional) Cek log ComfyUI kalau ada error\n",
    "!tail -30 /content/comfy.log"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
