File size: 32,796 Bytes
d99a751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d335a9c
 
d99a751
 
 
 
 
 
d335a9c
d99a751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
938adde
e35929b
938adde
e35929b
 
 
 
 
 
 
d99a751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e35929b
 
 
938adde
e35929b
14c3887
e35929b
938adde
 
d99a751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d335a9c
d99a751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14c3887
 
a714fc0
 
 
 
14c3887
 
d99a751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14c3887
 
 
 
d99a751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccb5633
 
d99a751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccb5633
d99a751
ccb5633
 
 
 
 
 
 
 
d99a751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83e7fa0
 
d99a751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d335a9c
 
ccb5633
 
 
 
 
 
 
d335a9c
 
 
 
 
 
 
 
 
 
ccb5633
d335a9c
 
ccb5633
 
d335a9c
 
ccb5633
 
d335a9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d99a751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14c3887
 
 
d335a9c
 
 
ccb5633
 
d335a9c
 
 
 
 
 
 
 
 
14c3887
 
 
 
 
 
 
 
 
d99a751
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "##~   DOWNLOADING CODE | BY: ANXETY   ~##\n",
        "\n",
        "import os\n",
        "import re\n",
        "import sys\n",
        "import time\n",
        "import json\n",
        "import shutil\n",
        "import requests\n",
        "import subprocess\n",
        "from datetime import timedelta\n",
        "from subprocess import getoutput\n",
        "from urllib.parse import unquote\n",
        "from IPython.utils import capture\n",
        "from IPython.display import clear_output\n",
        "\n",
        "\n",
        "#  ================= DETECT ENV =================\n",
        "def detect_environment():\n",
        "    environments = {\n",
        "        'COLAB_GPU': ('Google Colab', \"/content\"),\n",
        "        'KAGGLE_URL_BASE': ('Kaggle', \"/kaggle/working/content\"),\n",
        "        'SAGEMAKER_INTERNAL_IMAGE_URI': ('SageMaker Studio Lab', \"/home/studio-lab-user/content\")\n",
        "    }\n",
        "\n",
        "    for env_var, (environment, path) in environments.items():\n",
        "        if env_var in os.environ:\n",
        "            return environment, path\n",
        "\n",
        "    sys.exit(\"\\033[31mError: an unsupported runtime environment was detected.\\n\\033[34mSupported environments:\\033[0m Google Colab, Kaggle, Sagemaker Studio Lab\")\n",
        "\n",
        "env, root_path = detect_environment()\n",
        "webui_path = f\"{root_path}/sdw\"\n",
        "#  ----------------------------------------------\n",
        "\n",
        "\n",
        "# === ONLY SAGEMAKER ===\n",
        "if env == \"SageMaker Studio Lab\":\n",
        "    print(\"Updating dependencies, may take some time...\")\n",
        "    !pip install -q --upgrade torchsde\n",
        "    !pip install -q --upgrade pip\n",
        "    !pip install -q --upgrade psutil\n",
        "\n",
        "    clear_output()\n",
        "\n",
        "\n",
        "# ================ LIBRARIES ================\n",
        "flag_file = f\"{root_path}/libraries_installed.txt\"\n",
        "\n",
        "if not os.path.exists(flag_file):\n",
        "    xformers = \"xformers==0.0.20 triton==2.0.0\"\n",
        "    torch = \"torch==2.0.1+cu118 torchvision==0.15.2+cu118 torchaudio==2.0.2+cu118 torchtext==0.15.2 torchdata==0.6.1 --extra-index-url https://download.pytorch.org/whl/cu118\"\n",
        "\n",
        "    print(\"Installing the libraries, it's going to take a while....\", end='')\n",
        "    with capture.capture_output() as cap:\n",
        "        !apt -y install -qq aria2 &> /dev/null\n",
        "        !npm install -g localtunnel &> /dev/null\n",
        "        !curl -s -OL https://github.com/DEX-1101/sd-webui-notebook/raw/main/res/new_tunnel --output-dir {root_path}\n",
        "        !curl -s -Lo /usr/bin/cl https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 && chmod +x /usr/bin/cl\n",
        "        !pip install insightface\n",
        "\n",
        "        if env == \"SageMaker Studio Lab\":\n",
        "            %pip install -q opencv-python-headless huggingface-hub\n",
        "            %conda update -q -n base conda\n",
        "            %conda install -q -y aria2\n",
        "            %conda install -q -y glib\n",
        "            !pip install tensorflow\n",
        "\n",
        "            !wget -P /home/studio-lab-user https://huggingface.co/NagisaNao/fast_repo/resolve/main/sagemaker/FULL_DELETED_NOTEBOOK.ipynb\n",
        "\n",
        "        if env == \"Google Colab\":\n",
        "            !pip install -q xformers==0.0.22.post7\n",
        "        else:\n",
        "            !pip install -q {torch} -U\n",
        "            !pip install -q {xformers} -U\n",
        "\n",
        "        with open(flag_file, \"w\") as f:\n",
        "            f.write(\"hey ;3\")\n",
        "    del cap\n",
        "    print(\"\\rLibraries are installed!\" + \" \"*35)\n",
        "    time.sleep(2)\n",
        "    clear_output()\n",
        "\n",
        "\n",
        "# ================= loading settings V4 =================\n",
        "def load_settings(path):\n",
        "    if os.path.exists(path):\n",
        "        with open(path, 'r') as file:\n",
        "            return json.load(file)\n",
        "    return {}\n",
        "\n",
        "settings = load_settings(f'{root_path}/settings.json')\n",
        "\n",
        "variables = [\n",
        "    'Model', 'Model_Num', 'Inpainting_Model',\n",
        "    'Vae', 'Vae_Num',\n",
        "    'latest_webui', 'latest_exstensions', 'detailed_download',\n",
        "    'controlnet', 'controlnet_Num', 'commit_hash', 'optional_huggingface_token',\n",
        "    'ngrok_token' 'commandline_arguments',\n",
        "    'Model_url', 'Vae_url', 'LoRA_url', 'Embedding_url', 'Extensions_url', 'custom_file_urls'\n",
        "]\n",
        "\n",
        "locals().update({key: settings.get(key) for key in variables})\n",
        "\n",
        "\n",
        "# ================= OTHER =================\n",
        "try:\n",
        "    start_colab\n",
        "except:\n",
        "    start_colab = int(time.time())-5\n",
        "\n",
        "# CONFIG DIR\n",
        "models_dir = f\"{webui_path}/models/Stable-diffusion\"\n",
        "vaes_dir = f\"{webui_path}/models/VAE\"\n",
        "embeddings_dir = f\"{webui_path}/embeddings\"\n",
        "loras_dir = f\"{webui_path}/models/Lora\"\n",
        "extensions_dir = f\"{webui_path}/extensions\"\n",
        "control_dir = f\"{webui_path}/models/ControlNet\"\n",
        "\n",
        "\n",
        "# ================= MAIN CODE =================\n",
        "if not os.path.exists(webui_path):\n",
        "    start_install = int(time.time())\n",
        "    print(\"⌚ Unpacking Stable Diffusion...\", end='')\n",
        "    with capture.capture_output() as cap:\n",
        "        !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/NagisaNao/fast_repo/resolve/main/FULL_REPO.zip -o repo.zip\n",
        "        !unzip -q -o repo.zip -d {webui_path}\n",
        "        !rm -rf repo.zip\n",
        "\n",
        "        %cd {root_path}\n",
        "        os.environ[\"SAFETENSORS_FAST_GPU\"]='1'\n",
        "        os.environ[\"CUDA_MODULE_LOADING\"]=\"LAZY\"\n",
        "        os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\n",
        "        os.environ[\"PYTHONWARNINGS\"] = \"ignore\"\n",
        "\n",
        "        !echo -n {start_colab} > {webui_path}/static/colabTimer.txt\n",
        "    del cap\n",
        "    install_time = timedelta(seconds=time.time()-start_install)\n",
        "    print(\"\\r🚀 Unpacking is complete! For\",\"%02d:%02d:%02d ⚡\\n\" % (install_time.seconds / 3600, (install_time.seconds / 60) % 60, install_time.seconds % 60), end='', flush=True)\n",
        "else:\n",
        "    !echo -n {start_colab} > {webui_path}/static/colabTimer.txt\n",
        "    print(\"🚀 All unpacked... Skip. ⚡\")\n",
        "    start_colab = float(open(f'{webui_path}/static/colabTimer.txt', 'r').read())\n",
        "    time_since_start = str(timedelta(seconds=time.time()-start_colab)).split('.')[0]\n",
        "    print(f\"⌚️ You have been conducting this session for - \\033[33m{time_since_start}\\033[0m\")\n",
        "\n",
        "\n",
        "# === ONLY SAGEMAKER FIXIN EXTENSIONS ===\n",
        "if env == \"SageMaker Studio Lab\":\n",
        "    with capture.capture_output() as cap:\n",
        "        # --- SuperMerger ---\n",
        "        !wget -O {webui_path}/extensions/supermerger/scripts/mergers/mergers.py https://huggingface.co/NagisaNao/fast_repo/resolve/main/sagemaker/fixing/extensions/supermerger/scripts/mergers/mergers.py\n",
        "    del cap\n",
        "\n",
        "\n",
        "## Changes extensions and WebUi\n",
        "if latest_webui or latest_exstensions:\n",
        "    action = \"Updating WebUI and Extensions\" if latest_webui and latest_exstensions else (\"WebUI Update\" if latest_webui else \"Update Extensions\")\n",
        "    print(f\"⌚️ {action}...\", end='', flush=True)\n",
        "    with capture.capture_output() as cap:\n",
        "        !git config --global user.email \"[email protected]\"\n",
        "        !git config --global user.name \"Your Name\"\n",
        "\n",
        "        ## Update Webui\n",
        "        if latest_webui:\n",
        "            %cd {webui_path}\n",
        "            !git restore .\n",
        "            !git pull -X theirs --rebase --autostash\n",
        "\n",
        "        ## Update extensions\n",
        "        if latest_exstensions:\n",
        "            if env != \"SageMaker Studio Lab\":\n",
        "                !{'for dir in ' + webui_path + '/extensions/*/; do cd \\\"$dir\\\" && git reset --hard && git pull; done'}\n",
        "            else:\n",
        "                !{'for dir in /home/studio-lab-user/content/sdw/extensions/*/; do cd \\\"$dir\\\" && git fetch origin && git pull; done'}\n",
        "\n",
        "        !cd {webui_path}/repositories/stable-diffusion-stability-ai && git restore .\n",
        "    del cap\n",
        "    print(f\"\\r✨ {action} Completed!\")\n",
        "\n",
        "\n",
        "## Version switching\n",
        "if commit_hash:\n",
        "    print('⏳ Time machine activation...', end=\"\", flush=True)\n",
        "    with capture.capture_output() as cap:\n",
        "        %cd {webui_path}\n",
        "        !git config --global user.email \"[email protected]\"\n",
        "        !git config --global user.name \"Your Name\"\n",
        "        !git reset --hard {commit_hash}\n",
        "    del cap\n",
        "    print(f\"\\r⌛️ The time machine has been activated! Current commit: \\033[34m{commit_hash}\\033[0m\")\n",
        "\n",
        "\n",
        "## Downloading model and stuff | oh yeah~ I'm starting to misunderstand my own code ( almost my own ;3 )\n",
        "print(\"📦 Downloading models and stuff...\", end='')\n",
        "model_list = {\n",
        "    \"1.Anime (by Xpuct) + INP\": [\n",
        "        {\"url\": \"https://huggingface.co/XpucT/Anime/resolve/main/Anime_v2.safetensors\", \"name\": \"Anime_v2.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/XpucT/Anime/resolve/main/Anime_v2-inpainting.safetensors\", \"name\": \"Anime_v2-inpainting.safetensors\"}\n",
        "    ],\n",
        "    \"2.Cetus-Mix [Anime] [V4] + INP\": [\n",
        "        {\"url\": \"https://civitai.com/api/download/models/130298\", \"name\": \"CetusMix_V4.safetensors\"},\n",
        "        {\"url\": \"https://civitai.com/api/download/models/139882\", \"name\": \"CetusMix_V4-inpainting.safetensors\"}\n",
        "    ],\n",
        "    \"3.Counterfeit [Anime] [V3] + INP\": [\n",
        "        {\"url\": \"https://civitai.com/api/download/models/125050\", \"name\": \"Counterfeit_V3.safetensors\"},\n",
        "        {\"url\": \"https://civitai.com/api/download/models/137911\", \"name\": \"Counterfeit_V3-inpainting.safetensors\"}\n",
        "    ],\n",
        "    \"4.CuteColor [Anime] [V3]\": [\n",
        "        {\"url\": \"https://civitai.com/api/download/models/138754\", \"name\": \"CuteColor_V3.safetensors\"}\n",
        "    ],\n",
        "    \"5.Dark-Sushi-Mix [Anime]\": [\n",
        "        {\"url\": \"https://civitai.com/api/download/models/101640\", \"name\": \"DarkSushiMix_2_5D.safetensors\"},\n",
        "        {\"url\": \"https://civitai.com/api/download/models/56071\", \"name\": \"DarkSushiMix_colorful.safetensors\"}\n",
        "    ],\n",
        "    \"6.Meina-Mix [Anime] [V11] + INP\": [\n",
        "        {\"url\": \"https://civitai.com/api/download/models/119057\", \"name\": \"MeinaMix_V11.safetensors\"},\n",
        "        {\"url\": \"https://civitai.com/api/download/models/120702\", \"name\": \"MeinaMix_V11-inpainting.safetensors\"}\n",
        "    ],\n",
        "    \"7.Mix-Pro [Anime] [V4] + INP\": [\n",
        "        {\"url\": \"https://civitai.com/api/download/models/125668\", \"name\": \"MixPro_V4.safetensors\"},\n",
        "        {\"url\": \"https://civitai.com/api/download/models/139878\", \"name\": \"MixPro_V4-inpainting.safetensors\"}\n",
        "    ],\n",
        "    \"8.Vela-Mix [Anime] [V2] [6GB]\": [ # 6GB - why so much...?\n",
        "        {\"url\": \"https://civitai.com/api/download/models/83548\", \"name\": \"VelaMix_2.safetensors\"}\n",
        "    ]\n",
        "}\n",
        "\n",
        "# 1-4 (fp16/cleaned)\n",
        "vae_list = {\n",
        "    \"1.Anime.vae\": [\n",
        "        {\"url\": \"https://civitai.com/api/download/models/131654\", \"name\": \"Anime.vae.safetensors\"},\n",
        "        {\"url\": \"https://civitai.com/api/download/models/131658\", \"name\": \"vae-ft-mse.vae.safetensors\"}\n",
        "    ],\n",
        "    \"2.Anything.vae\": [{\"url\": \"https://civitai.com/api/download/models/131656\", \"name\": \"Anything.vae.safetensors\"}],\n",
        "    \"3.Blessed2.vae\": [{\"url\": \"https://civitai.com/api/download/models/142467\", \"name\": \"Blessed2.vae.safetensors\"}],\n",
        "    \"4.ClearVae.vae\": [{\"url\": \"https://civitai.com/api/download/models/133362\", \"name\": \"ClearVae_23.vae.safetensors\"}],\n",
        "    \"5.WD.vae\": [{\"url\": \"https://huggingface.co/NoCrypt/resources/resolve/main/VAE/wd.vae.safetensors\", \"name\": \"WD.vae.safetensors\"}]\n",
        "}\n",
        "\n",
        "controlnet_list = {\n",
        "    \"1.canny\": [\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/resolve/main/control_v11p_sd15_canny_fp16.safetensors\", \"name\": \"control_v11p_sd15_canny_fp16.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/raw/main/control_v11p_sd15_canny_fp16.yaml\", \"name\": \"control_v11p_sd15_canny_fp16.yaml\"}\n",
        "    ],\n",
        "    \"2.openpose\": [\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/resolve/main/control_v11p_sd15_openpose_fp16.safetensors\", \"name\": \"control_v11p_sd15_openpose_fp16.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/raw/main/control_v11p_sd15_openpose_fp16.yaml\", \"name\": \"control_v11p_sd15_openpose_fp16.yaml\"}\n",
        "    ],\n",
        "    \"3.depth\": [\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/resolve/main/control_v11f1p_sd15_depth_fp16.safetensors\", \"name\": \"control_v11f1p_sd15_depth_fp16.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/raw/main/control_v11f1p_sd15_depth_fp16.yaml\", \"name\": \"control_v11f1p_sd15_depth_fp16.yaml\"},\n",
        "        {\"url\": \"https://huggingface.co/NagisaNao/models/resolve/main/ControlNet_v11/control_v11p_sd15_depth_anything_fp16.safetensors\", \"name\": \"control_v11p_sd15_depth_anything_fp16.safetensors\"}\n",
        "    ],\n",
        "    \"4.normal_map\": [\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/resolve/main/control_v11p_sd15_normalbae_fp16.safetensors\", \"name\": \"control_v11p_sd15_normalbae_fp16.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/raw/main/control_v11p_sd15_normalbae_fp16.yaml\", \"name\": \"control_v11p_sd15_normalbae_fp16.yaml\"}\n",
        "    ],\n",
        "    \"5.mlsd\": [\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/resolve/main/control_v11p_sd15_mlsd_fp16.safetensors\", \"name\": \"control_v11p_sd15_mlsd_fp16.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/raw/main/control_v11p_sd15_mlsd_fp16.yaml\", \"name\": \"control_v11p_sd15_mlsd_fp16.yaml\"}\n",
        "    ],\n",
        "    \"6.lineart\": [\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/resolve/main/control_v11p_sd15_lineart_fp16.safetensors\", \"name\": \"control_v11p_sd15_lineart_fp16.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/resolve/main/control_v11p_sd15s2_lineart_anime_fp16.safetensors\", \"name\": \"control_v11p_sd15s2_lineart_anime_fp16.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/raw/main/control_v11p_sd15_lineart_fp16.yaml\", \"name\": \"control_v11p_sd15_lineart_fp16.yaml\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/raw/main/control_v11p_sd15s2_lineart_anime_fp16.yaml\", \"name\": \"control_v11p_sd15s2_lineart_anime_fp16.yaml\"}\n",
        "    ],\n",
        "    \"7.soft_edge\": [\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/resolve/main/control_v11p_sd15_softedge_fp16.safetensors\", \"name\": \"control_v11p_sd15_softedge_fp16.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/raw/main/control_v11p_sd15_softedge_fp16.yaml\", \"name\": \"control_v11p_sd15_softedge_fp16.yaml\"}\n",
        "    ],\n",
        "    \"8.scribble\": [\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/resolve/main/control_v11p_sd15_scribble_fp16.safetensors\", \"name\": \"control_v11p_sd15_scribble_fp16.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/raw/main/control_v11p_sd15_scribble_fp16.yaml\", \"name\": \"control_v11p_sd15_scribble_fp16.yaml\"}\n",
        "    ],\n",
        "    \"9.segmentation\": [\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/resolve/main/control_v11p_sd15_seg_fp16.safetensors\", \"name\": \"control_v11p_sd15_seg_fp16.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/raw/main/control_v11p_sd15_seg_fp16.yaml\", \"name\": \"control_v11p_sd15_seg_fp16.yaml\"}\n",
        "    ],\n",
        "    \"10.shuffle\": [\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/resolve/main/control_v11e_sd15_shuffle_fp16.safetensors\", \"name\": \"control_v11e_sd15_shuffle_fp16.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/raw/main/control_v11e_sd15_shuffle_fp16.yaml\", \"name\": \"control_v11e_sd15_shuffle_fp16.yaml\"}\n",
        "    ],\n",
        "    \"11.tile\": [\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/resolve/main/control_v11f1e_sd15_tile_fp16.safetensors\", \"name\": \"control_v11f1e_sd15_tile_fp16.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/raw/main/control_v11f1e_sd15_tile_fp16.yaml\", \"name\": \"control_v11f1e_sd15_tile_fp16.yaml\"}\n",
        "    ],\n",
        "    \"12.inpaint\": [\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/resolve/main/control_v11p_sd15_inpaint_fp16.safetensors\", \"name\": \"control_v11p_sd15_inpaint_fp16.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/raw/main/control_v11p_sd15_inpaint_fp16.yaml\", \"name\": \"control_v11p_sd15_inpaint_fp16.yaml\"}\n",
        "    ],\n",
        "    \"13.instruct_p2p\": [\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/resolve/main/control_v11e_sd15_ip2p_fp16.safetensors\", \"name\": \"control_v11e_sd15_ip2p_fp16.safetensors\"},\n",
        "        {\"url\": \"https://huggingface.co/ckpt/ControlNet-v1-1/raw/main/control_v11e_sd15_ip2p_fp16.yaml\", \"name\": \"control_v11e_sd15_ip2p_fp16.yaml\"}\n",
        "    ]\n",
        "}\n",
        "\n",
        "extension_repo = []\n",
        "prefixes = [\n",
        "    \"model:\",\n",
        "    \"vae:\",\n",
        "    \"lora:\",\n",
        "    \"embeddings:\",\n",
        "    \"extensions:\"\n",
        "]\n",
        "\n",
        "!mkdir -p {models_dir} {vaes_dir} {embeddings_dir} {loras_dir} {control_dir}\n",
        "\n",
        "url = \"\"\n",
        "hf_token = optional_huggingface_token if optional_huggingface_token else \"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\"\n",
        "user_header = f\"\\\"Authorization: Bearer {hf_token}\\\"\"\n",
        "\n",
        "def handle_manual(url):\n",
        "    original_url = url\n",
        "    url = url.split(':', 1)[1]\n",
        "    file_name = re.search(r'\\[(.*?)\\]', url)\n",
        "    file_name = file_name.group(1) if file_name else None\n",
        "    if file_name:\n",
        "        url = re.sub(r'\\[.*?\\]', '', url)\n",
        "\n",
        "    dir_mapping = {\"model\": models_dir, \"vae\": vaes_dir, \"lora\": loras_dir, \"embeddings\": embeddings_dir, \"extensions\": None}\n",
        "\n",
        "    for prefix, dir in dir_mapping.items():\n",
        "        if original_url.startswith(f\"{prefix}:\"):\n",
        "            if prefix != \"extensions\":\n",
        "                manual_download(url, dir, file_name=file_name)\n",
        "            else:\n",
        "                extension_repo.append((url, file_name))\n",
        "\n",
        "def manual_download(url, dst_dir, file_name):\n",
        "    basename = url.split(\"/\")[-1] if file_name is None else file_name\n",
        "\n",
        "    # -- GDrive --\n",
        "    if 'drive.google' in url:\n",
        "        if 'folders' in url:\n",
        "            !gdown --folder \"{url}\" -O {dst_dir} --fuzzy -c\n",
        "        else:\n",
        "            !gdown \"{url}\" -O {dst_dir} --fuzzy -c\n",
        "    # -- Huggin Face --\n",
        "    elif 'huggingface' in url:\n",
        "        if '/blob/' in url:\n",
        "            url = url.replace('/blob/', '/resolve/')\n",
        "        if file_name:\n",
        "            !aria2c --optimize-concurrent-downloads --console-log-level=error --summary-interval=10 --header={user_header} -c -j5 -x16 -s16 -k1M  -d {dst_dir} -o {basename} {url}\n",
        "        else:\n",
        "            parsed_link = '\\n{}\\n\\tout={}'.format(url, unquote(url.split('/')[-1]))\n",
        "            !echo -e \"{parsed_link}\" | aria2c --header={user_header} --console-log-level=error --summary-interval=10 -i- -j5 -x16 -s16 -k1M -c -d \"{dst_dir}\" -o  {basename}\n",
        "    # -- Other --\n",
        "    elif 'http' in url or 'magnet' in url:\n",
        "        if file_name:\n",
        "            !aria2c --optimize-concurrent-downloads --console-log-level=error --summary-interval=10 -j5 -x16 -s16 -k1M -c -d {dst_dir} -o {file_name} {url}\n",
        "        else:\n",
        "            parsed_link = '\"{}\"'.format(url)\n",
        "            !aria2c --optimize-concurrent-downloads --console-log-level=error --summary-interval=10 -j5 -x16 -s16 -k1M -c -d {dst_dir} -Z {parsed_link}\n",
        "\n",
        "def download(url):\n",
        "    links_and_paths = url.split(',')\n",
        "\n",
        "    for link_or_path in links_and_paths:\n",
        "        link_or_path = link_or_path.strip()\n",
        "        if not link_or_path:\n",
        "            continue\n",
        "\n",
        "        if any(link_or_path.startswith(prefix.lower()) for prefix in prefixes):\n",
        "            handle_manual(link_or_path)\n",
        "            continue\n",
        "\n",
        "        url, dst_dir, file_name = link_or_path.split()\n",
        "        manual_download(url, dst_dir, file_name)\n",
        "\n",
        "submodels = []\n",
        "\n",
        "def add_submodels(selection, num_selection, model_dict, dst_dir):\n",
        "    if selection == \"none\":\n",
        "        return []\n",
        "    if selection == \"ALL\":\n",
        "        all_models = []\n",
        "        for models in model_dict.values():\n",
        "            all_models.extend(models)\n",
        "        selected_models = all_models\n",
        "    else:\n",
        "        selected_models = model_dict[selection]\n",
        "        selected_nums = map(int, num_selection.replace(',', '').split())\n",
        "\n",
        "        for num in selected_nums:\n",
        "            if 1 <= num <= len(model_dict):\n",
        "                name = list(model_dict)[num - 1]\n",
        "                selected_models.extend(model_dict[name])\n",
        "\n",
        "    unique_models = list({model['name']: model for model in selected_models}.values())\n",
        "\n",
        "    for model in unique_models:\n",
        "        model['dst_dir'] = dst_dir\n",
        "\n",
        "    return unique_models\n",
        "\n",
        "submodels += add_submodels(Model, Model_Num, model_list, models_dir)                                                   # model\n",
        "submodels += add_submodels(Vae, Vae_Num, vae_list, vaes_dir)                                                           # vae\n",
        "submodels += add_submodels(controlnet, \"\" if controlnet == \"ALL\" else controlnet_Num, controlnet_list, control_dir)    # controlnet\n",
        "\n",
        "for submodel in submodels:\n",
        "    if not Inpainting_Model and \"inpainting\" in submodel['name']:\n",
        "        continue\n",
        "\n",
        "    url += f\"{submodel['url']} {submodel['dst_dir']} {submodel['name']}, \"\n",
        "\n",
        "def process_file_download(file_url):\n",
        "    global Model_url, Vae_url, LoRA_url, Embedding_url, Extensions_url\n",
        "    urls_dict = {\n",
        "        'model': 'Model_url',\n",
        "        'vae': 'Vae_url',\n",
        "        'embed': 'Embedding_url',\n",
        "        'lora': 'LoRA_url',\n",
        "        'extension': 'Extensions_url'\n",
        "    }\n",
        "\n",
        "    if file_url.startswith(\"http\"):\n",
        "        if \"blob\" in file_url:\n",
        "            file_url = file_url.replace(\"blob\", \"raw\")\n",
        "        response = requests.get(file_url)\n",
        "        lines = response.text.split('\\n')\n",
        "    else:\n",
        "        with open(file_url, 'r') as file:\n",
        "            lines = file.readlines()\n",
        "\n",
        "    current_tag = None\n",
        "    for line in lines:\n",
        "        if line.strip().startswith('#'):\n",
        "            current_tag = next((tag for tag in urls_dict if tag in line.lower()), None)\n",
        "        elif current_tag and line.strip():\n",
        "            urls = [url.strip() for url in line.split()]\n",
        "            for url in urls:\n",
        "                if url.startswith(\"http\"):\n",
        "                    globals()[urls_dict[current_tag]] += \", \" + url\n",
        "\n",
        "# fix all possible errors/options and function call\n",
        "if custom_file_urls:\n",
        "    if not custom_file_urls.endswith('.txt'):\n",
        "        custom_file_urls += '.txt'\n",
        "    if not custom_file_urls.startswith('http'):\n",
        "        if not custom_file_urls.startswith(root_path):\n",
        "            custom_file_urls = f'{root_path}/{custom_file_urls}'\n",
        "    if custom_file_urls.count('/content') >= 2:\n",
        "        custom_file_urls = re.sub(r'(/content){2,}', '/content', custom_file_urls)\n",
        "\n",
        "    try:\n",
        "        process_file_download(custom_file_urls)\n",
        "    except FileNotFoundError:\n",
        "        pass\n",
        "\n",
        "urls = [Model_url, Vae_url, LoRA_url, Embedding_url, Extensions_url]\n",
        "\n",
        "for i, prefix in enumerate(prefixes):\n",
        "    if urls[i]:\n",
        "        prefixed_urls = [f\"{prefix}{u}\" for u in urls[i].replace(',', '').split()]\n",
        "        if prefixed_urls:\n",
        "            url += \", \".join(prefixed_urls) + \", \"\n",
        "\n",
        "if detailed_download == \"on\":\n",
        "    print(\"\\n\\n\\033[33m# ====== Detailed Download ====== #\\n\\033[0m\")\n",
        "    download(url)\n",
        "    print(\"\\n\\033[33m# =============================== #\\n\\033[0m\")\n",
        "else:\n",
        "    with capture.capture_output() as cap:\n",
        "        download(url)\n",
        "    del cap\n",
        "\n",
        "print(\"\\r🏁 Download Complete!\" + \" \"*15)\n",
        "\n",
        "\n",
        "# Cleaning shit after downloading...\n",
        "!find  \\( -name \".ipynb_checkpoints\" -o -name \".aria2\" \\) -type d -exec rm -r {} \\; >/dev/null 2>&1\n",
        "\n",
        "\n",
        "## Install of Custom extensions\n",
        "if len(extension_repo) > 0:\n",
        "    print(\"✨ Installing custom extensions...\", end='', flush=True)\n",
        "    with capture.capture_output() as cap:\n",
        "        for repo, repo_name in extension_repo:\n",
        "            if not repo_name:\n",
        "                repo_name = repo.split('/')[-1]\n",
        "            !cd {extensions_dir} \\\n",
        "                && git clone {repo} {repo_name} \\\n",
        "                && cd {repo_name} \\\n",
        "                && git fetch\n",
        "    del cap\n",
        "    print(f\"\\r📦 Installed '{len(extension_repo)}', Custom extensions!\")\n",
        "\n",
        "\n",
        "## List Models and stuff\n",
        "if detailed_download == \"off\":\n",
        "    print(\"\\n\\n\\033[33mIf you don't see any downloaded files, enable the 'Detailed Downloads' feature in the widget.\")\n",
        "\n",
        "if any(not file.endswith('.txt') for file in os.listdir(models_dir)):\n",
        "    print(\"\\n\\033[33m➤ Models\\033[0m\")\n",
        "    !find {models_dir}/ -mindepth 1 ! -name '*.txt' -printf '%f\\n'\n",
        "if any(not file.endswith('.txt') for file in os.listdir(vaes_dir)):\n",
        "    print(\"\\n\\033[33m➤ VAEs\\033[0m\")\n",
        "    !find {vaes_dir}/ -mindepth 1 ! -name '*.txt' -printf '%f\\n'\n",
        "if any(not file.endswith('.txt') and not os.path.isdir(os.path.join(embeddings_dir, file)) for file in os.listdir(embeddings_dir)):\n",
        "    print(\"\\n\\033[33m➤ Embeddings\\033[0m\")\n",
        "    !find {embeddings_dir}/ -mindepth 1 -maxdepth 1 \\( -name '*.pt' -or -name '*.safetensors' \\) -printf '%f\\n'\n",
        "if any(not file.endswith('.txt') for file in os.listdir(loras_dir)):\n",
        "    print(\"\\n\\033[33m➤ LoRAs\\033[0m\")\n",
        "    !find {loras_dir}/ -mindepth 1 ! -name '*.keep' -printf '%f\\n'\n",
        "print(f\"\\n\\033[33m➤ Extensions\\033[0m\")\n",
        "!find {extensions_dir}/ -mindepth 1 -maxdepth 1 ! -name '*.txt' -printf '%f\\n'\n",
        "if any(not file.endswith(('.txt', '.yaml')) for file in os.listdir(control_dir)):\n",
        "    print(\"\\n\\033[33m➤ ControlNet\\033[0m\")\n",
        "    !find {control_dir}/ -mindepth 1 ! -name '*.yaml' -printf '%f\\n' | sed 's/^[^_]*_[^_]*_[^_]*_\\(.*\\)_fp16\\.safetensors$/\\1/'\n",
        "\n",
        "\n",
        "# === OTHER ===\n",
        "# Downlaod discord tags UmiWildcards\n",
        "files_umi = [\n",
        "    \"https://huggingface.co/NagisaNao/fast_repo/resolve/main/extensions/UmiWildacrd/discord/200_pan_gen.txt\",\n",
        "    \"https://huggingface.co/NagisaNao/fast_repo/resolve/main/extensions/UmiWildacrd/discord/150_bra_gen.txt\"\n",
        "]\n",
        "save_dir_path = f\"{webui_path}/extensions/Umi-AI-Wildcards/wildcards/discord\"\n",
        "\n",
        "with capture.capture_output() as cap:\n",
        "    for file in files_umi:\n",
        "        !aria2c --optimize-concurrent-downloads --console-log-level=error --summary-interval=10 -j5 -x16 -s16 -k1M -c -d {save_dir_path} {file}\n",
        "del cap\n",
        "\n",
        "\n",
        "# === ONLY SAGEMAKER ===\n",
        "if env == \"SageMaker Studio Lab\":\n",
        "    with capture.capture_output() as cap:\n",
        "        !rm -rf /home/studio-lab-user/.conda/envs/studiolab-safemode\n",
        "        !rm -rf /home/studio-lab-user/.conda/envs/sagemaker-distribution\n",
        "        !rm -rf /home/studio-lab-user/.conda/pkgs/cache\n",
        "        !pip cache purge\n",
        "        !rm -rf ~/.cache\n",
        "    del cap"
      ],
      "metadata": {
        "id": "2lJmbqrs3Mu8"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}