{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Forge 3D — Python worker\n",
    "Runs in **Google Colab** or **Kaggle** and builds 3D models for your Forge 3D scenes (https://forge3d-xcam.onrender.com).\n",
    "\n",
    "1. Paste your access key below (the `mk_…` key from the app).\n",
    "2. **No GPU needed.** A plain CPU runtime runs everything: Cycles path-traced renders up to 8K (denoised), seamless PBR textures, text → 3D (procedural), image → 3D (relief), game assets, erosion, voxelize, optimize. A T4 GPU is optional and only speeds up the AI engines (SDXL, TripoSR).\n",
    "3. Run all cells. The worker picks up jobs from the app, agents and the API, and drops finished GLB models into the scene.\n",
    "\n",
    "**Colab:** it keeps running in the background while this runtime is connected.\n",
    "**Kaggle:** turn on *Internet* in Settings, then *Save Version → Save & Run All* so it runs in the background without your browser."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "FORGE3D_KEY = \"\"          # <- paste your mk_... key here\n",
    "SITE = \"https://forge3d-xcam.onrender.com\"\n",
    "ALLOW_PYTHON = False      # True = run custom Python jobs sent from the app (only enable if you trust everyone with the key)\n",
    "MAX_HOURS = 8.5           # Kaggle background runs stop after this\n",
    "GPU_JOBS = True           # install Blender (+ AI models when a GPU is present); first run ~2-5 min\n",
    "AI_ON_CPU = False         # True = also install SDXL/TripoSR on a CPU runtime (slow but works)\n"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import os, subprocess, sys\n",
    "IN_COLAB = \"google.colab\" in sys.modules\n",
    "IN_KAGGLE = bool(os.environ.get(\"KAGGLE_KERNEL_RUN_TYPE\")) or os.path.exists(\"/kaggle\")\n",
    "def sh(c): print(subprocess.run(c, shell=True, capture_output=True, text=True).stdout[-400:])\n",
    "sh(\"pip -q install trimesh numpy requests fast_simplification scipy pillow\")\n",
    "try:\n",
    "    import torch; GPU = torch.cuda.is_available()\n",
    "except Exception:\n",
    "    GPU = False\n",
    "if GPU:\n",
    "    sh(\"pip -q install 'diffusers>=0.27' transformers accelerate rembg\")\n",
    "sh(f\"wget -q -O modeler_worker.py {SITE}/py/modeler_worker.py\")\n",
    "print(\"GPU:\", GPU, \"| Colab:\", IN_COLAB, \"| Kaggle:\", IN_KAGGLE)\n",
    "import modeler_worker\n",
    "if GPU_JOBS:\n",
    "    modeler_worker.setup(gpu_jobs=GPU, blender=True, ai=True if AI_ON_CPU else None)\n"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import importlib, modeler_worker\n",
    "importlib.reload(modeler_worker)\n",
    "key = FORGE3D_KEY or os.environ.get(\"FORGE3D_KEY\")\n",
    "if not key and IN_KAGGLE:\n",
    "    try:\n",
    "        from kaggle_secrets import UserSecretsClient\n",
    "        key = UserSecretsClient().get_secret(\"FORGE3D_KEY\")\n",
    "    except Exception:\n",
    "        pass\n",
    "assert key, \"Paste your key into FORGE3D_KEY (or add a Kaggle secret named FORGE3D_KEY)\"\n",
    "if IN_KAGGLE:\n",
    "    # Kaggle background runs end when the last cell finishes, so block here\n",
    "    worker = modeler_worker.run(key=key, background=False, allow_python=ALLOW_PYTHON, max_hours=MAX_HOURS)\n",
    "else:\n",
    "    worker = modeler_worker.run(key=key, background=True, allow_python=ALLOW_PYTHON)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Optional: preview a generator right here\n",
    "Builds an asset locally without the server (good for tweaking generators). Stop the worker with `worker.stop()`."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "m = modeler_worker.preview(\"pine\", seed=7, size=2)\n",
    "print(len(m.faces), \"triangles\")\n",
    "m.show() if IN_COLAB else None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Optional: plug in your own text→3D model\n",
    "```python\n",
    "def my_engine(params, progress):\n",
    "    progress(\"running my model\")\n",
    "    mesh = ...            # build a trimesh.Trimesh (Y-up) from params[\"prompt\"]\n",
    "    return mesh\n",
    "modeler_worker.register_engine(\"text\", \"my-engine\", my_engine)\n",
    "# then send jobs with params {\"prompt\": \"...\", \"engine\": \"my-engine\"}\n",
    "```"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "provenance": [],
   "gpuType": "T4"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}