{
"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",
" \n",
" '''))\n",
"\n",
"# совет пользователям Firefox\n",
"def check_browser():\n",
" display(HTML('''\n",
" \n",
" '''))"
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}