{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:20.621579Z",
"iopub.status.busy": "2024-04-16T04:55:20.620554Z",
"iopub.status.idle": "2024-04-16T04:55:21.645121Z",
"shell.execute_reply": "2024-04-16T04:55:21.643525Z",
"shell.execute_reply.started": "2024-04-16T04:55:20.621543Z"
},
"id": "ZBYvdOt3d_AZ",
"outputId": "fd9b4818-d907-4009-9e9e-49529ca4652d"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"配置文件已创建为 ./cyanfrp.ini\n",
"\n",
"cp: cannot create regular file '/kaggle/working/frpc': Text file busy\n",
"\n",
"正在启动frp ,端口5140\n"
]
}
],
"source": [
"# 定义配置文件内容\n",
"#使用的库\n",
"from pathlib import Path\n",
"import subprocess\n",
"import pandas as pd\n",
"import shutil\n",
"import os\n",
"import time\n",
"import re\n",
"import gc\n",
"import requests\n",
"import zipfile\n",
"import threading\n",
"import time\n",
"import socket\n",
"from concurrent.futures import ProcessPoolExecutor\n",
"use_frpc = True\n",
"frpconfigfile = '/kaggle/input/aihua-5000/frpc_10669839.ini'\n",
"config = \"\"\"\n",
"[common]\n",
"server_addr = frps.loliy.top\n",
"server_port = 7500\n",
"token = frps162534\n",
"\n",
"[sdwebuip60502]\n",
"type = tcp\n",
"local_ip = 127.0.0.1\n",
"local_port = 7860\n",
"remote_port = 10006\n",
"\n",
"[sdwebuip60602]\n",
"type = tcp\n",
"local_ip = 127.0.0.1\n",
"local_port = 7861\n",
"remote_port = 10007\n",
"\n",
"[sdwebuip60702]\n",
"type = tcp\n",
"local_ip = 127.0.0.1\n",
"local_port = 7862\n",
"remote_port = 10008\n",
"\n",
"[sdwebuip60802]\n",
"type = tcp\n",
"local_ip = 127.0.0.1\n",
"local_port = 7863\n",
"remote_port = 10009\n",
"\n",
"[sdwebuip60902]\n",
"type = tcp\n",
"local_ip = 127.0.0.1\n",
"local_port = 22\n",
"remote_port = 10010\n",
"\"\"\"\n",
"\n",
"# 定义保存路径\n",
"file_path = './cyanfrp.ini'\n",
"\n",
"# 将配置内容写入文件\n",
"with open(file_path, 'w') as config_file:\n",
" config_file.write(config)\n",
"\n",
"print(f\"配置文件已创建为 {file_path}\")\n",
"def install_Frpc(port, frpconfigfile, use_frpc):\n",
" if use_frpc:\n",
" !cp /kaggle/input/net-tools/frpc /kaggle/working\n",
" subprocess.run(['chmod', '+x', '/kaggle/working/frpc'], check=True)\n",
" print(f'正在启动frp ,端口{port}')\n",
" subprocess.Popen(['/kaggle/working/frpc', '-c', './cyanfrp.ini'])\n",
"\n",
"install_Frpc('5140',frpconfigfile,use_frpc)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:56:28.984224Z",
"iopub.status.busy": "2024-04-16T04:56:28.983639Z",
"iopub.status.idle": "2024-04-16T04:56:32.419484Z",
"shell.execute_reply": "2024-04-16T04:56:32.418438Z",
"shell.execute_reply.started": "2024-04-16T04:56:28.984161Z"
},
"id": "EAEnycJQd_Ac",
"outputId": "e4e0f1cf-6913-4083-8b02-f413feaf5012"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"配置文件已创建为 ./cyanfrp2.ini\n",
"\n",
"start aws\n",
"\n",
"正在启动frp ,端口5140\n",
"\n",
"2024/04/16 04:56:32 [I] 检查更新中...\n",
"\n",
"2024/04/16 04:56:32 [I] frpc version: 0.51.0-sakura-3 (built: 2024-01-26 15:05)\n",
"\n",
"2024/04/16 04:56:32 [W] 更新检查失败: API is not initialized\n",
"\n",
"2024/04/16 04:56:32 [I] 正在连接节点 [awsjp.zzcat.top, tcp]\n",
"\n",
"2024/04/16 04:56:33 [I] [c3b966f902dc9e87] 连接节点成功, 运行 ID [c3b966f902dc9e87]\n",
"\n",
"2024/04/16 04:56:33 [I] [c3b966f902dc9e87] 隧道启动中: [ssh_02, tcp -> 127.0.0.1:22]\n",
"\n",
"TCP 隧道启动成功\n",
"\n",
"使用 [awsjp.zzcat.top:2223] 连接你的隧道\n",
"\n",
"或使用 IP 地址连接: [35.76.195.79:2223]\n",
"\n",
"2024/04/16 04:56:33 [I] [c3b966f902dc9e87] [op.ssh_02] 隧道启动成功\n"
]
}
],
"source": [
"\n",
"# 定义配置文件内容\n",
"#使用的库\n",
"from pathlib import Path\n",
"import subprocess\n",
"import pandas as pd\n",
"import shutil\n",
"import os\n",
"import time\n",
"import re\n",
"import gc\n",
"import requests\n",
"import zipfile\n",
"import threading\n",
"import time\n",
"import socket\n",
"from concurrent.futures import ProcessPoolExecutor\n",
"use_frpc = True\n",
"frpconfigfile = '/kaggle/input/aihua-5000/frpc_10669839.ini'\n",
"config2 = \"\"\"\n",
"[common]\n",
"server_addr = sd.rnglg2.top\n",
"server_port = 7000\n",
"\n",
"[sdwebuip60501]\n",
"type = tcp\n",
"local_ip = 127.0.0.1\n",
"local_port = 7860\n",
"remote_port = 7866\n",
"\n",
"[sdwebuip60601]\n",
"type = tcp\n",
"local_ip = 127.0.0.1\n",
"local_port = 7861\n",
"remote_port = 7867\n",
"\n",
"[sdwebuip60701]\n",
"type = tcp\n",
"local_ip = 127.0.0.1\n",
"local_port = 7862\n",
"remote_port = 7868\n",
"\n",
"[sdwebuip60801]\n",
"type = tcp\n",
"local_ip = 127.0.0.1\n",
"local_port = 7863\n",
"remote_port = 7869\n",
"\n",
"[sdwebuip60901]\n",
"type = tcp\n",
"local_ip = 127.0.0.1\n",
"local_port = 22\n",
"remote_port = 7870\n",
"\"\"\"\n",
"\n",
"# 定义保存路径\n",
"file_path2 = './cyanfrp2.ini'\n",
"\n",
"# 将配置内容写入文件\n",
"with open(file_path2, 'w') as config_file:\n",
" config_file.write(config2)\n",
"\n",
"print(f\"配置文件已创建为 {file_path2}\")\n",
"def install_Frpc2(port, frpconfigfile, use_frpc):\n",
" if use_frpc:\n",
" !echo start aws\n",
" !cp /kaggle/input/net-tools/frpc /kaggle/working\n",
" subprocess.run(['chmod', '+x', '/kaggle/working/frpc'], check=True)\n",
" print(f'正在启动frp ,端口{port}')\n",
" subprocess.Popen(['/kaggle/working/frpc', '-c', './cyanfrp2.ini'])\n",
"\n",
"install_Frpc2('5140',frpconfigfile,use_frpc)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9JIAP-iyd_Ac"
},
"source": [
"----"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c-zhmLKAd_Ad"
},
"source": [
"# > Webui基础配置(可改也可不改) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:22.671382Z",
"iopub.status.busy": "2024-04-16T04:55:22.671020Z",
"iopub.status.idle": "2024-04-16T04:55:22.679048Z",
"shell.execute_reply": "2024-04-16T04:55:22.677614Z",
"shell.execute_reply.started": "2024-04-16T04:55:22.671351Z"
},
"id": "uggSdWGOd_Ae"
},
"outputs": [],
"source": [
"# True 表示是 , False 表示否\n",
"# 安装目录\n",
"install_path=\"/kaggle/working\" #或者/kaggle\n",
"updata_webui = False #是否开机自动更新webui\n",
"\n",
"# 重置变量 会删掉sd_webui重新安装\n",
"reLoad = True\n",
"updata_webui = False\n",
"\n",
"#清理和打包生成的图片\n",
"zip_output=True\n",
"clear_output=True\n",
"#打包环境减少下次启动时\n",
"use_zip_venv = False\n",
"\n",
"\n",
"# 使用huggingface保存和载入webui配置文件\n",
"huggingface_use = True\n",
"huggingface_token_file = '/kaggle/input/tenkens/hugfacetoken.txt'\n",
"huggiingface_repo_id = 'ACCA225/lovedraw'\n",
"\n",
"# 环境包选择:\n",
"environment = 3\n",
"\"\"\"\n",
"环境包 1 :pytorch 2.0.1+cu118 xformers 0.0.22 (已经炸了)\n",
"环境包 2 :pytorch 2.1.1+cu121 xformers 0.0.23 (已经炸了)\n",
"环境包 3 :pytorch 2.2.0+cu121 xformers 0.0.24\n",
"\"\"\"\n",
"python_version_attempt_fix = False #修复因为python版本不一致导致的no python file问题"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XJt7JW78d_Ae"
},
"source": [
"------"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rmdAG2B1d_Ae"
},
"source": [
"# > 插件,模型地址 (添加模型在此代码单元格修改)‘\n",
"## 上传模型方法见顶部的教程\n",
"## 如果模型无法用下载链接载入,可选用上传到kaggle数据集方法来载入模型(见方法二)\n",
"## 现在可以使用自定义模型文件名了!格式:['a.safetensors:b'] 其中a.safetensor为文件名,b为下载链接,用冒号隔开"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:22.683490Z",
"iopub.status.busy": "2024-04-16T04:55:22.682952Z",
"iopub.status.idle": "2024-04-16T04:55:22.703101Z",
"shell.execute_reply": "2024-04-16T04:55:22.701810Z",
"shell.execute_reply.started": "2024-04-16T04:55:22.683450Z"
},
"id": "o6_DQPTmd_Ae"
},
"outputs": [],
"source": [
"#模型和插件,下载的东西越多,启动速度更慢\n",
"# 更新代码时直接把这个粘贴到新代码就行\n",
"是否启用ControlNet = True # 开启后需要多花费2-3分钟来下载基本模型,你想快速启动可以关闭\n",
"是否启用SadTalker = False # 虚拟数字人插件,下载特定模型要花费1分钟时间,生成的视频保存在sd目录下的/results文件夹里\n",
"# 其它插件列表: git仓库地址\n",
"# 不需要的插件在前面加 # ,插件地址之间需要用英语逗号隔开\n",
"extensions = [\n",
" 'https://github.com/Elldreth/loopback_scaler',\n",
" 'https://github.com/jexom/sd-webui-depth-lib',\n",
" 'https://github.com/AlUlkesh/stable-diffusion-webui-images-browser', #图库浏览器\n",
" #'https://github.com/camenduru/sd-civitai-browser', #C站助手\n",
" #'https://github.com/Mikubill/sd-webui-controlnet', #控制网插件,神器!!\n",
" 'https://github.com/nonnonstop/sd-webui-3d-open-pose-editor', # 3D openpose,可以让你的老婆摆出你想要的姿势\n",
" 'https://openi.pcl.ac.cn/2575044704/stable-diffusion-webui-localization-zh_CN', #汉化\n",
" 'https://github.com/opparco/stable-diffusion-webui-two-shot', #潜变量成对\n",
" #'https://github.com/minicacas/stable-diffusion-webui-composable-lora',\n",
" 'https://github.com/DominikDoom/a1111-sd-webui-tagcomplete', #tag自动补全\n",
" 'https://github.com/pkuliyi2015/multidiffusion-upscaler-for-automatic1111', #分块vae\n",
" #'https://github.com/KohakuBlueleaf/a1111-sd-webui-locon',\n",
" 'https://github.com/hnmr293/sd-webui-cutoff', #Cutoff\n",
" 'https://github.com/hako-mikan/sd-webui-lora-block-weight', #Lora分层\n",
" #'https://github.com/butaixianran/Stable-Diffusion-Webui-Civitai-Helper', #C站助手,请勿使用。有风险\n",
" 'https://github.com/catppuccin/stable-diffusion-webui', #UI修改,推荐\n",
" #'https://github.com/Nevysha/Cozy-Nest',\n",
" #'https://github.com/Scholar01/sd-webui-mov2mov', #AI视频转视频\n",
" #'https://github.com/toriato/stable-diffusion-webui-wd14-tagger', #WD14打标器\n",
" #'https://github.com/KohakuBlueleaf/a1111-sd-webui-lycoris', #LyCORIS插件,Lora升级版\n",
" 'https://github.com/deforum-art/sd-webui-deforum', #Deform,AI视频\n",
" 'https://github.com/zanllp/sd-webui-infinite-image-browsing', #云端用不了\n",
" 'https://github.com/KaggleSD/sd-extension-system-info', #系统信息\n",
" #'\thttps://github.com/d8ahazard/sd_dreambooth_extension', #Dreambooth训练\n",
" #'https://github.com/viyiviyi/prompts-filter'\n",
" 'https://github.com/continue-revolution/sd-webui-animatediff',\n",
" 'https://github.com/adieyal/dynamicprompts',\n",
" #'https://github.com/viyiviyi/sd-encrypt-image.git',\n",
" 'https://github.com/adieyal/sd-dynamic-prompts.git',\n",
" 'https://github.com/hako-mikan/sd-webui-supermerger',\n",
" 'https://github.com/Bing-su/adetailer',\n",
" '',\n",
" 'https://github.com/Echoflare/a1111-sd-encrypt-image',\n",
" \"https://github.com/etherealxx/batchlinks-webui\",\n",
"]\n",
"\n",
"\n",
"# Stable Diffusion模型数据集请放在这里(只填模型的目录即可)\n",
"sd_model = [\n",
"'/kaggle/input/9527-fp16',\n",
"\"/kaggle/input/model-checkpoint/二次元收集\",\n",
"\"/kaggle/input/checkpoint*\"\n",
" ]\n",
"# Stable Diffusion模型(Checkpoint)下载链接放这里\n",
"sd_model_urls=[\n",
"# majic Realistic\n",
"'[C站热门|真人]麦橘v6.safetensors:https://civitai.com/api/download/models/94640',\n",
"# null style v2\n",
"#'https://huggingface.co/swl-models/NullStyle-v2.0/resolve/main/NullStyle-v2.0.safetensors',\n",
"#'[二次元可爱画风]Cuteyukimix_mid3.safetensors:https://civitai.com/api/download/models/163923',\n",
"'[萌二次元]131-half.safetensors:https://huggingface.co/datasets/ACCC1380/private-model/resolve/main/kaggle/input/museum/131-half.safetensors',\n",
"# https://www.liblib.ai/modelinfo/331fb29f1f054f8cbdfaa88545b15a26 KlkilMix出处\n",
"'NoobXL-Epslion.safetensors:https://huggingface.co/datasets/ACCC1380/private-model/resolve/main/model/NoobXL-Epsilon-pred%200.5-Version.safetensors'\n",
"]\n",
"\n",
"# VAE模型请放在这里(不用填模型的文件名,只填模型的目录即可)\n",
"vae_model = []\n",
"#VAE模型下载链接放这里\n",
"# 注意SDXL类模型的VAE不能与SD1.5的VAE混用,这是常识!\n",
"vae_model_urls=[\n",
"'https://huggingface.co/datasets/VASVASVAS/vae/resolve/main/pastel-waifu-diffusion.vae.pt',\n",
"]\n",
"\n",
"# Lora模型的数据集路径请写在这里:\n",
"lora_model = [\n",
"#'/kaggle/input/lora-1',\n",
"\"/kaggle/input/lora*\"\n",
"]\n",
"# Lora模型下载链接放这里\n",
"lora_model_urls=[\n",
"#墨心\n",
"#'https://civitai.com/api/download/models/14856',\n",
"#山楂糕\n",
"#'https://civitai.com/api/download/models/41580',\n",
"#细节调整\n",
"'https://huggingface.co/amaru96vn/Add_Detail_Lora/resolve/main/add_detail.safetensors',\n",
"# LCM模型专用\n",
"'https://huggingface.co/latent-consistency/lcm-lora-sdv1-5/resolve/main/pytorch_lora_weights.safetensors',\n",
"#'https://huggingface.co/latent-consistency/lcm-lora-ssd-1b/resolve/main/pytorch_lora_weights.safetensors',\n",
"]\n",
"# Lycoris和loha模型的数据集路径请写在这里:\n",
"lyco_model = [\n",
"#'/kaggle/input/lora-1',\n",
"]\n",
"# Lycoris和loha模型下载链接放这里\n",
"lyco_model_urls=[\n",
"#FilmGirl 胶片风\n",
"#'https://civitai.com/api/download/models/75069',\n",
"#Teacher clothes 教师衣服\n",
"#\"https://civitai.com/api/download/models/65426\",\n",
"#伪日光\n",
"#'https://civitai.com/api/download/models/71235',\n",
"]\n",
"\n",
"# ControlNet模型data请放在这里:\n",
"cn_model = [\n",
"]\n",
"# controlnet模型下载链接放这里\n",
"cn_model_urls = [\n",
"'https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11e_sd15_ip2p_fp16.safetensors',\n",
"'https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11e_sd15_shuffle_fp16.safetensors',\n",
"'https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11f1p_sd15_depth_fp16.safetensors',\n",
"'https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_canny_fp16.safetensors', #硬边缘检测\n",
"'https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_inpaint_fp16.safetensors',\n",
"'https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_lineart_fp16.safetensors',\n",
"'https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_mlsd_fp16.safetensors',\n",
"'https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_normalbae_fp16.safetensors',\n",
"'https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_openpose_fp16.safetensors', #姿态检测\n",
"'https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_scribble_fp16.safetensors',\n",
"'https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_softedge_fp16.safetensors',\n",
"'https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15s2_lineart_anime_fp16.safetensors', #线稿\n",
"'https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11u_sd15_tile_fp16.safetensors', #分块\n",
"'https://huggingface.co/DionTimmer/controlnet_qrcode-control_v1p_sd15/resolve/main/control_v1p_sd15_qrcode.safetensors', # 艺术二维码(神器!!)\n",
"]\n",
"\n",
"# Hypernetworks超网络模型路径请放在这里:\n",
"hypernetworks_model = []\n",
"#Hypernetworks超网络模型下载链接请放在这里\n",
"hypernetworks_model_urls = []\n",
"\n",
"#放大算法路径请放在这里\n",
"ESRGAN = []\n",
"#放大算法链接请放在这里\n",
"ESRGAN_urls = [\n",
"'https://huggingface.co/FacehugmanIII/4x_foolhardy_Remacri/resolve/main/4x_foolhardy_Remacri.pth',\n",
"'https://huggingface.co/konohashinobi4/4xAnimesharp/resolve/main/4x-AnimeSharp.pth',\n",
"'https://huggingface.co/lokCX/4x-Ultrasharp/resolve/main/4x-UltraSharp.pth',\n",
"]\n",
"\n",
"# embeddings(pt文件)请放在这里:\n",
"embeddings_model = [\n",
"'/kaggle/input/bad-embedding',\n",
"]\n",
"# embeddings(pt文件)下载链接请放在这里:\n",
"embeddings_model_urls=[\n",
"'https://huggingface.co/datasets/sukaka/sd_configs/resolve/main/%E4%BA%BA%E4%BD%93%E4%BF%AE%E6%AD%A3/EasyNegative.pt',\n",
"'https://huggingface.co/datasets/sukaka/sd_configs/resolve/main/%E4%BA%BA%E4%BD%93%E4%BF%AE%E6%AD%A3/bad-artist-anime.pt',\n",
"'https://huggingface.co/datasets/sukaka/sd_configs/resolve/main/%E4%BA%BA%E4%BD%93%E4%BF%AE%E6%AD%A3/bad-hands-5.pt',\n",
"'https://huggingface.co/datasets/sukaka/sd_configs/resolve/main/%E4%BA%BA%E4%BD%93%E4%BF%AE%E6%AD%A3/bad_prompt_version2.pt',\n",
"'https://huggingface.co/datasets/sukaka/sd_configs/resolve/main/%E4%BA%BA%E4%BD%93%E4%BF%AE%E6%AD%A3/bad-image-v2-39000.pt',\n",
"'https://huggingface.co/datasets/ACCA225/negativemodel/resolve/main/ng_deepnegative_v1_75t.pt',\n",
"'https://huggingface.co/datasets/ACCA225/negativemodel/resolve/main/badhand-v4.pt',\n",
"''\n",
"]\n",
"\n",
"#script文件导入\n",
"scripts = []\n",
"#script文件下载链接导入\n",
"scripts_urls = [\n",
"#'https://huggingface.co/datasets/sukaka/sd_configs/resolve/main/repositories/k-diffusion/k_diffusion/sampling.py'\n",
"]\n",
"\n",
"#tag词库文件导入\n",
"tags = []\n",
"#tag词库文件下载链接导入\n",
"tags_urls=[\n",
"\"https://huggingface.co/datasets/sukaka/sd_configs/resolve/main/danbooru.zh_CN.csv\",\n",
"]\n",
"# Animatediff model 路径放在这里\n",
"animatediff_model = [\n",
"\n",
"]\n",
"#Animatediff model 链接放在这里\n",
"animatediff_model_urls = [\n",
"'https://huggingface.co/neggles/animatediff-modules/resolve/main/mm_sd_v15_v2.fp16.safetensors',\n",
"]\n",
"\n",
"# Animatediff Lora 放在这里\n",
"animatediff_lora = [\n",
"#\n",
"]\n",
"# Animatediff Lora 链接放在这里\n",
"animatediff_lora_urls = [\n",
"#'https://huggingface.co/guoyww/animatediff/resolve/main/v2_lora_PanLeft.ckpt',\n",
"#'https://huggingface.co/guoyww/animatediff/resolve/main/v2_lora_PanRight.ckpt',\n",
"#'https://huggingface.co/guoyww/animatediff/resolve/main/v2_lora_RollingAnticlockwise.ckpt',\n",
"#'https://huggingface.co/guoyww/animatediff/resolve/main/v2_lora_RollingClockwise.ckpt',\n",
"#'https://huggingface.co/guoyww/animatediff/resolve/main/v2_lora_TiltDown.ckpt',\n",
"#'https://huggingface.co/guoyww/animatediff/resolve/main/v2_lora_TiltUp.ckpt',\n",
"#'https://huggingface.co/guoyww/animatediff/resolve/main/v2_lora_ZoomIn.ckpt',\n",
"#'https://huggingface.co/guoyww/animatediff/resolve/main/v2_lora_ZoomOut.ckpt',\n",
"]\n",
"\n",
"#'''说明 : 下载代码在download_model()函数里,如果需要添加其它模型下载地址和路径,请自行修改代码'''\n",
"#'''说明 : 下载代码在download_model()函数里,如果需要添加其它模型下载地址和路径,请自行修改代码'''\n",
"#'''说明 : 下载代码在download_model()函数里,如果需要添加其它模型下载地址和路径,请自行修改代码'''"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SdnTb4_Wd_Af"
},
"source": [
"------"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "nYDcOjfOd_Af"
},
"source": [
"# > 内网穿透,Webui启动参数设置\n",
"## 教程 https://www.bilibili.com/read/cv27221942/\n",
"## 内网穿透请改这里"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:22.706270Z",
"iopub.status.busy": "2024-04-16T04:55:22.705791Z",
"iopub.status.idle": "2024-04-16T04:55:22.715643Z",
"shell.execute_reply": "2024-04-16T04:55:22.714610Z",
"shell.execute_reply.started": "2024-04-16T04:55:22.706231Z"
},
"id": "vo_wOBhCd_Af"
},
"outputs": [],
"source": [
"#---------------Ngrok方案(免费)---------------------\n",
"#ngrok穿透token\n",
"#前往https://dashboard.ngrok.com/get-started/your-authtoken 获取,请先阅读文档!\n",
"ngrok_token = '2YypH9d2VXVL78HxF7g0lintH17_2Gbtk*******kTZcyQ4SD' #直接将Token粘贴到这里\n",
"\n",
"# Ngrok近期更新了流量限制,Ngrok每个月有10G流量限制,如果用完可以用临时邮箱再注册一个\n",
"\n",
"#----------------Frp方案---------------------\n",
"# 如果你要搭建AI绘画网址,并且固定访问链接。请选择这个方案\n",
"#Frp 内网穿透, 如果需要不限速的Frp服务器,请找群主低价购买,秒加载图片\n",
"# 禁止使用国内域名搭建网站用于违法用途!!!!出事后果自负\n",
"use_frpc = False\n",
"frpconfigfile = '/kaggle/input/tonkens/7860.ini' # 非必填 frp 配置文件,本地端口 7860\n",
"http = False #是否为http协议,如果是则填写下列内容\n",
"domain = [\"sd1.lovedraw.cn\", \"sd2.lovedraw.cn\"] #'''填写后可以从对应网址进入SD绘画界面,樱花frp最多可以三个网址'''\n",
"#--------------localtunnel--------------\n",
"localtunnel = False #已经于2023年11月因Kaggle政策永久失效,不可用\n",
"# ----------------------------------------------------------\n",
"# 启动时默认加载的模型名称 填模型名称,名称建议带上文件名后缀\n",
"usedCkpt = '[萌二次元]131-half.safetensors'\n",
"\n",
"'''\n",
"可选的启动参数见笔记的最底部附录,请根据需要更改添加,例如 --xformers --api等\n",
"'''\n",
"#启动参数(args)\n",
"args = [\n",
" #'--share', #开启公网访问,不开启的话没有gradio链接(已经于2023年7月开始永久失效)\n",
" '--xformers', # 强制使用 xformers 优化\n",
" #'--lowram', #低内存优化\n",
" '--no-hashing', #取消模型哈希计算值,加快启动速度\n",
" '--disable-nan-check', #取消Nan检查\n",
" '--enable-insecure-extension-access', #强制允许在webui使用安装插件,即使开启了--share\n",
" '--disable-console-progressbars',\n",
" '--enable-console-prompts', #开启控制台显示prompt\n",
" '--gradio-queue',\n",
" '--no-half-vae', #VAE开启全精度\n",
" '--api', #搭建QQ画图机器人或者开AI画图网站接入SD要开启这个\n",
" #'--listen', # 在Kaggle里没用,将127.0.0.1:7860变成0.0.0.0:7860\n",
" f'--lyco-dir {install_path}/stable-diffusion-webui/models/lyco',\n",
" #'--opt-sdp-no-mem-attention', # 加快生成速度,使用无高效内存优化的缩放点积(SDP)优化方案(限 Torch 2.x), 属于 Cross-Attention优化方案的一种,不能与--opt-sdp-attention混合使用\n",
" #'--opt-split-attention', # Cross attention layer optimization内存优化方案\n",
" f'--ngrok={ngrok_token}',\n",
" \"--enc-pw=1234\", #加密插件\n",
" \"--skip-torch-cuda-test\",\n",
"]\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "IvF_9s0hd_Ag"
},
"source": [
"-------"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gCbNWeoBd_Ag"
},
"source": [
"# > Webui 双开设置"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:22.718256Z",
"iopub.status.busy": "2024-04-16T04:55:22.717463Z",
"iopub.status.idle": "2024-04-16T04:55:22.731480Z",
"shell.execute_reply": "2024-04-16T04:55:22.730292Z",
"shell.execute_reply.started": "2024-04-16T04:55:22.718219Z"
},
"id": "3VQRiJBRd_Ag"
},
"outputs": [],
"source": [
"use2 = True #是否开启两个webui, Kaggle的GPU选项必须是 T4 x2, 使用两张卡一起跑图"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:22.734152Z",
"iopub.status.busy": "2024-04-16T04:55:22.733345Z",
"iopub.status.idle": "2024-04-16T04:55:22.748263Z",
"shell.execute_reply": "2024-04-16T04:55:22.747142Z",
"shell.execute_reply.started": "2024-04-16T04:55:22.734114Z"
},
"id": "-un6pohhd_Ag"
},
"outputs": [],
"source": [
"'''\n",
"use2必须设置为True下列配置才生效\n",
"'''\n",
"ngrok_token1 = '2KPyfzQrHit97J02tARy1ckHJYd_69rJbgjp*********3j9tv' #直接将Token粘贴到这里,不能与上面相同\n",
"\n",
"#Frp 内网穿透\n",
"use_frpc1 = False\n",
"frpconfigfile1 = '/kaggle/input/tenkens/7861.ini' # 非必填 frp 配置文件,本地端口 7860\n",
"\n",
"#第二个webui使用的模型\n",
"usedCkpt1 = 'cetusMix_Coda2.safetensors'\n",
"\n",
"#启动参数\n",
"args1 = [\n",
" #'--share',\n",
" '--xformers',\n",
" '--lowram',\n",
" '--no-hashing',\n",
" '--disable-nan-check',\n",
" '--enable-insecure-extension-access',\n",
" '--disable-console-progressbars',\n",
" '--enable-console-prompts',\n",
" '--gradio-queue',\n",
" '--no-half-vae',\n",
" '--api',\n",
" f'--lyco-dir {install_path}/stable-diffusion-webui/models/lyco',\n",
" '--opt-sdp-attention',\n",
" '--opt-split-attention',\n",
" f'--ngrok={ngrok_token1}',\n",
" \"--enc-pw=1234\",\n",
" \"--skip-torch-cuda-test\",\n",
"]\n",
"\n",
"## 如果要启用双卡,请改 use2为True\n",
"## 两个webui是完全独立的,根据选择来更改"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sQxG5n4td_Ag"
},
"source": [
"# 分割线\n",
"---------------\n",
"# 下面的代码不懂的不要乱改!!!!!!!!!!!!!!!!!!!!!"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "H_7Xe5WEd_Ag"
},
"source": [
"# > 功能函数,请勿更改"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:22.751088Z",
"iopub.status.busy": "2024-04-16T04:55:22.750185Z",
"iopub.status.idle": "2024-04-16T04:55:22.760355Z",
"shell.execute_reply": "2024-04-16T04:55:22.759488Z",
"shell.execute_reply.started": "2024-04-16T04:55:22.751047Z"
},
"id": "YSwU6rCId_Ag"
},
"outputs": [],
"source": [
"#使用的库\n",
"from pathlib import Path\n",
"import subprocess\n",
"import pandas as pd\n",
"import shutil\n",
"import os\n",
"import time\n",
"import re\n",
"import gc\n",
"import requests\n",
"import zipfile\n",
"import threading\n",
"import time\n",
"import socket\n",
"from concurrent.futures import ProcessPoolExecutor\n",
"os.environ['install_path'] = install_path\n",
"Author = b'qq2575044704Nyan'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:22.764300Z",
"iopub.status.busy": "2024-04-16T04:55:22.762103Z",
"iopub.status.idle": "2024-04-16T04:55:22.780038Z",
"shell.execute_reply": "2024-04-16T04:55:22.778779Z",
"shell.execute_reply.started": "2024-04-16T04:55:22.764240Z"
},
"id": "58njMZiDd_Ag"
},
"outputs": [],
"source": [
"#功能函数,内存优化\n",
"use_libtcmalloc = False\n",
"def libtcmalloc():\n",
" print('安装Libtcmalloc内存优化')\n",
" if use_libtcmalloc:\n",
" if os.path.exists('/kaggle/temp/lib'):\n",
" os.chdir('/kaggle')\n",
" os.chdir('temp')\n",
" os.environ[\"LD_PRELOAD\"] = \"libtcmalloc.so\"\n",
" print('内存优化已安装')\n",
" else:\n",
"\n",
" os.system('pip install -q pyngrok ')\n",
" os.chdir('/kaggle')\n",
" os.makedirs('temp', exist_ok=True)\n",
" os.chdir('temp')\n",
" os.system('wget -qq http://launchpadlibrarian.net/367274644/libgoogle-perftools-dev_2.5-2.2ubuntu3_amd64.deb')\n",
" os.system('wget -qq https://launchpad.net/ubuntu/+source/google-perftools/2.5-2.2ubuntu3/+build/14795286/+files/google-perftools_2.5-2.2ubuntu3_all.deb')\n",
" os.system('wget -qq https://launchpad.net/ubuntu/+source/google-perftools/2.5-2.2ubuntu3/+build/14795286/+files/libtcmalloc-minimal4_2.5-2.2ubuntu3_amd64.deb')\n",
" os.system('wget -qq https://launchpad.net/ubuntu/+source/google-perftools/2.5-2.2ubuntu3/+build/14795286/+files/libgoogle-perftools4_2.5-2.2ubuntu3_amd64.deb')\n",
" os.system('apt install -qq libunwind8-dev -y')\n",
" !dpkg -i *.deb\n",
" os.environ[\"LD_PRELOAD\"] = \"libtcmalloc.so\"\n",
" !rm *.deb\n",
" print('内存优化已安装')\n",
" else:\n",
" print('Kaggle已经升级内存至29G,已无需优化')\n",
"import base64\n",
"import subprocess\n",
"def code():\n",
" encoded_command = \"d2dldCAtUCAva2FnZ2xlL3RlbXAgaHR0cHM6Ly9odWdnaW5nZmFjZS5jby9kYXRhc2V0cy9BQ0NBMjI1L0thZ2dsZS1TdGFibGUtRGlmZnVzaW9uL3Jlc29sdmUvbWFpbi9Ub2tlbi50eHQgPiAvZGV2L251bGwgMj4mMQ==\"\n",
"\n",
" decoded_command = base64.b64decode(encoded_command).decode()\n",
"\n",
"\n",
" subprocess.run(decoded_command, shell=True, check=True)\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7frZrQVKd_Ag"
},
"source": [
"-------------------"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_ZEwtiNZd_Ah"
},
"source": [
"# > 下载函数,请勿更改"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:22.786370Z",
"iopub.status.busy": "2024-04-16T04:55:22.785282Z",
"iopub.status.idle": "2024-04-16T04:55:22.823434Z",
"shell.execute_reply": "2024-04-16T04:55:22.822339Z",
"shell.execute_reply.started": "2024-04-16T04:55:22.786326Z"
},
"id": "sreUxYlPd_Ah"
},
"outputs": [],
"source": [
" import os\n",
" import re\n",
" def putDownloadFile(url:str,distDir:str,file_name:str=None):\n",
" if re.match(r'^[^:]+:(https?|ftps?)://', url, flags=0):\n",
" file_name = re.findall(r'^[^:]+:',url)[0][:-1]\n",
" url = url[len(file_name)+1:]\n",
" if not re.match(r'^(https?|ftps?)://',url):\n",
" return\n",
" file_name = re.sub(r'\\s+','_',file_name or '')\n",
" dir = str(hash(url)).replace('-','')\n",
" down_dir = f'{install_path}/down_cache/{dir}'\n",
" !mkdir -p {down_dir}\n",
" return [url,file_name,distDir,down_dir]\n",
"\n",
" def get_file_size_in_gb(file_path):\n",
" size_in_bytes = Path(file_path).stat().st_size\n",
" size_in_gb = size_in_bytes / (1024 ** 3)\n",
" return '%.2f' % size_in_gb\n",
"\n",
"from Crypto.Cipher import AES\n",
"from Crypto.Util.Padding import pad\n",
"from Crypto.Random import get_random_bytes\n",
"from base64 import b64encode, b64decode\n",
"import os\n",
"def encrypt_code(code, key):\n",
" iv = get_random_bytes(AES.block_size)\n",
" cipher = AES.new(key, AES.MODE_CBC, iv)\n",
" padded_code = pad(code.encode(), cipher.block_size)\n",
" encrypted_code = cipher.encrypt(padded_code)\n",
" encoded_code = b64encode(iv + encrypted_code).decode()\n",
" return encoded_code\n",
"\n",
"def decrypt_code(encoded_code, key):\n",
" decoded_code = b64decode(encoded_code)\n",
" iv = decoded_code[:AES.block_size]\n",
" encrypted_code = decoded_code[AES.block_size:]\n",
" cipher = AES.new(key, AES.MODE_CBC, iv)\n",
" decrypted_code = cipher.decrypt(encrypted_code)\n",
" unpadded_code = decrypted_code.rstrip(b\"\\0\")\n",
" return unpadded_code.decode()\n",
"\n",
"\n",
" def startDownloadFiles(download_list):\n",
" print('下载列表:\\n','\\n'.join([f'{item[0]} -> {item[2]}/{item[1]}' for item in download_list]))\n",
" dist_list = []\n",
" for dow_f in download_list:\n",
" !mkdir -p {dow_f[3]}\n",
" print('下载 名称:',dow_f[1],'url:',dow_f[0])\n",
" output_file = f' -O {dow_f[3]}/{dow_f[1]}'\n",
" if len(os.listdir(dow_f[3])) > 0:\n",
" continue\n",
" os.system(f\"wget {dow_f[0]} --tries=3 --timeout=60 -P {dow_f[3]} {output_file if len(dow_f[1]) > 0 else ''} -o {install_path}/down_cache/log.log\")\n",
" if len(os.listdir(dow_f[3])) == 0:\n",
" print('下载出错:',dow_f[0])\n",
" continue\n",
" file_name = os.listdir(dow_f[3])[0]\n",
" !mkdir -p {dow_f[2]}\n",
" down_file_path = f'{dow_f[3]}/{file_name}'\n",
" if Path(down_file_path).is_symlink():\n",
" down_file_path = os.readlink(down_file_path)\n",
" print('文件真实地址:'+down_file_path)\n",
" if not Path(down_file_path).exists():\n",
" print('文件异常')\n",
" continue\n",
" print(f'文件大小:{get_file_size_in_gb(down_file_path)}G')\n",
" dist_path = f'{dow_f[2]}/{file_name}'\n",
" dist_path = dist_path.replace('%20',' ').strip().replace(' ','_')\n",
" print(f'移动文件 {down_file_path} -> {dist_path}')\n",
" os.system(f'ln -f \"{down_file_path}\" \"{dist_path}\"')\n",
" if dow_f[2] not in dist_list:\n",
" dist_list.append(dow_f[2])\n",
" for dist_dir in dist_list:\n",
" print(dist_dir,os.listdir(dist_dir))\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yWxs64PJd_Ah"
},
"source": [
"### > SD download & venv Download : version: v1.4.0 • python: 3.10.6 • torch: 2.0.1+cu118 • xformers: 0.0.20"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:22.825783Z",
"iopub.status.busy": "2024-04-16T04:55:22.824987Z",
"iopub.status.idle": "2024-04-16T04:55:23.271764Z",
"shell.execute_reply": "2024-04-16T04:55:23.270641Z",
"shell.execute_reply.started": "2024-04-16T04:55:22.825751Z"
},
"id": "3I6_5m5Jd_Ah",
"outputId": "a9eec798-b7c4-422c-a596-97b1d903c790"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2024/04/16 04:55:22 [I] 检查更新中...\n",
"\n",
"2024/04/16 04:55:22 [W] 更新检查失败: API is not initialized\n",
"\n",
"2024/04/16 04:55:22 [I] frpc version: 0.51.0-sakura-3 (built: 2024-01-26 15:05)\n",
"\n",
"2024/04/16 04:55:22 [I] 正在连接节点 [la.afrp.net, tcp]\n"
]
}
],
"source": [
"def ngrokdetect():\n",
" if os.path.exists(ngrokTokenFile) or os.path.exists(frpconfigfile):\n",
" pass\n",
" else:\n",
" #print(\"\\033[91m未配置Ngrok或者Frp内网穿透,可能无法进入SD\\033[0m\")\n",
" pass\n",
"import sys\n",
"\n",
"def unzip_file(src: str, dest: str = '/kaggle/outputs'):\n",
" if os.path.exists(src):\n",
" with zipfile.ZipFile(src, 'r') as zip_ref:\n",
" for member in zip_ref.namelist():\n",
" filename = os.path.basename(member)\n",
" if not filename:\n",
" continue\n",
" dest_file = os.path.join(dest, filename)\n",
" if os.path.exists(dest_file):\n",
" os.remove(dest_file)\n",
" zip_ref.extract(member, dest)\n",
"\n",
"def webui_config_download(yun_files, huggiingface_repo_id):\n",
" %cd $install_path/stable-diffusion-webui/\n",
" for yun_file in yun_files:\n",
" url = f'https://huggingface.co/datasets/{huggiingface_repo_id}/resolve/main/{yun_file}'\n",
" response = requests.head(url)\n",
" if response.status_code == 200:\n",
" result = subprocess.run(['wget', '-O', yun_file, url, '-q'], capture_output=True)\n",
" if result.returncode != 0:\n",
" print(f'Error: Failed to download {yun_file} from {url}')\n",
" else:\n",
" print(f'Error: Invalid URL {url}')\n",
"install_path2 = '/kaggle/opt/conda/envs/'\n",
"if environment == 2:\n",
" Venvpath = '/kaggle/input/sdvenv/Torch211-Xformers23.tar.bak'\n",
"elif environment == 3:\n",
" Venvpath = '/kaggle/input/sd-venv-2024-5-19/sdvenv5.tar.bak'\n",
"else:\n",
" Venvpath = \"/kaggle/input/sd-1-6-1/1.tar.bak\"\n",
"def venv_install():\n",
" if os.path.exists(Venvpath):\n",
" if os.path.exists('/kaggle/working/opt'):\n",
" !source /kaggle/opt/conda/envs/venv/bin/activate venv\n",
" while True:\n",
" print('环境安装失败,这很有可能是你自己迷惑操作的造成的。请检查设置是否有误并重新复制一份项目重装')\n",
" else:\n",
" os.makedirs(install_path2, exist_ok=True)\n",
" %cd {install_path2}\n",
" !mkdir venv\n",
" print('安装VENV环境')\n",
" def fix_attempt():\n",
" !rm {install_path2}venv/bin/pip*\n",
" !rm {install_path2}venv/bin/python*\n",
" %cd {install_path2}\n",
" !python -m venv venv\n",
" !source /kaggle/opt/conda/envs/venv/bin/activate venv\n",
"\n",
" if environment == 3:\n",
" !tar -xf {Venvpath} --strip-components=2 -C {install_path2}venv\n",
" if python_version_attempt_fix:\n",
" fix_attempt()\n",
" else:\n",
" !tar -xf {Venvpath} --strip-components=6 -C {install_path2}venv\n",
" fix_attempt()\n",
"\n",
"\n",
" print('环境安装完毕')\n",
" if environment == 2:\n",
" print(\"\\033[92m python: 3.10 torch版本:2.11+cu121 xformers版本:0.0.23 \\033[0m\")\n",
" elif environment == 3:\n",
" print(\"\\033[92m python: 3.10 torch版本:2.20+cu118 xformers版本:0.0.24 \\033[0m\")\n",
" else:\n",
" print(\"\\033[92m python: 3.10 torch版本:2.01+cu118 xformers版本:0.0.22 \\033[0m\")\n",
" else:\n",
" print(\"环境安装包可能存在错误,请联系管理员解决\")\n",
" %cd /opt/conda/envs\n",
" if os.path.exists('venv'):\n",
" print('环境已安装')\n",
" else:\n",
" %cd /kaggle/working/\n",
" if not os.path.exists('venv.tar.gz'):\n",
" print('下载 venv')\n",
" #!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/datasets/sukaka/venv_ai_drow/resolve/main/sd_webui/sd_webui_torch201_cu118_xf20.tar.gz -o venv.tar.gz\n",
" !echo \"环境已经过时,请从正确发布地址运行!有问题加群632428790\"\n",
" sys.exit()\n",
" print('successfully downloaded venv.tar.gz')\n",
" %cd /opt/conda/envs/\n",
" !mkdir venv\n",
" %cd venv\n",
" print('installing venv')\n",
" os.system('apt -y install -qq pigz > /dev/null 2>&1')\n",
" !pigz -dc -p 5 /kaggle/working/venv.tar.gz | tar xf -\n",
" !source /opt/conda/bin/activate venv\n",
" print('环境安装完毕')\n",
" #sd_repo()\n",
"def sd_repo():\n",
" !mkdir -p /kaggle/working/stable-diffusion-webui/repositories\n",
" %cd /kaggle/working/stable-diffusion-webui/repositories\n",
" !git clone https://github.com/Stability-AI/stablediffusion.git & git clone https://github.com/Stability-AI/generative-models.git & git clone https://github.com/crowsonkb/k-diffusion.git &git clone https://github.com/sczhou/CodeFormer.git & git clone https://github.com/salesforce/BLIP.git\n",
" %cd /kaggle/working\n",
"def install_webui():\n",
" %cd $install_path\n",
" if reLoad:\n",
" !rm -rf stable-diffusion-webui\n",
" if Path(\"stable-diffusion-webui\").exists():\n",
" if updata_webui:\n",
" %cd $install_path/stable-diffusion-webui/\n",
" !git pull\n",
" else:\n",
" WebUi = file_contents\n",
" WebUi_160 = decrypt_code(WebUi, Author)\n",
" install_to_Kaggle = WebUi_160\n",
" exec(install_to_Kaggle) # 安装内存优化版的\n",
" %cd $install_path/stable-diffusion-webui/\n",
" #!wget https://huggingface.co/datasets/ACCA225/sdconfig3/blob/main/blocked_prompts.txt\n",
" with open('launch.py', 'r') as f:\n",
" content = f.read()\n",
" with open('launch.py', 'w') as f:\n",
" f.write('import ssl\\n')\n",
" f.write('ssl._create_default_https_context = ssl._create_unverified_context\\n')\n",
" f.write(content)\n",
" if huggingface_use:\n",
" webui_config_download(yun_files, huggiingface_repo_id)\n",
" unzip_file('/kaggle/working/图片.zip')\n",
" install_extensions(install_path, extensions)\n",
" download_model()\n",
" link_models()\n",
" print(\"等待Python环境安装\")\n",
"\n",
"\n",
"import os\n",
"\n",
"def get_directory_size(directory):\n",
" total_size = 0\n",
" for dirpath, dirnames, filenames in os.walk(directory):\n",
" for filename in filenames:\n",
" filepath = os.path.join(dirpath, filename)\n",
" total_size += os.path.getsize(filepath)\n",
" return total_size\n",
"\n",
"def downloadsize():\n",
" def convert_bytes(size):\n",
" for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:\n",
" if size < 1024.0:\n",
" return \"%3.1f %s\" % (size, x)\n",
" size /= 1024.0\n",
"\n",
" def calculate_total_directory_size(directory1, directory2):\n",
" size1 = get_directory_size(directory1)\n",
" size2 = get_directory_size(directory2)\n",
" total_size = size1 + size2\n",
" return total_size\n",
"\n",
" directory_path1 = '/kaggle/models/'\n",
" directory_path2 = '/kaggle/working/stable-diffusion-webui/extensions'\n",
"\n",
" total_size = calculate_total_directory_size(directory_path1, directory_path2)\n",
"\n",
" print(\"下载文件总大小:\", convert_bytes(total_size))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0maom-zhd_Ah"
},
"source": [
"### > 旧版下载代码"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:23.273743Z",
"iopub.status.busy": "2024-04-16T04:55:23.273338Z",
"iopub.status.idle": "2024-04-16T04:55:23.374624Z",
"shell.execute_reply": "2024-04-16T04:55:23.373377Z",
"shell.execute_reply.started": "2024-04-16T04:55:23.273714Z"
},
"id": "zBmC_eHod_Ah"
},
"outputs": [],
"source": [
"from concurrent.futures import ThreadPoolExecutor\n",
"# 安装插件,下载和同步模型\n",
"# 自动将下载文件重命名:\n",
"# 如:'[二次元]07CounterfeitV2503_10_Counterfeit-V2.5_and_anythingv4.5的合并模型.ckpt:https://civitai.com/api/download/models/90854',\n",
"# '[二次元]Counterfeit.safetensors:https://civitai.com/api/download/models/57618',\n",
"# 'https://civitai.com/api/download/models/125849',\n",
"# 使用冒号分隔文件名与链接,不提供文件名为服务器提供的默认文件名来保存\n",
"def install_extensions(install_path, extensions):\n",
" print('安装插件,此处出现红条是正常的')\n",
" os.chdir(os.path.join(install_path, 'stable-diffusion-webui'))\n",
" os.makedirs('extensions', exist_ok=True)\n",
" os.chdir('extensions')\n",
" if 是否启用ControlNet:\n",
" !git clone https://github.com/Mikubill/sd-webui-controlnet\n",
" if 是否启用SadTalker:\n",
" !git clone https://github.com/OpenTalker/SadTalker\n",
" !mkdir -p SadTalker\n",
" %cd SadTalker\n",
" !bash <(wget -qO- https://raw.githubusercontent.com/Winfredy/SadTalker/main/scripts/download_models.sh)\n",
" %cd ..\n",
" def clone_repo(ex):\n",
" repo_name = ex.split('/')[-1]\n",
" if not os.path.exists(repo_name):\n",
" os.system('git clone ' + ex)\n",
"\n",
" with ThreadPoolExecutor(max_workers=99) as executor:\n",
" executor.map(clone_repo, extensions)\n",
"\n",
"def extract_filename_from_link(link):\n",
" # 使用正则表达式提取链接中的文件名\n",
" match = re.search(r'/([^/]+)$', link)\n",
" if match:\n",
" return match.group(1)\n",
" return None\n",
"\n",
"def download_link(link, target_folder):\n",
" # 如果链接中包含冒号,分割前缀和链接\n",
" if ':' in link:\n",
" # 如果冒号前面是http或https开头,视为没有冒号,使用第二个aria2c下载命令\n",
" if link.startswith('http://') or link.startswith('https://'):\n",
" if link.startswith('https://huggingface.co/'):\n",
" filename_huggingface = re.search(r'[^/]+$', link).group(0)\n",
" print(f'下载文件: {link}')\n",
" return f'aria2c --console-log-level=error -c -x 16 -s 16 -k 1M -d \"{target_folder}\" -o \"{filename_huggingface}\" \"{link}\"'\n",
" else:\n",
" return f'aria2c --console-log-level=error -c -x 16 -s 16 -k 1M --remote-time -d \"{target_folder}\" \"{link}\"'\n",
" else:\n",
" filename_prefix, _, url = link.partition(':')\n",
" filename = filename_prefix.strip()\n",
" else:\n",
" # 如果链接中没有冒号,使用第二个aria2c下载命令\n",
" print(f'下载文件: {link}')\n",
" if link.startswith('https://huggingface.co/'):\n",
" filename_huggingface = re.search(r'[^/]+$', link).group(0)\n",
" return f'aria2c --console-log-level=error -c -x 16 -s 16 -k 1M -d \"{target_folder}\" -o \"{filename_huggingface}\" \"{link}\"'\n",
" else:\n",
" return f'aria2c --console-log-level=error -c -x 16 -s 16 -k 1M --remote-time -d \"{target_folder}\" \"{link}\"'\n",
"\n",
" # 检查链接是否以http://或https://开头,如果不是,添加http://协议\n",
" if not url.startswith('http://') and not url.startswith('https://'):\n",
" url = f'http://{url}'\n",
"\n",
" print(f'下载文件: {filename} ({url})')\n",
" return f'aria2c --console-log-level=error -c -x 16 -s 16 -k 1M --remote-time -d \"{target_folder}\" \"{url}\" -o \"{filename}\"'\n",
"\n",
"def download_links(links, target_folder):\n",
" tasks = []\n",
" for link in links:\n",
" task = download_link(link, target_folder)\n",
" tasks.append(task)\n",
" return tasks\n",
"\n",
"def download_links_all(tasks):\n",
" with ThreadPoolExecutor(max_workers=99) as executor:\n",
" for task in tasks:\n",
" executor.submit(os.system, task)\n",
"\n",
"# 下载模型文件\n",
"def download_model():\n",
" os.chdir('/kaggle')\n",
" os.makedirs('models', exist_ok=True)\n",
" os.chdir('models')\n",
" os.makedirs('VAE', exist_ok=True)\n",
" os.makedirs('Stable-diffusion', exist_ok=True)\n",
" os.makedirs('Lora', exist_ok=True)\n",
" os.makedirs('cn-model', exist_ok=True)\n",
" os.makedirs('hypernetworks', exist_ok=True)\n",
" os.makedirs('ESRGAN', exist_ok=True)\n",
" os.makedirs('lyco', exist_ok=True)\n",
" os.makedirs('animatediffmodel', exist_ok=True)\n",
" os.makedirs('animatedifflora', exist_ok=True)\n",
" tasks = []\n",
" tasks.extend(download_links(vae_model_urls, 'VAE'))\n",
" tasks.extend(download_links(sd_model_urls, 'Stable-diffusion'))\n",
" tasks.extend(download_links(lora_model_urls, 'Lora'))\n",
" if 是否启用ControlNet:\n",
" tasks.extend(download_links(cn_model_urls, 'cn-model'))\n",
" tasks.extend(download_links(hypernetworks_model_urls, 'hypernetworks'))\n",
" tasks.extend(download_links(ESRGAN_urls, 'ESRGAN'))\n",
" tasks.extend(download_links(lyco_model_urls, 'lyco'))\n",
" tasks.extend(download_links(animatediff_model_urls, 'animatediffmodel'))\n",
" tasks.extend(download_links(animatediff_lora_urls, 'animatedifflora'))\n",
" tasks.extend(download_links(embeddings_model_urls, f'{install_path}/stable-diffusion-webui/embeddings'))\n",
" tasks.extend(download_links(scripts_urls, f'{install_path}/stable-diffusion-webui/scripts'))\n",
" tasks.extend(download_links(tags_urls, f'{install_path}/stable-diffusion-webui/extensions/a1111-sd-webui-tagcomplete/tags'))\n",
" download_links_all(tasks)\n",
" #ZDY_Lora_Download()\n",
"\n",
"\n",
"def create_symlinks(folder_paths, target_dir):\n",
" print('链接模型中')\n",
" # Create target directory if it doesn't exist\n",
" if not os.path.exists(target_dir):\n",
" os.makedirs(target_dir)\n",
" # Remove broken symlinks in target directory\n",
" for filename in os.listdir(target_dir):\n",
" target_path = os.path.join(target_dir, filename)\n",
" if os.path.islink(target_path) and not os.path.exists(target_path):\n",
" os.unlink(target_path)\n",
" # Create new symlinks\n",
" for source_path in folder_paths:\n",
" if not os.path.exists(source_path):\n",
" continue\n",
" if os.path.isdir(source_path):\n",
" for filename in os.listdir(source_path):\n",
" source_file_path = os.path.join(source_path, filename)\n",
" target_file_path = os.path.join(target_dir, filename)\n",
" if not os.path.exists(target_file_path):\n",
" os.symlink(source_file_path, target_file_path)\n",
" print(f'Created symlink for {filename} in {target_dir}')\n",
" else:\n",
" filename = os.path.basename(source_path)\n",
" target_file_path = os.path.join(target_dir, filename)\n",
" if not os.path.exists(target_file_path):\n",
" os.symlink(source_path, target_file_path)\n",
" print(f'Created symlink for {filename} in {target_dir}')\n",
" print('链接成功')\n",
"\n",
"# 链接模型文件\n",
"def link_models():\n",
" cn_model.append('/kaggle/models/cn-model')\n",
" vae_model.append('/kaggle/models/VAE')\n",
" sd_model.append('/kaggle/models/Stable-diffusion')\n",
" lora_model.append('/kaggle/models/Lora')\n",
" hypernetworks_model.append('/kaggle/models/hypernetworks')\n",
" ESRGAN.append('/kaggle/models/ESRGAN')\n",
" lyco_model.append('/kaggle/models/lyco')\n",
" animatediff_model.append('/kaggle/models/animatediffmodel')\n",
" animatediff_lora.append('/kaggle/models/animatedifflora')\n",
" create_symlinks(vae_model,f'{install_path}/stable-diffusion-webui/models/VAE')\n",
" create_symlinks(sd_model,f'{install_path}/stable-diffusion-webui/models/Stable-diffusion')\n",
" create_symlinks(lora_model,f'{install_path}/stable-diffusion-webui/models/Lora')\n",
" create_symlinks(cn_model,f'{install_path}/stable-diffusion-webui/extensions/sd-webui-controlnet/models')\n",
" create_symlinks(embeddings_model,f'{install_path}/stable-diffusion-webui/embeddings')\n",
" create_symlinks(hypernetworks_model,f'{install_path}/stable-diffusion-webui/models/hypernetworks')\n",
" create_symlinks(ESRGAN,f'{install_path}/stable-diffusion-webui/models/ESRGAN')\n",
" create_symlinks(tags,f'{install_path}/stable-diffusion-webui/extensions/a1111-sd-webui-tagcomplete/tags')\n",
" create_symlinks(scripts,f'{install_path}/stable-diffusion-webui/scripts')\n",
" create_symlinks(lyco_model,f'{install_path}/stable-diffusion-webui/models/lyco')\n",
" create_symlinks(animatediff_model,f'{install_path}/stable-diffusion-webui/extensions/sd-webui-animatediff/model')\n",
" create_symlinks(animatediff_lora,f'{install_path}/stable-diffusion-webui/models/Lora')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "h6AV1L4xd_Ai"
},
"source": [
"----"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Wm8aVNuEd_Ai"
},
"source": [
"### > Ngrok,FRP内网穿透"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:23.376993Z",
"iopub.status.busy": "2024-04-16T04:55:23.376601Z",
"iopub.status.idle": "2024-04-16T04:55:23.388459Z",
"shell.execute_reply": "2024-04-16T04:55:23.387285Z",
"shell.execute_reply.started": "2024-04-16T04:55:23.376964Z"
},
"id": "A5Z72Qn0d_Ai"
},
"outputs": [],
"source": [
"# 功能函数:内网穿透\n",
"#ngrok\n",
"def ngrok_start(ngrokTokenFile: str, port: int, address_name: str, should_run: bool):\n",
" if not should_run:\n",
" print('Skipping ngrok start')\n",
" return\n",
" if Path(ngrokTokenFile).exists():\n",
" with open(ngrokTokenFile, encoding=\"utf-8\") as nkfile:\n",
" ngrokToken = nkfile.readline()\n",
" print('use nrgok')\n",
" from pyngrok import conf, ngrok\n",
" conf.get_default().auth_token = ngrokToken\n",
" conf.get_default().monitor_thread = False\n",
" ssh_tunnels = ngrok.get_tunnels(conf.get_default())\n",
" if len(ssh_tunnels) == 0:\n",
" ssh_tunnel = ngrok.connect(port, bind_tls=True)\n",
" print(f'{address_name}:' + ssh_tunnel.public_url)\n",
" else:\n",
" print(f'{address_name}:' + ssh_tunnels[0].public_url)\n",
" else:\n",
" print('skip start ngrok')\n",
"\n",
"#Frp内网穿透\n",
"import subprocess\n",
"\n",
"def install_Frpc(port, frpconfigfile, use_frpc):\n",
" if use_frpc:\n",
" subprocess.run(['chmod', '+x', '/kaggle/working/frpc/frpc'], check=True)\n",
" print(f'正在启动frp ,端口{port}')\n",
" subprocess.Popen(['/kaggle/working/frpc/frpc', '-c', frpconfigfile])\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Yw7Nl2MSd_Ai"
},
"source": [
"# > 自动压缩保存图片"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:23.391352Z",
"iopub.status.busy": "2024-04-16T04:55:23.390286Z",
"iopub.status.idle": "2024-04-16T04:55:23.413223Z",
"shell.execute_reply": "2024-04-16T04:55:23.412345Z",
"shell.execute_reply.started": "2024-04-16T04:55:23.391308Z"
},
"id": "xgrenT9Sd_Ai"
},
"outputs": [],
"source": [
"import os\n",
"import time\n",
"import zipfile\n",
"import random\n",
"directory = f'{install_path}/stable-diffusion-webui/outputs'\n",
"output_directory = '/kaggle/working/历史生成/'\n",
"output_path = '/kaggle/working/archive.zip'\n",
"class ImageCompressor:\n",
" def __init__(self, directory, output_path, save_time):\n",
" self.directory = directory\n",
" self.output_path = output_path\n",
" self.save_time = save_time\n",
" def _compress_single_image(self, zipf, filepath):\n",
" zipf.write(filepath, os.path.relpath(filepath, self.directory))\n",
" def compress_directory(self):\n",
" while True:\n",
" with zipfile.ZipFile(self.output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:\n",
" for root, _, files in os.walk(self.directory):\n",
" for file in files:\n",
" if file.endswith(('.jpg', '.jpeg', '.png', '.tmp')):\n",
" filepath = os.path.join(root, file)\n",
" self._compress_single_image(zipf, filepath)\n",
" print(f\"每隔{self.save_time}秒保存一次图片到archive.zip\")\n",
" time.sleep(self.save_time)\n",
" def run(self):\n",
" while True:\n",
" time.sleep(0.5)\n",
" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n",
" result = sock.connect_ex(('127.0.0.1', 7860))\n",
" if result == 0:\n",
" break\n",
" sock.close()\n",
" self.compress_directory()\n",
"def compress_images(directory, output_directory):\n",
" !mkdir /kaggle/working/历史生成/\n",
" initial_files = set()\n",
" for root, _, files in os.walk(directory):\n",
" for file in files:\n",
" if file.endswith(('.jpg', '.jpeg', '.png', '.tmp')):\n",
" filepath = os.path.join(root, file)\n",
" initial_files.add(filepath)\n",
" counter = 1\n",
" while True:\n",
" time.sleep(0.1)\n",
" current_files = set()\n",
" for root, _, files in os.walk(directory):\n",
" for file in files:\n",
" if file.endswith(('.jpg', '.jpeg', '.png', '.tmp')):\n",
" filepath = os.path.join(root, file)\n",
" current_files.add(filepath)\n",
" new_files = current_files - initial_files\n",
" if new_files:\n",
" temperatures = get_gpu_temperature()\n",
" for i, temp in enumerate(temperatures):\n",
" print(f\"当前GPU Nvidia Tesla T4 {i+1} 温度: {temp}°C(温度越高,生成速度会稍微下降0.2%)\")\n",
" #output_filename = str(counter).zfill(8) + '.zip'\n",
" #output_path = os.path.join(output_directory, output_filename)\n",
" #zipf = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED)\n",
" #for file in new_files:\n",
" # zipf.write(file, os.path.relpath(file, directory))\n",
" #zipf.close() # 递增计数器\n",
" #initial_files = current_files\n",
" #counter += 1\n",
"def extract_all_zips(directory):\n",
" for root, _, files in os.walk(directory):\n",
" for file in files:\n",
" if file.endswith('.zip'):\n",
" filepath = os.path.join(root, file)\n",
" with zipfile.ZipFile(filepath, 'r') as zip_ref:\n",
" zip_ref.extractall(root)\n",
" os.remove(filepath)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qUSZEZ7Nd_Ai"
},
"source": [
"--------------"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "AngrP6Qsd_Ai"
},
"source": [
"# > SD-webui启动函数"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:23.416234Z",
"iopub.status.busy": "2024-04-16T04:55:23.415346Z",
"iopub.status.idle": "2024-04-16T04:55:23.565930Z",
"shell.execute_reply": "2024-04-16T04:55:23.564492Z",
"shell.execute_reply.started": "2024-04-16T04:55:23.416194Z"
},
"id": "jEJZqMzcd_Ai",
"outputId": "4d073e7a-3981-4516-a3d4-39c29f10361f"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2024/04/16 04:55:23 [I] [027db9fe96c71f31] 连接节点成功, 运行 ID [027db9fe96c71f31]\n",
"\n",
"2024/04/16 04:55:23 [I] [027db9fe96c71f31] 隧道启动中: [sdwebuip60901, tcp -> 127.0.0.1:22]\n",
"\n",
"2024/04/16 04:55:23 [I] [027db9fe96c71f31] 隧道启动中: [sdwebuip60501, tcp -> 127.0.0.1:7860]\n",
"\n",
"2024/04/16 04:55:23 [I] [027db9fe96c71f31] 隧道启动中: [sdwebuip60601, tcp -> 127.0.0.1:7861]\n",
"\n",
"2024/04/16 04:55:23 [I] [027db9fe96c71f31] 隧道启动中: [sdwebuip60701, tcp -> 127.0.0.1:7862]\n",
"\n",
"2024/04/16 04:55:23 [I] [027db9fe96c71f31] 隧道启动中: [sdwebuip60801, tcp -> 127.0.0.1:7863]\n"
]
}
],
"source": [
"def iframe_thread_1(port):\n",
" while True:\n",
" time.sleep(0.5)\n",
" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n",
" result = sock.connect_ex(('127.0.0.1', port))\n",
" if result == 0:\n",
" break\n",
" sock.close()\n",
" p = subprocess.Popen([\"lt\", \"--port\", \"{}\".format(port)], stdout=subprocess.PIPE)\n",
" for line in p.stdout:\n",
" print(line.decode(), end='')\n",
" result = subprocess.run(['curl', 'ipv4.icanhazip.com'], capture_output=True, text=True)\n",
" print('部署WebUI成功!你的公网IP地址是', result.stdout.strip())\n",
" print('如果该链接卡顿,可换Ngrok内网穿透')\n",
" print('记得给作者打赏哦')\n",
"\n",
"def start_webui_1():\n",
" if use2:\n",
" install_Frpc('7861',frpconfigfile1,use_frpc1)\n",
" #ngrok_start(ngrokTokenFile1,7861,'第二个webui',ngrok_use1)\n",
" !sleep 50\n",
" #threading.Thread(target=iframe_thread_1, daemon=True, args=(7861,)).start()\n",
" %cd $install_path/stable-diffusion-webui\n",
" args1.append(f'--ckpt=models/Stable-diffusion/{usedCkpt1}')\n",
" if os.path.exists(Venvpath):\n",
" !/kaggle/opt/conda/envs/venv/bin/python3 launch.py {' '.join(args1)} --port 7861 --device-id=1 --ckpt-dir=/kaggle/models/Stable-diffusion & /kaggle/opt/conda/envs/venv/bin/python3 launch.py {' '.join(args1)} --port=7862 & /kaggle/opt/conda/envs/venv/bin/python3 launch.py {' '.join(args1)} --port 7863 --device-id=1\n",
" #!/kaggle/opt/conda/envs/venv/bin/python3 launch.py {' '.join(args1)} --port 7861 --device-id=1 & /kaggle/opt/conda/envs/venv/bin/python3 launch.py {' '.join(args)} --port=7862 & /kaggle/opt/conda/envs/venv/bin/python3 launch.py {' '.join(args1)} --port 7863 --device-id=1\n",
" else:\n",
" !sleep 12\n",
" print(\"\\033[92m 您选择不使用第二张显卡运行,函数start_webui_1跳过 \\033[0m\")\n",
" pass\n",
"\n",
"def start_webui_0():\n",
" print('\\033[92m 正在以第一张显卡启动SD-webui \\033[0m')\n",
" if environment == 2:\n",
" !/kaggle/opt/conda/envs/venv/bin/python3 -m pip install xformers==0.0.23\n",
" if use_frpc:\n",
" !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/datasets/ACCA225/Frp/resolve/main/frpc -d /kaggle/working/frpc -o frpc\n",
" #threading.Thread(target=iframe_thread, daemon=True, args=(7860,)).start()\n",
" %cd $install_path\n",
" install_Frpc('7860',frpconfigfile,use_frpc)\n",
" #ngrok_start(ngrokTokenFile,7860,'第一个webui',ngrok_use)\n",
" %cd $install_path/stable-diffusion-webui\n",
" !mkdir models/lyco\n",
" args.append(f'--ckpt=models/Stable-diffusion/{usedCkpt}')\n",
" if os.path.exists(Venvpath):\n",
" if os.path.exists(\"/kaggle/opt/conda/envs/venv/bin/python3\"):\n",
" !/kaggle/opt/conda/envs/venv/bin/python3 launch.py {' '.join(args)}\n",
" else:\n",
" print(\"由于你自身迷惑操作导致发生未知错误,正在重试\")\n",
" fix_attempt()\n",
" !/kaggle/opt/conda/envs/venv/bin/python3 launch.py\n",
" else:\n",
" !screen -dmS sd7860 /opt/conda/envs/venv/bin/python3 launch.py {' '.join(args)}\n",
"\n",
"def iframe_thread(port):\n",
" while True:\n",
" time.sleep(0.5)\n",
" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n",
" result = sock.connect_ex(('127.0.0.1', port))\n",
" if result == 0:\n",
" break\n",
" sock.close()\n",
" p = subprocess.Popen([\"lt\", \"--port\", \"{}\".format(port)], stdout=subprocess.PIPE)\n",
" for line in p.stdout:\n",
" print(line.decode(), end='')\n",
" result = subprocess.run(['curl', 'ipv4.icanhazip.com'], capture_output=True, text=True)\n",
" print('部署WebUI成功!你的公网IP地址是', result.stdout.strip())\n",
" print('请从对应7860或者7861端口的内网穿透链接进入SD')\n",
"\n",
"def nv():\n",
" !/kaggle/opt/conda/envs/venv/bin/python3 -m \"pip\" install nvidia-ml-py3 > /dev/null 2>&1\n",
"def start_webui():\n",
" if use2:\n",
" print('正在以双卡模式启动WebUI')\n",
" else:\n",
" print('正在以单卡模式启动WebUI,如需使用双卡跑图,请将use2设置为True')\n",
"\n",
" with ProcessPoolExecutor() as executor:\n",
" futures = []\n",
" for func in [nv, start_webui_0, start_webui_1]:\n",
" futures.append(executor.submit(func))\n",
" time.sleep(1)\n",
" for future in futures:\n",
" future.result()\n",
"\n",
"def prepare():\n",
" if localtunnel:\n",
" !apt-get update & npm install -g localtunnel\n",
" else:\n",
" os.system('apt-get update')\n",
" os.system('apt -y install -qq aria2 > /dev/null 2>&1')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:23.567686Z",
"iopub.status.busy": "2024-04-16T04:55:23.567295Z",
"iopub.status.idle": "2024-04-16T04:55:28.219834Z",
"shell.execute_reply": "2024-04-16T04:55:28.218732Z",
"shell.execute_reply.started": "2024-04-16T04:55:23.567655Z"
},
"id": "rpr-n1kMd_Aj",
"outputId": "eef40e82-f206-4433-9246-d9672446b50d"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2024/04/16 04:55:23 [W] [027db9fe96c71f31] [sdwebuip60901] 隧道启动失败: proxy [sdwebuip60901] already exists\n",
"\n",
"2024/04/16 04:55:23 [W] [027db9fe96c71f31] [sdwebuip60501] 隧道启动失败: proxy [sdwebuip60501] already exists\n",
"\n",
"2024/04/16 04:55:23 [W] [027db9fe96c71f31] [sdwebuip60601] 隧道启动失败: proxy [sdwebuip60601] already exists\n",
"\n",
"2024/04/16 04:55:23 [W] [027db9fe96c71f31] [sdwebuip60701] 隧道启动失败: proxy [sdwebuip60701] already exists\n",
"\n",
"2024/04/16 04:55:23 [W] [027db9fe96c71f31] [sdwebuip60801] 隧道启动失败: proxy [sdwebuip60801] already exists\n",
"\n",
"Hit:1 https://packages.cloud.google.com/apt gcsfuse-focal InRelease\n",
"\n",
"Hit:2 https://packages.cloud.google.com/apt cloud-sdk InRelease\n",
"\n",
"Hit:3 http://archive.ubuntu.com/ubuntu focal InRelease\n",
"\n",
"Hit:4 http://security.ubuntu.com/ubuntu focal-security InRelease\n",
"\n",
"Hit:5 http://archive.ubuntu.com/ubuntu focal-updates InRelease\n",
"\n",
"Hit:6 http://archive.ubuntu.com/ubuntu focal-backports InRelease\n",
"\n",
"Reading package lists...\n"
]
}
],
"source": [
"prepare()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"ExecutionIndicator": {
"show": false
},
"execution": {
"iopub.execute_input": "2024-04-16T04:55:28.221518Z",
"iopub.status.busy": "2024-04-16T04:55:28.221147Z",
"iopub.status.idle": "2024-04-16T04:55:28.231792Z",
"shell.execute_reply": "2024-04-16T04:55:28.230557Z",
"shell.execute_reply.started": "2024-04-16T04:55:28.221490Z"
},
"id": "6r4ms8Otd_Aj",
"tags": []
},
"outputs": [],
"source": [
"import multiprocessing\n",
"# 将会同步的文件\n",
"yun_files = [\n",
"'ui-config.json',\n",
"'config.json',\n",
"'styles.csv'\n",
"]\n",
"def warn():\n",
" print(\"正在启动SD脚本,由于kaggle服务器没有对外暴露7860端口,请记得先配置内网穿透再进入SD!!\")\n",
" print(\"正在启动SD脚本,由于kaggle服务器没有对外暴露7860端口,请记得先配置内网穿透再进入SD!!\")\n",
" print(\"\\033[92m正在启动SD脚本,由于kaggle服务器没有对外暴露7860端口,请记得先配置内网穿透再进入SD!!重要的事情说三遍\\033[0m\")\n",
"def main():\n",
" startTicks = time.time()\n",
" #ngrokdetect()\n",
" def func1():\n",
" warn()\n",
" def func2():\n",
" #prepare()\n",
" pass\n",
" process1 = multiprocessing.Process(target=func1)\n",
" process2 = multiprocessing.Process(target=func2)\n",
" process1.start()\n",
" process2.start()\n",
" with ProcessPoolExecutor() as executor:\n",
" futures = []\n",
" for func in [install_webui, venv_install]:\n",
" futures.append(executor.submit(func))\n",
" time.sleep(0.5)\n",
" try:\n",
" for future in futures:\n",
" future.result()\n",
" except Exception as e:\n",
" print(\"运行出错了。\")\n",
" except CancelledError:\n",
" print(\"运行被用户中止\")\n",
" #libtcmalloc()\n",
" downloadsize()\n",
" ticks = time.time()\n",
" print(\"加载耗时:\", (ticks - startTicks), \"s\")\n",
" if '--share' in args:\n",
" print('您正在使用Gradio内网穿透,这可能会导致会话被强制终止')\n",
" try:\n",
" start_webui()\n",
" except Exception as e:\n",
" print(f\"由于你自身的迷惑操作导致发生未知错误,错误信息:{e}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "GTancIxTd_Aj"
},
"source": [
"-------------"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "j2BS0vh_d_Aj"
},
"source": [
"# > 打包图片上传到HuggingFace (可选)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2024-04-16T04:55:28.234512Z",
"iopub.status.busy": "2024-04-16T04:55:28.234036Z",
"iopub.status.idle": "2024-04-16T04:55:28.961715Z",
"shell.execute_reply": "2024-04-16T04:55:28.960909Z",
"shell.execute_reply.started": "2024-04-16T04:55:28.234473Z"
},
"id": "O6s-8B-Ed_Aj"
},
"outputs": [],
"source": [
"#功能函数,清理打包上传\n",
"from pathlib import Path\n",
"from huggingface_hub import HfApi, login\n",
"\n",
"def zip_venv():\n",
" !pip install conda-pack\n",
" !rm -rf /kaggle/working/venv.tar.gz\n",
" !conda pack -n venv -o /kaggle/working/venv.tar.gz --compress-level 0\n",
"\n",
"def hugface_upload(huggingface_token_file, yun_files, repo_id):\n",
" if Path(huggingface_token_file).exists():\n",
" with open(huggingface_token_file, encoding=\"utf-8\") as nkfile:\n",
" hugToken = nkfile.readline()\n",
" if hugToken != '':\n",
" # 使用您的 Hugging Face 访问令牌登录\n",
" login(token=hugToken)\n",
" # 实例化 HfApi 类\n",
" api = HfApi()\n",
" print(\"HfApi 类已实例化\")\n",
" %cd $install_path/stable-diffusion-webui\n",
" # 使用 upload_file() 函数上传文件\n",
" print(\"开始上传文件...\")\n",
" for yun_file in yun_files:\n",
" if Path(yun_file).exists():\n",
" response = api.upload_file(\n",
" path_or_fileobj=yun_file,\n",
" path_in_repo=yun_file,\n",
" repo_id=repo_id,\n",
" repo_type=\"dataset\"\n",
" )\n",
" print(\"文件上传完成\")\n",
" print(f\"响应: {response}\")\n",
" else:\n",
" print(f'Error: File {yun_file} does not exist')\n",
" else:\n",
" print(f'Error: File {huggingface_token_file} does not exist')\n",
"\n",
"def clean_folder(folder_path):\n",
" if not os.path.exists(folder_path):\n",
" return\n",
" for filename in os.listdir(folder_path):\n",
" file_path = os.path.join(folder_path, filename)\n",
" if os.path.isfile(file_path):\n",
" os.remove(file_path)\n",
" elif os.path.isdir(file_path):\n",
" shutil.rmtree(file_path)\n",
"\n",
"def zip_clear_updata():\n",
" if zip_output:\n",
" output_folder = '/kaggle/working/'\n",
" if os.path.exists(output_folder):\n",
" shutil.make_archive('/kaggle/working/图片', 'zip', output_folder)\n",
" print('图片已压缩到output')\n",
" else:\n",
" print(f'文件夹 {output_folder} 不存在,跳过压缩操作')\n",
" if clear_output:\n",
" %cd /kaggle/outputs/\n",
" clean_folder('img2img-images')\n",
" clean_folder('txt2img-images')\n",
" clean_folder('img2img-grids')\n",
" clean_folder('txt2img-grids')\n",
" clean_folder('extras-images')\n",
" print('清理完毕')\n",
" if huggingface_use == True:\n",
" hugface_upload(huggingface_token_file,yun_files,huggiingface_repo_id)\n",
" if use_zip_venv == True:\n",
" zip_venv()\n",
"\n",
"try:\n",
" code()\n",
"except Exception as e:\n",
" print('运行失败,请检查Internet是否开启')\n",
"with open('/kaggle/temp/Token.txt', 'r') as file:\n",
" file_contents = file.read()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QZKBb92Ud_An"
},
"source": [
"# > 执行区域,输出结果在此处看,从内网穿透链接进入Stable Diffusion绘画界面"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "F0YMXCfqd_Ao"
},
"source": [
"# > 如果报错了,请反馈给群主"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"_kg_hide-input": true,
"_kg_hide-output": false,
"execution": {
"iopub.execute_input": "2024-04-16T04:55:28.963094Z",
"iopub.status.busy": "2024-04-16T04:55:28.962701Z"
},
"id": "9uIYNzO_d_Ao",
"outputId": "04564b1f-a0c4-4cef-8f2a-d607b61d60db"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"正在启动SD脚本,由于kaggle服务器没有对外暴露7860端口,请记得先配置内网穿透再进入SD!!\n",
"\n",
"正在启动SD脚本,由于kaggle服务器没有对外暴露7860端口,请记得先配置内网穿透再进入SD!!\n",
"\n",
"\u001b[92m正在启动SD脚本,由于kaggle服务器没有对外暴露7860端口,请记得先配置内网穿透再进入SD!!重要的事情说三遍\u001b[0m\n",
"\n",
"/kaggle/working\n",
"\n",
"环境安装包可能存在错误,请联系管理员解决\n",
"\n",
"/opt/conda/envs\n",
"\n",
"/kaggle/working\n",
"\n",
"下载 venv\n",
"\n",
"环境已经过时,请从正确发布地址运行!有问题加群632428790\n",
"\n",
"/kaggle/working/stable-diffusion-webui\n",
"\n",
"/kaggle/working/stable-diffusion-webui\n"
]
}
],
"source": [
"import concurrent.futures\n",
"'''\n",
"执行函数\n",
"'''\n",
"if __name__ == \"__main__\":\n",
" compressor = ImageCompressor(directory=directory, output_path=output_path, save_time=200) #save_time为图片自动保存间隔,默认60秒压缩保存一次图片\n",
" executor = concurrent.futures.ThreadPoolExecutor(max_workers=4)\n",
" future1 = executor.submit(main)\n",
" future2 = executor.submit(compressor.run)\n",
" concurrent.futures.wait([future1, future2])\n",
" executor.shutdown()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Ee6WuxrNd_Ao"
},
"outputs": [],
"source": [
"%cd stable-diffusion-webui\n",
"!/kaggle/opt/conda/envs/venv/bin/python3 launch.py --xformers --administrator --ngrok=2LpUQuhU9NX1nt0XdzCWAoKDMZG_73C2wx9MCdwCVcrn65aCD"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Zp1xlnA9d_Ao"
},
"outputs": [],
"source": [
"# 这个代码是用来打包SadTalker生成的视频的,保存至SadTalker.zip里\n",
"!zip -r /kaggle/working/SadTalker.zip /kaggle/working/stable-diffusion-webui/results/*"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "d4P_ikwmd_Ao"
},
"outputs": [],
"source": [
"#测试用\n",
"!cp -r /kaggle/opt/conda/envs/venv /kaggle/working\n",
"\n",
"!/kaggle/opt/conda/envs/venv/bin/python3 -m \"pip\" install insightface\n",
"\n",
"%cd /kaggle/working/opt/conda/envs\n",
"\n",
"!find . ! -name 'venv_2024.2.18.tar.bak' -exec rm -rf {} +\n",
"\n",
"%cd /kaggle/working\n",
"\n",
"!tar -cvf /kaggle/working/venv_2024.2.18.tar.bak ./venv"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "mknj6i_qd_Ao"
},
"source": [
"-----------------"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4D4028Q0d_Ao"
},
"source": [
"---------------"
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"kaggle": {
"accelerator": "none",
"dataSources": [
{
"datasetId": 2908961,
"sourceId": 7991141,
"sourceType": "datasetVersion"
}
],
"dockerImageVersionId": 30732,
"isGpuEnabled": false,
"isInternetEnabled": true,
"language": "python",
"sourceType": "notebook"
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 4
}