File size: 15,419 Bytes
d5d73e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mInOtcO66MPD"
      },
      "outputs": [],
      "source": [
        "#1\n",
        "# объявление основных переменных/функций\n",
        "\n",
        "\n",
        "import os\n",
        "import os.path\n",
        "from google.colab import output as cou\n",
        "from google.colab import drive\n",
        "import re\n",
        "from re import search\n",
        "import subprocess\n",
        "from subprocess import getoutput\n",
        "import threading\n",
        "from IPython.display import HTML, Javascript, display, clear_output\n",
        "from ipython_genutils.py3compat import builtin_mod\n",
        "import ipywidgets as widgets\n",
        "import requests\n",
        "import glob\n",
        "import time\n",
        "from datetime import timedelta\n",
        "import distutils.dir_util\n",
        "from IPython.utils import capture\n",
        "import multiprocessing\n",
        "import random\n",
        "import string\n",
        "from tqdm import tqdm\n",
        "import concurrent.futures\n",
        "from concurrent.futures import ThreadPoolExecutor, as_completed\n",
        "import pickle\n",
        "import platform\n",
        "\n",
        "\n",
        "cfg = \"/content/.config/\"\n",
        "#переменная !$dl для сокращения команды загрузки, перед использованием обязательно задать переменную пути $path\n",
        "path = '/content/'\n",
        "wget = \"wget -nv -t 10 --show-progress --progress=bar -q --content-disposition \"\n",
        "dl = f\"{wget} -P {path} \"\n",
        "wq = \"wget -q -nv -t 10 --content-disposition\"\n",
        "lz4 = \"tar -xI lz4 -f\"\n",
        "sf = \"https://huggingface.co/utnah/safetensors/resolve/main/\"\n",
        "pt = \"https://huggingface.co/utnah/ckpt/resolve/main/\"\n",
        "vae = \"https://huggingface.co/utnah/vae/resolve/main/\"\n",
        "esrgan = \"https://huggingface.co/utnah/esrgan/resolve/main/\"\n",
        "lora = \"https://huggingface.co/utnah/lora/resolve/main/\"\n",
        "hyper = \"https://huggingface.co/utnah/hypernetworks/resolve/main/\"\n",
        "dl_deps = \"wget -q -t 10 --content-disposition https://huggingface.co/utnah/deps/resolve/main/\"\n",
        "deps = \"https://huggingface.co/utnah/deps/resolve/main/\"\n",
        "pip = f\"/usr/local/lib/python{'.'.join(platform.python_version().split('.')[:2])}/dist-packages/\"\n",
        "gh = \"https://github.com/PR0LAPSE/StableDiffusionWebUIColab/raw/main/src/\"\n",
        "dl_gh = f\"wget -q -t 10 --content-disposition  {gh}\"\n",
        "end = '/content/.config/end'\n",
        "deps_bar = f\"{gh}depsprogressbar\" # прогрессбар во время распаковки пакетов: loader(deps)\n",
        "inprogress = f\"{gh}loader_anim\" # заглушка на css во время выполнения чего-либо: loader(inprogress)\n",
        "\n",
        "m = HTML(requests.get(gh+'st').text)\n",
        "ok = \"\"\n",
        "with capture.capture_output() as stored_variables:\n",
        "  %store cfg\n",
        "  %store wget\n",
        "  %store sf\n",
        "  %store pt\n",
        "  %store esrgan\n",
        "  %store lora\n",
        "  %store hyper\n",
        "  %store dl_deps\n",
        "  %store deps\n",
        "  %store gh\n",
        "  %store dl_gh\n",
        "  %store end\n",
        "  %store deps_bar\n",
        "  %store inprogress\n",
        "  %store m\n",
        "\n",
        "vars_data = (cfg, wget, dl, wq, lz4, sf, pt, vae, esrgan, hyper, dl_deps, deps, pip, gh, dl_gh, end, deps_bar, inprogress, m)  # все переменные для сохранения в файл\n",
        "with open(f'{cfg}variables', 'wb') as vars:\n",
        "    pickle.dump(vars_data, vars)\n",
        "\n",
        "def loader(html): # для подгрузки html/svg\n",
        "  display(HTML(html, metadata=dict(isolated=True)))  \n",
        "\n",
        "#простая качалка (для загрузки архива с зависимостями)\n",
        "def download(url: str, fname: str, desc: str, chunk_size=1024):\n",
        "  try:\n",
        "    resp = requests.get(url, stream=True)\n",
        "    total = int(resp.headers.get('content-length', 0))\n",
        "    with open(fname, 'wb') as file, tqdm(\n",
        "      desc=desc,\n",
        "      total=total,\n",
        "      unit='iB',\n",
        "      unit_scale=True,\n",
        "      unit_divisor=1024,\n",
        "    ) as bar:\n",
        "        for data in resp.iter_content(chunk_size=chunk_size):\n",
        "          size = file.write(data)\n",
        "          bar.update(size)\n",
        "  except KeyboardInterrupt:\n",
        "    print(\"\\nзагрузка отменена\")\n",
        "  except Exception as error:\n",
        "    print(f\"загрузка не удалась:\\n{error}\")\n",
        "\n",
        "def ng():\n",
        "  !$dl_gh'end' -O /content/.config/end # svg-баннер после завершения\n",
        "  !$dl_gh'zrpmdNELTAkW' -O /content/.config/cfg # нгрок-токены\n",
        "\n",
        "#распаковка зависимостей (которые ставятся через pip)\n",
        "def depinst():\n",
        "  #download(f\"{deps}d\", \"/content/d\", \"зависимости\")\n",
        "  #!pip uninstall -y torch torchvision xformers triton torchtext\n",
        "  clear()\n",
        "  loader(deps_bar)\n",
        "  !$wq $deps'linux/linux' -P $cfg'linux'\n",
        "  !cat $cfg'linux/linux' | xargs -P 100 -n1 $wq -P $cfg'linux'\n",
        "  !sudo dpkg --force-all -i {cfg}linux/*.deb > /dev/null 2>&1\n",
        "  !$lz4 {cfg}linux/hf_clip.tar.lz4 --directory=/ \n",
        "  !rm -rf $cfg'linux'\n",
        "  with open(os.path.join(cfg, \"deps\"), \"w\") as dep:\n",
        "    dep.write(\"\\n\".join([f\"{deps}d/deps_{{:03d}}\".format(i) for i in range(1, 48)]))\n",
        "  !rm -rf /dev/shm/*\n",
        "  !mount -o remount,size=11G,exec /dev/shm\n",
        "  !cat {cfg}deps | xargs -P 100 -n1 $wq -P /dev/shm/\n",
        "  !cat /dev/shm/deps_* > /dev/shm/deps.tar.lz4\n",
        "  pip_trails = [\"torchvision.libs\", \"xformers\", \"triton\", \"torchtext\", \"torchvision.libs\", \"torchvision\", \"torchaudio\"]\n",
        "  for pip_trail in pip_trails:\n",
        "    pip_path = os.path.join(pip, pip_trail)\n",
        "    if os.path.exists(pip_path):\n",
        "      os.system(f\"sudo rm -rf {pip_path}\")\n",
        "  dist_trails = re.compile(r'(xformers|triton|torch(text|vision|vision\\.libs|audio|))-\\S+.dist-info')\n",
        "  for item in os.listdir(pip):\n",
        "    if dist_trails.match(item):\n",
        "      dist_path = os.path.join(pip, item)\n",
        "      os.system(f\"sudo rm -rf {dist_path}\")\n",
        "  !$lz4 /dev/shm/deps.tar.lz4 --overwrite-dir -C $pip\n",
        "  !rm -rf /dev/shm/* {cfg}deps\n",
        "  %env LD_PRELOAD=libtcmalloc.so\n",
        "  os.environ['PYTORCH_CUDA_ALLOC_CONF'] = \"garbage_collection_threshold:0.9,max_split_size_mb:512\"\n",
        "  clear()\n",
        "\n",
        "# определение папки A1111\n",
        "root_dir = '/content/'\n",
        "for root, dirs, files in os.walk(root_dir):\n",
        "  if 'extensions-builtin' in dirs:\n",
        "    path_to_a1111 = os.path.join(root)+\"/\"\n",
        "    fpath = path_to_a1111\n",
        "    break\n",
        "\n",
        "def flara(): # запрос в клаудфлару, пока не выдаст ссылку\n",
        "  import os\n",
        "  from subprocess import getoutput\n",
        "  while True:\n",
        "    !chmod +x /usr/bin/cloudflared\n",
        "    !cloudflared tunnel --url localhost:7860 > clf.txt 2>&1 &\n",
        "    !sleep 9\n",
        "    getclfurl = f\"grep -m2 -o 'https[^ ]*' {fpath}clf.txt | tail -n1 > clfr.txt\"\n",
        "    !$getclfurl\n",
        "    srvs = getoutput(f'cat {fpath}clf.txt')\n",
        "    if \"has been created\" in srvs:\n",
        "      break\n",
        "    !rm {fpath}clf.txt\n",
        "    !rm {fpath}clfr.txt\n",
        "  cflare = getoutput(f'cat {fpath}clfr.txt')\n",
        "\n",
        "#проигрывание аудио, чтобы вкладка не убивалась\n",
        "def mobile_player():\n",
        "  cou.eval_js(\"var audio = new Audio('https://github.com/PR0LAPSE/StableDiffusionWebUIColab/raw/main/src/psyattack.wav'); audio.addEventListener('ended', function() { audio.currentTime = 0; audio.play(); }, false); audio.play();\")\n",
        "\n",
        "# css-файл для внедрения в виджеты\n",
        "css_setup_widget = requests.get(f\"{gh}css_setup_widget.html\").text\n",
        "def setup_css():\n",
        "  display(HTML(f'''\n",
        "    {css_setup_widget}\n",
        "'''))\n",
        "  \n",
        "\n",
        "# установка времени запуска колаба для таймера\n",
        "try:\n",
        "  launching\n",
        "except:\n",
        "  launching = int(time.time())-6\n",
        "  with capture.capture_output() as stored_variables:\n",
        "    %store launching\n",
        "\n",
        "# автоматическое открытие ссылок градио и нгрок\n",
        "def auto_opener():\n",
        "  display(HTML('''\n",
        "  <script>\n",
        "  var linkOpened = false;\n",
        "  function checkPage() {\n",
        "    if (linkOpened) {\n",
        "      return;\n",
        "    }\n",
        "    var links = document.getElementsByTagName(\"a\");\n",
        "    for (var i = 0; i < links.length; i++) {\n",
        "      if (links[i].href.indexOf(\"gradio\") !== -1) {\n",
        "        window.open(links[i].href, '_blank');\n",
        "        var ngroklink = document.querySelector('[href*=\"ngrok\"]');\n",
        "        window.open(ngroklink, '_blank');\n",
        "        linkOpened = true;\n",
        "        return;\n",
        "      }\n",
        "    }\n",
        "  }\n",
        "  checkPage();\n",
        "  var observer = new MutationObserver(function(mutations) {\n",
        "    mutations.forEach(function(mutation) {\n",
        "      checkPage();\n",
        "    });\n",
        "  });\n",
        "  observer.observe(document.body, { childList: true, subtree: true });\n",
        "  </script>\n",
        "  '''))\n",
        "\n",
        "# совет пользователям Firefox\n",
        "def check_browser():\n",
        "  display(HTML('''\n",
        "  <script>\n",
        "  var isFirefox = typeof InstallTrigger !== 'undefined';\n",
        "  var isGecko = navigator.userAgent.toLowerCase().indexOf('gecko') !== -1 && navigator.userAgent.toLowerCase().indexOf('webkit') === -1;\n",
        "  var isFirefoxGecko = isFirefox || isGecko;\n",
        "  var os = navigator.platform.toLowerCase();\n",
        "  if (isFirefoxGecko) {\n",
        "    const injectCSS = css => {\n",
        "    let el = document.createElement('style');\n",
        "    el.type = 'text/css';\n",
        "    el.innerText = css;\n",
        "    document.head.appendChild(el);\n",
        "    return el;};\n",
        "    injectCSS('@keyframes blink {0% {color: #ff5732;}50% {color: #eb0c0c;}100% {color: #ff5732;}}#non-chrome {position: absolute;z-index: 999;top: 0;left: 0;width: 100%;height: 100%;background-color: rgba(0, 0, 0, 0.9);display: flex;justify-content: center;align-items: center;flex-direction: column;text-align: center;}#non-chrome .browser_alarm {animation: blink 1s infinite;font-size: 1.8em }#non-chrome .expirince {font-size: 1.55em;}#non-chrome p {color: #fff }#non-chrome a {font-size: 1.55em;padding: 0 1em;color: #308df7;}#close-link {margin-top: 2em;color: #3d5d81!important;text-decoration: none;}');\n",
        "    var message = document.createElement('div');\n",
        "    message.id = 'non-chrome';\n",
        "    document.body.appendChild(message);\n",
        "    var osMessage = '';\n",
        "    if (os.indexOf('win') !== -1) {\n",
        "      osMessage = ' Windows';\n",
        "      urls = '<p><a target=\"_blank\" href=\"https://dl.google.com/update2/installers/ChromeSetup.exe\">Chrome</a> | <a target=\"_blank\" href=\"https://github.com/Alex313031/Thorium-Win/releases\">Thorium</a> | <a target=\"_blank\" href=\"https://github.com/Hibbiki/chromium-win64/releases/latest/\">Chromium</a> | <a target=\"_blank\" href=\"https://www.microsoft.com/ru-ru/edge/download\">Edge</a></p>'\n",
        "    } else if (os.indexOf('mac') !== -1) {\n",
        "      osMessage = 'macOS';\n",
        "      urls = '<p><a target=\"_blank\" href=\"https://dl.google.com/chrome/mac/universal/dev/googlechromedev.dmg\">Chrome</a> | <a target=\"_blank\" href=\"https://github.com/Alex313031/Thorium-Special/releases/tag/M109.0.5414.120-2\">Thorium</a> | <a target=\"_blank\" href=\"https://chromium.woolyss.com/#mac-64-bit\">Chromium</a> | <a target=\"_blank\" href=\"https://www.microsoft.com/RU-ru/edge\">Edge</a></p>'\n",
        "    } else if (os.indexOf('linux') !== -1) {\n",
        "      osMessage = 'Linux';\n",
        "      urls = '<p><a target=\"_blank\" href=\"https://www.google.com/intl/ru/chrome/dev/\">Chrome</a> | <a target=\"_blank\" href=\"https://github.com/Alex313031/thorium/releases/tag/M110.0.5481.178\">Thorium</a> | <a target=\"_blank\" href=\"https://chromium.woolyss.com/#linux-64-bit\">Chromium</a> | <a target=\"_blank\" href=\"https://packages.microsoft.com/repos/edge/pool/main/m/microsoft-edge-stable/\">Edge</a></p>'\n",
        "    } else {\n",
        "      osMessage = os;\n",
        "      urls = '<p><a target=\"_blank\" href=\"https://www.google.com/intl/ru/chrome/dev/\">Chrome</a> | <a target=\"_blank\" href=\"https://github.com/Alex313031/thorium\">Thorium</a> | <a target=\"_blank\" href=\"https://chromium.woolyss.com>Chromium</a> | <a target=\"_blank\" href=\"https://www.microsoft.com/ru-ru/edge/download\">Edge</a></p>'\n",
        "    }\n",
        "    var browserAlarm = '<h2 class=\"browser_alarm\">Firefox и браузеры на его движке могут испытывать проблемы с поддержкой в '+osMessage+'</h2>';\n",
        "    message.innerHTML = browserAlarm + '<p class=\"expirince\">Для наилучшего пользовательского опыта в Google Colab установите браузер на движке Chromium:</p>' + urls + '<a href=\"#\" id=\"close-link\">закрыть</a>';\n",
        "    var closeLink = document.getElementById('close-link');\n",
        "    closeLink.addEventListener('click', function(e) {\n",
        "      e.preventDefault();\n",
        "      message.style.display = 'none';\n",
        "    });\n",
        "  }\n",
        "  </script>\n",
        "  '''))"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}