{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "D4TNDJdRpPN9" }, "source": [ "#Invoke AI Notebook\n", "\n", "Works on the free tier: Generating images with the SDXL base model and refiner. Adding SDXL models in diffusers format from HuggingFace.\n", "\n", "Works, but only with Colab Pro: Adding custom checkpoints and LoRAs." ] }, { "cell_type": "markdown", "metadata": { "id": "Ow5L4LUnr_Cs" }, "source": [ "Step 1" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "MIhVvU8jkdm6" }, "outputs": [], "source": [ "#@markdown # Installing InvokeAI\n", "\n", "#@markdown Use Google Drive to store models (uses about 7 GB). Uncheck this if you don't have enough space in your Drive.\n", "useGoogleDrive = False #@param {type:\"boolean\"}\n", "\n", "googleDriveModelsFolder = '/stablemodels' #@param {type:\"string\"}\n", "\n", "#@markdown This step usually takes about 5 minutes.\n", "\n", "#@markdown You can ignore the message about restarting the runtime.\n", "import os\n", "import subprocess\n", "from google.colab import drive\n", "if useGoogleDrive:\n", " drive.mount('/content/drive')\n", " if not googleDriveModelsFolder.startswith('/'):\n", " googleDriveModelsFolder = '/' + googleDriveModelsFolder\n", " modelsPath = \"/content/drive/MyDrive\"+googleDriveModelsFolder\n", " if not modelsPath.endswith(\"/\"):\n", " modelsPath = modelsPath + \"/\"\n", "\n", "env = os.environ.copy()\n", "\n", "!pip install 'InvokeAI[xformers]' --use-pep517 --extra-index-url https://download.pytorch.org/whl/cu117\n", "\n", "exit()\n" ] }, { "cell_type": "markdown", "metadata": { "id": "ERca0J67r8Ss" }, "source": [ "Step 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "YTkFxvuH0BsX" }, "outputs": [], "source": [ "#@markdown # Configuration and downloading default models\n", "\n", "!mkdir /content/invokeai\n", "!mkdir /content/invokeai/configs\n", "\n", "#@markdown Download only the default model in initial configuration.\n", "#@markdown Checking this prevents running out of space in Colab.\n", "\n", "defaultOnly = True #@param {type:\"boolean\"}\n", "skipWeights = True #@param {type:\"boolean\"}\n", "noFullPrecision = True #@param {type:\"boolean\"}\n", "#@markdown This step usually takes about 2 minutes with only the default model and no weights.\n", "\n", "#@markdown You can ignore \"File exists\" warnings in the output.\n", "\n", "cmd = 'invokeai-configure --root_dir /content/invokeai --yes'\n", "\n", "if defaultOnly:\n", " cmd += ' --default_only'\n", "\n", "if skipWeights:\n", " cmd += ' --skip-sd-weights'\n", "\n", "if noFullPrecision:\n", " cmd += ' --no-full-precision'\n", "\n", "get_ipython().system(cmd)\n", "\n", "import fileinput\n", "import os\n", "def find(name, path):\n", " for root, dirs, files in os.walk(path):\n", " if name in files:\n", " return os.path.join(root, name)\n", "\n", "if noFullPrecision:\n", " model_install_file = find('model_install_backend.py', '/usr/local/lib')\n", " print('modifying file ' + model_install_file)\n", " for line in fileinput.input(model_install_file, inplace=True):\n", " if ('precision = torch_dtype(choose_torch_device())' in line):\n", " line = line.replace('torch_dtype(choose_torch_device())', 'torch.float16')\n", " print(line, end='')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "colab": { "base_uri": "https://localhost:8080/" }, "id": "3owdtpnWsRoU", "outputId": "a6873dfe-a211-427d-f158-b0865c5bf95e" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Mounted at /content/drive\n" ] } ], "source": [ "# Linking output images to Google Drive\n", "outputDrivePath = '/content/drive/MyDrive/images/invoke-outputs' #@param {type:\"string\"}\n", "# Full path to the output folder on Google Drive\n", "\n", "saveDatabase = True #@param {type:\"boolean\"}\n", "from os import path\n", "\n", "from google.colab import drive\n", "import os\n", "from os import path\n", "drive.mount('/content/drive')\n", "\n", "if not outputDrivePath.endswith('/'):\n", " outputDrivePath = outputDrivePath + '/'\n", "imagesDrivePath = outputDrivePath + 'images'\n", "databaseDrivePath = outputDrivePath + 'databases'\n", "if not path.exists(imagesDrivePath):\n", " os.makedirs(imagesDrivePath, exist_ok=True)\n", "\n", "\n", "outputsLocalPath = '/content/invokeai/outputs'\n", "imagesLocalPath = '/content/invokeai/outputs/images'\n", "\n", "if not path.exists(outputsLocalPath):\n", " os.makedirs(outputsLocalPath, exist_ok=True)\n", "\n", "import datetime\n", "\n", "if path.exists(imagesLocalPath):\n", " cmd = f'mv {imagesLocalPath} {imagesLocalPath}-backup{datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")}'\n", " get_ipython().system(cmd)\n", "\n", "cmd = f'ln -s {imagesDrivePath} {outputsLocalPath}'\n", "get_ipython().system(cmd)\n", "\n", "# Linking the database\n", "if saveDatabase:\n", " if not path.exists(databaseDrivePath):\n", " os.makedirs(databaseDrivePath, exist_ok=True)\n", "\n", " databaseLocalPath = '/content/invokeai/databases'\n", "\n", " cmd = f'mv {databaseLocalPath} {databaseLocalPath}-backup{datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")}'\n", " get_ipython().system(cmd)\n", "\n", " cmd = f'ln -s {databaseDrivePath} /content/invokeai'\n", " get_ipython().system(cmd)\n" ] }, { "cell_type": "markdown", "metadata": { "id": "jS0EJ4LosUFY" }, "source": [ "Step 6: Load any SDXL models in diffusers format from Drive - Optional" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "sdaNxzYPsaXX" }, "outputs": [], "source": [ "# Adding custom SDXL models in diffusers format from Goole Drive\n", "googleDriveModelFolder = '/content/drive/MyDrive/path-to-the-model' #@param {type:\"string\"}\n", "#@markdown - Full path to the model folder on Google Drive\n", "\n", "#@markdown This can also be done from the Model Manager in the Web UI.\n", "\n", "updateModelsYaml = True\n", "with open('/content/invokeai/configs/models.yaml') as f:\n", " if googleDriveModelFolder in f.read():\n", " updateModelsYaml = False\n", "if updateModelsYaml:\n", " with open('/content/invokeai/configs/models.yaml', 'a') as file:\n", " folders = googleDriveModelFolder.split('/');\n", " modelname = folders[len(folders)-1]\n", " print(modelname)\n", " lines = [\n", " 'sdxl/main/' + modelname + ':\\n',\n", " ' path: ' + googleDriveModelFolder + '\\n',\n", " ' description: Stable Diffusion XL base model (12 GB)\\n',\n", " ' variant: normal\\n',\n", " ' format: diffusers\\n'\n", " ]\n", " file.writelines(lines)" ] }, { "cell_type": "markdown", "metadata": { "id": "T4xrUy3Gsomd" }, "source": [ "Step 7: Starting the app" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "nCiDkdSlqZhd" }, "outputs": [], "source": [ "def install_jemalloc():\n", " !apt -y update -qq\n", " !apt -y install libjemalloc-dev\n", "install_jemalloc()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "e-IErS_AaNNz" }, "outputs": [], "source": [ "!apt-get install aria2\n", "civitai_model_urls = \"https://civitai.com/api/download/models/157223?type=Model&format=SafeTensor&size=pruned&fp=fp16, https://civitai.com/api/download/models/138176?type=Model&format=SafeTensor&size=pruned&fp=fp32\" # @param {'type': 'string'}\n", "url_list = civitai_model_urls.split(\", \")\n", "for url in url_list:\n", " !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M --content-disposition -d /content/invokeai/models/sd-1/main {url}" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "QC6jE2afaVHy" }, "outputs": [], "source": [ "# @title Embeddings\n", "import zipfile\n", "embeddings_zip_url = 'https://github.com/Ysb321/supper/releases/download/emm/emm.zip, https://civitai.com/api/download/models/42247?type=Model&format=Other'\n", "url_list = embeddings_zip_url.split(\", \")\n", "for url in url_list:\n", " !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M -d /content/invokeai/models/sd-1/embedding {url}\n", "current_dir = '/content/invokeai/models/sd-1/embedding'\n", "for entry in os.scandir(current_dir):\n", " if entry.is_file() and entry.name.endswith('.zip'):\n", " with zipfile.ZipFile(entry, 'r') as zip_ref:\n", " zip_ref.extractall(current_dir)\n", "!rm /content/invokeai/models/sd-1/embedding/*.zip" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "zPR0gqrAc97R" }, "outputs": [], "source": [ "# @title lorazip\n", "import zipfile\n", "lora_zip_url = 'https://huggingface.co/datasets/ysb123/yy/resolve/main/ppp.zip, https://huggingface.co/datasets/ysb123/yy/resolve/main/ddd.zip, https://huggingface.co/datasets/ysb123/yy/resolve/main/Lora.zip'\n", "url_list = lora_zip_url.split(\", \")\n", "for url in url_list:\n", " !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M --content-disposition -d /content/invokeai/models/sd-1/lora {url}\n", "directory = '/content/invokeai/models/sd-1/lora'\n", "for filename in os.listdir(directory):\n", " if '.' not in filename:\n", " old_filepath = os.path.join(directory, filename)\n", " new_filepath = os.path.join(directory, filename + '.zip')\n", " os.rename(old_filepath, new_filepath)\n", "current_dir = '/content/invokeai/models/sd-1/lora'\n", "for entry in os.scandir(current_dir):\n", " if entry.is_file() and entry.name.endswith('.zip'):\n", " with zipfile.ZipFile(entry, 'r') as zip_ref:\n", " zip_ref.extractall(current_dir)\n", "!rm /content/invokeai/models/sd-1/lora/*.zip" ] }, { "cell_type": "code", "source": [ "lora_url = 'https://civitai.com/api/download/models/139136' # @param {'type': 'string'}\n", "url_list = lora_url.split(\", \")\n", "for url in url_list:\n", " !wget --content-disposition -P /content/invokeai/models/sd-1/lora {url}" ], "metadata": { "cellView": "form", "id": "iOf2elAdGwqc" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "8P-UgO8Ysrlz" }, "outputs": [], "source": [ "#@markdown # Option 2: Starting the Web UI with ngrok\n", "!pip install pyngrok\n", "\n", "from pyngrok import ngrok, conf\n", "import fileinput\n", "import sys\n", "%env LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.2\n", "Ngrok_token = \"\" #@param {type:\"string\"}\n", "#@markdown - Add ngrok token (obtainable from https://ngrok.com)\n", "\n", "#@markdown Only works with InvokeAI 3.0.2 and later\n", "\n", "share=''\n", "if Ngrok_token!=\"\":\n", " ngrok.kill()\n", " srv=ngrok.connect(9090 , pyngrok_config=conf.PyngrokConfig(auth_token=Ngrok_token),\n", " bind_tls=True).public_url\n", " print(srv)\n", " get_ipython().system(\"invokeai-web --root /content/invokeai/\")\n", "else:\n", " print('An ngrok token is required. You can get one on https://ngrok.com and paste it into the ngrok_token field.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "qN-IExD5XwOs" }, "outputs": [], "source": [ "#@markdown # Option 1: Starting the Web UI with Localtunnel\n", "\n", "%cd /content/invokeai/\n", "!npm install -g localtunnel\n", "\n", "#@markdown Copy the IP address shown in the output above the line\n", "#@markdown \"your url is: https://some-random-words.loca.lt\"\n", "!wget -q -O - ipv4.icanhazip.com\n", "\n", "#@markdown Wait for the line that says \"Uvicorn running on http://127.0.0.1:9090 (Press CTRL+C to quit)\"\n", "\n", "#@markdown Click the localtunnel url and paste the IP you copied earlier to the \"Endpoint IP\" text field\n", "!lt --port 9090 --local_https False & invokeai-web --root /content/invokeai/\n", "\n", "#@markdown If the UI shows a red dot that says 'disconnected' when hovered in the upper\n", "#@markdown right corner and the Invoke button is disabled, change 'https' to 'http'\n", "#@markdown in the browser's address bar and press enter.\n", "#@markdown When the page reloads, the UI should work properly.\n" ] } ], "metadata": { "accelerator": "GPU", "colab": { "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 0 }