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
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
{
  "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
}