stlaurentjr commited on
Commit
f95b529
1 Parent(s): 74fa2fe

Upload 2 files

Browse files
notebooks/RNPD-A1111.ipynb ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "9e42bc1e-9825-4587-b533-c74607b1a377",
6
+ "metadata": {},
7
+ "source": [
8
+ "## A1111 Runpod Notebook From https://github.com/TheLastBen/fast-stable-diffusion, if you encounter any issues, feel free to discuss them."
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "markdown",
13
+ "id": "813d4d10-e6d1-42b1-ae37-ae41ad47e595",
14
+ "metadata": {},
15
+ "source": [
16
+ "# Dependencies"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "execution_count": null,
22
+ "id": "bfd51417-bba8-41fb-ae56-c6555e2a0465",
23
+ "metadata": {
24
+ "tags": []
25
+ },
26
+ "outputs": [],
27
+ "source": [
28
+ "# Install the dependencies\n",
29
+ "\n",
30
+ "force_reinstall= False\n",
31
+ "\n",
32
+ "# Set to true only if you want to install the dependencies again.\n",
33
+ "\n",
34
+ "#--------------------\n",
35
+ "with open('/dev/null', 'w') as devnull:import requests, os, time, importlib;open('/workspace/mainrunpodA1111.py', 'wb').write(requests.get('https://huggingface.co/datasets/TheLastBen/RNPD/raw/main/Scripts/mainrunpodA1111.py').content);os.chdir('/workspace');time.sleep(2);import mainrunpodA1111;importlib.reload(mainrunpodA1111);from mainrunpodA1111 import *;Deps(force_reinstall)"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "markdown",
40
+ "id": "76ae705b-15e3-47b9-b226-52e71ef1737d",
41
+ "metadata": {},
42
+ "source": [
43
+ "# Install/Update AUTOMATIC1111 repo"
44
+ ]
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "execution_count": null,
49
+ "id": "652afdee-64a4-483b-926a-094c884dd260",
50
+ "metadata": {
51
+ "tags": []
52
+ },
53
+ "outputs": [],
54
+ "source": [
55
+ "Huggingface_token_optional=\"\"\n",
56
+ "\n",
57
+ "# Restore your backed-up SD folder by entering your huggingface token, leave it empty to start fresh or continue with the existing sd folder (if any).\n",
58
+ "\n",
59
+ "#--------------------\n",
60
+ "repo(Huggingface_token_optional)"
61
+ ]
62
+ },
63
+ {
64
+ "cell_type": "markdown",
65
+ "id": "ca3a26bb-8625-42b9-9e2f-e55939a536ef",
66
+ "metadata": {},
67
+ "source": [
68
+ "# Model Download/Load"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "execution_count": null,
74
+ "id": "1e5dbca1-5ee2-41db-be94-9d2919dc3aef",
75
+ "metadata": {
76
+ "tags": []
77
+ },
78
+ "outputs": [],
79
+ "source": [
80
+ "Original_Model_Version = \"SDXL\"\n",
81
+ "\n",
82
+ "# Choices are \"SDXL\", \"v1.5\", \"v2-512\", \"v2-768\"\n",
83
+ "\n",
84
+ "#-------------- Or\n",
85
+ "\n",
86
+ "Path_to_MODEL = \"\"\n",
87
+ "\n",
88
+ "# Insert the full path of your trained model or to a folder containing multiple models.\n",
89
+ "\n",
90
+ "\n",
91
+ "MODEL_LINK = \"\"\n",
92
+ "\n",
93
+ "# A direct link to a Model or a shared gdrive link.\n",
94
+ "\n",
95
+ "\n",
96
+ "#--------------------\n",
97
+ "model=mdl(Original_Model_Version, Path_to_MODEL, MODEL_LINK)"
98
+ ]
99
+ },
100
+ {
101
+ "cell_type": "markdown",
102
+ "id": "9c578da4-3164-411c-9255-226ce8157545",
103
+ "metadata": {},
104
+ "source": [
105
+ "# LoRA Download"
106
+ ]
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "execution_count": null,
111
+ "id": "a0f3dfba-4127-4619-8bb1-4589e84a5fe4",
112
+ "metadata": {
113
+ "tags": []
114
+ },
115
+ "outputs": [],
116
+ "source": [
117
+ "LoRA_LINK = \"\"\n",
118
+ "\n",
119
+ "# Downlad the LoRA model directly to A1111 LoRA folder\n",
120
+ "\n",
121
+ "#--------------------\n",
122
+ "loradwn(LoRA_LINK)"
123
+ ]
124
+ },
125
+ {
126
+ "cell_type": "markdown",
127
+ "id": "02706779-fec8-4661-8589-0e28f0d4fb3b",
128
+ "metadata": {},
129
+ "source": [
130
+ "# ControlNet"
131
+ ]
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "execution_count": null,
136
+ "id": "222cdfd7-38f1-422b-81a2-963a2a8d504b",
137
+ "metadata": {
138
+ "tags": []
139
+ },
140
+ "outputs": [],
141
+ "source": [
142
+ "# Download/update ControlNet extension and its models.\n",
143
+ "\n",
144
+ "ControlNet_v1_Model = \"none\"\n",
145
+ "\n",
146
+ "# Choices are : none; all; 1: Canny; 2: Depth; 3: Lineart; 4: MLSD; 5: Normal; 6: OpenPose; 7: Scribble; 8: Seg; 9: ip2p; 10:Shuffle; 11: Inpaint; 12: Softedge; 13: Lineart_Anime; 14: Tile; 15: T2iadapter_Models\n",
147
+ "\n",
148
+ "ControlNet_XL_Model = \"none\"\n",
149
+ "\n",
150
+ "# Choices are : none; all; 1: Canny; 2: Depth; 3: Sketch; 4: OpenPose; 5: Recolor\n",
151
+ "\n",
152
+ "#--------------------\n",
153
+ "CNet(ControlNet_v1_Model, ControlNet_XL_Model)"
154
+ "CNet(\"1\", ControlNet_XL_Model)"
155
+ "CNet(\"2\", ControlNet_XL_Model)"
156
+ "CNet(\"3\", ControlNet_XL_Model)"
157
+ "CNet(\"6\", ControlNet_XL_Model)"
158
+ "CNet(\"11\", ControlNet_XL_Model)"
159
+ "CNet(\"15\", ControlNet_XL_Model)"
160
+ ]
161
+ },
162
+ {
163
+ "cell_type": "markdown",
164
+ "id": "48184b7b-9cd0-4f04-9c85-4464031d6596",
165
+ "metadata": {
166
+ "tags": []
167
+ },
168
+ "source": [
169
+ "# Start Stable-Diffusion"
170
+ ]
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "execution_count": null,
175
+ "id": "e73f76a6-01a4-44d0-87a7-77fed9c9b77c",
176
+ "metadata": {
177
+ "tags": []
178
+ },
179
+ "outputs": [],
180
+ "source": [
181
+ "User = \"\"\n",
182
+ "\n",
183
+ "Password= \"\"\n",
184
+ "\n",
185
+ "# Add credentials to your Gradio interface (optional).\n",
186
+ "\n",
187
+ "#-----------------\n",
188
+ "configf=sd(User, Password, model) if 'model' in locals() else sd(User, Password, \"\");import gradio;gradio.close_all()\n",
189
+ "!python /workspace/sd/stable-diffusion-webui/webui.py $configf"
190
+ ]
191
+ },
192
+ {
193
+ "cell_type": "markdown",
194
+ "id": "5ac65e18-810c-4825-a507-d96beec805df",
195
+ "metadata": {},
196
+ "source": [
197
+ "# Backup SD folder"
198
+ ]
199
+ },
200
+ {
201
+ "cell_type": "code",
202
+ "execution_count": null,
203
+ "id": "332a8b52-29b4-494a-bf12-817feb87b745",
204
+ "metadata": {
205
+ "tags": []
206
+ },
207
+ "outputs": [],
208
+ "source": [
209
+ "# This will backup your sd folder -without the models- to your huggingface account, so you can restore it whenever you start an instance.\n",
210
+ "\n",
211
+ "Huggingface_Write_token=\"\"\n",
212
+ "\n",
213
+ "# Must be a WRITE token, get yours here : https://huggingface.co/settings/tokens\n",
214
+ "\n",
215
+ "#--------------------\n",
216
+ "save(Huggingface_Write_token)"
217
+ ]
218
+ }
219
+ ],
220
+ "metadata": {
221
+ "kernelspec": {
222
+ "display_name": "Python 3 (ipykernel)",
223
+ "language": "python",
224
+ "name": "python3"
225
+ },
226
+ "language_info": {
227
+ "codemirror_mode": {
228
+ "name": "ipython",
229
+ "version": 3
230
+ },
231
+ "file_extension": ".py",
232
+ "mimetype": "text/x-python",
233
+ "name": "python",
234
+ "nbconvert_exporter": "python",
235
+ "pygments_lexer": "ipython3",
236
+ "version": "3.10.6"
237
+ }
238
+ },
239
+ "nbformat": 4,
240
+ "nbformat_minor": 5
241
+ }
scripts/mainrunpodA1111.py ADDED
@@ -0,0 +1,536 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from IPython.display import clear_output
3
+ from subprocess import call, getoutput, Popen, run
4
+ import time
5
+ import ipywidgets as widgets
6
+ import requests
7
+ import sys
8
+ import fileinput
9
+ from torch.hub import download_url_to_file
10
+ from urllib.parse import urlparse, parse_qs, unquote
11
+ import re
12
+ import six
13
+
14
+ from urllib.request import urlopen, Request
15
+ import tempfile
16
+ from tqdm import tqdm
17
+
18
+
19
+
20
+
21
+ def Deps(force_reinstall):
22
+
23
+ if not force_reinstall and os.path.exists('/usr/local/lib/python3.10/dist-packages/safetensors'):
24
+ ntbks()
25
+ print('Modules and notebooks updated, dependencies already installed')
26
+ os.environ['TORCH_HOME'] = '/workspace/cache/torch'
27
+ os.environ['PYTHONWARNINGS'] = 'ignore'
28
+ else:
29
+ call('pip install --root-user-action=ignore --disable-pip-version-check --no-deps -qq gdown PyWavelets numpy==1.23.5 accelerate==0.12.0 --force-reinstall', shell=True, stdout=open('/dev/null', 'w'))
30
+ ntbks()
31
+ if os.path.exists('deps'):
32
+ call("rm -r deps", shell=True)
33
+ if os.path.exists('diffusers'):
34
+ call("rm -r diffusers", shell=True)
35
+ call('mkdir deps', shell=True)
36
+ if not os.path.exists('cache'):
37
+ call('mkdir cache', shell=True)
38
+ os.chdir('deps')
39
+ dwn("https://huggingface.co/TheLastBen/dependencies/resolve/main/rnpddeps-t2.tar.zst", "/workspace/deps/rnpddeps-t2.tar.zst", "Installing dependencies")
40
+ call('tar -C / --zstd -xf rnpddeps-t2.tar.zst', shell=True, stdout=open('/dev/null', 'w'))
41
+ call("sed -i 's@~/.cache@/workspace/cache@' /usr/local/lib/python3.10/dist-packages/transformers/utils/hub.py", shell=True)
42
+ os.chdir('/workspace')
43
+ call("git clone --depth 1 -q --branch main https://github.com/TheLastBen/diffusers", shell=True, stdout=open('/dev/null', 'w'))
44
+ call('pip install --root-user-action=ignore --disable-pip-version-check -qq gradio==3.41.2', shell=True, stdout=open('/dev/null', 'w'))
45
+ call("rm -r deps", shell=True)
46
+ os.chdir('/workspace')
47
+ os.environ['TORCH_HOME'] = '/workspace/cache/torch'
48
+ os.environ['PYTHONWARNINGS'] = 'ignore'
49
+ call("sed -i 's@text = _formatwarnmsg(msg)@text =\"\"@g' /usr/lib/python3.10/warnings.py", shell=True)
50
+ clear_output()
51
+
52
+ done()
53
+
54
+
55
+ def dwn(url, dst, msg):
56
+ file_size = None
57
+ req = Request(url, headers={"User-Agent": "torch.hub"})
58
+ u = urlopen(req)
59
+ meta = u.info()
60
+ if hasattr(meta, 'getheaders'):
61
+ content_length = meta.getheaders("Content-Length")
62
+ else:
63
+ content_length = meta.get_all("Content-Length")
64
+ if content_length is not None and len(content_length) > 0:
65
+ file_size = int(content_length[0])
66
+
67
+ with tqdm(total=file_size, disable=False, mininterval=0.5,
68
+ bar_format=msg+' |{bar:20}| {percentage:3.0f}%') as pbar:
69
+ with open(dst, "wb") as f:
70
+ while True:
71
+ buffer = u.read(8192)
72
+ if len(buffer) == 0:
73
+ break
74
+ f.write(buffer)
75
+ pbar.update(len(buffer))
76
+ f.close()
77
+
78
+
79
+ def ntbks():
80
+
81
+ os.chdir('/workspace')
82
+ if not os.path.exists('Latest_Notebooks'):
83
+ call('mkdir Latest_Notebooks', shell=True)
84
+ else:
85
+ call('rm -r Latest_Notebooks', shell=True)
86
+ call('mkdir Latest_Notebooks', shell=True)
87
+ os.chdir('/workspace/Latest_Notebooks')
88
+ call('wget -q -i https://huggingface.co/datasets/TheLastBen/RNPD/raw/main/Notebooks.txt', shell=True)
89
+ call('rm Notebooks.txt', shell=True)
90
+ os.chdir('/workspace')
91
+
92
+
93
+ def repo(Huggingface_token_optional):
94
+
95
+ from slugify import slugify
96
+ from huggingface_hub import HfApi, CommitOperationAdd, create_repo
97
+
98
+ os.chdir('/workspace')
99
+ if Huggingface_token_optional!="":
100
+ username = HfApi().whoami(Huggingface_token_optional)["name"]
101
+ backup=f"https://huggingface.co/datasets/{username}/fast-stable-diffusion/resolve/main/sd_backup_rnpd.tar.zst"
102
+ headers = {"Authorization": f"Bearer {Huggingface_token_optional}"}
103
+ response = requests.head(backup, headers=headers)
104
+ if response.status_code == 302:
105
+ print('Restoring the SD folder...')
106
+ open('/workspace/sd_backup_rnpd.tar.zst', 'wb').write(requests.get(backup, headers=headers).content)
107
+ call('tar --zstd -xf sd_backup_rnpd.tar.zst', shell=True)
108
+ call('rm sd_backup_rnpd.tar.zst', shell=True)
109
+ else:
110
+ print('Backup not found, using a fresh/existing repo...')
111
+ time.sleep(2)
112
+ if not os.path.exists('/workspace/sd/stablediffusiond'): #reset later
113
+ call('wget -q -O sd_mrep.tar.zst https://huggingface.co/TheLastBen/dependencies/resolve/main/sd_mrep.tar.zst', shell=True)
114
+ call('tar --zstd -xf sd_mrep.tar.zst', shell=True)
115
+ call('rm sd_mrep.tar.zst', shell=True)
116
+ os.chdir('/workspace/sd')
117
+ if not os.path.exists('stable-diffusion-webui'):
118
+ call('git clone -q --depth 1 --branch master https://github.com/AUTOMATIC1111/stable-diffusion-webui', shell=True)
119
+
120
+ else:
121
+ print('Installing/Updating the repo...')
122
+ os.chdir('/workspace')
123
+ if not os.path.exists('/workspace/sd/stablediffusiond'): #reset later
124
+ call('wget -q -O sd_mrep.tar.zst https://huggingface.co/TheLastBen/dependencies/resolve/main/sd_mrep.tar.zst', shell=True)
125
+ call('tar --zstd -xf sd_mrep.tar.zst', shell=True)
126
+ call('rm sd_mrep.tar.zst', shell=True)
127
+
128
+ os.chdir('/workspace/sd')
129
+ if not os.path.exists('stable-diffusion-webui'):
130
+ call('git clone -q --depth 1 --branch master https://github.com/AUTOMATIC1111/stable-diffusion-webui', shell=True)
131
+
132
+
133
+ os.chdir('/workspace/sd/stable-diffusion-webui/')
134
+ call('git reset --hard', shell=True)
135
+ print('')
136
+ call('git pull', shell=True)
137
+ os.chdir('/workspace')
138
+ clear_output()
139
+ done()
140
+
141
+
142
+
143
+ def mdl(Original_Model_Version, Path_to_MODEL, MODEL_LINK):
144
+
145
+ import gdown
146
+
147
+ src=getsrc(MODEL_LINK)
148
+
149
+ if not os.path.exists('/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv1-5.ckpt'):
150
+ call('ln -s /workspace/auto-models/* /workspace/sd/stable-diffusion-webui/models/Stable-diffusion', shell=True)
151
+
152
+ if Path_to_MODEL !='':
153
+ if os.path.exists(str(Path_to_MODEL)):
154
+ print('Using the custom model')
155
+ model=Path_to_MODEL
156
+ else:
157
+ print('Wrong path, check that the path to the model is correct')
158
+
159
+ elif MODEL_LINK !="":
160
+
161
+ if src=='civitai':
162
+ modelname=get_name(MODEL_LINK, False)
163
+ model=f'/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
164
+ if not os.path.exists(model):
165
+ dwn(MODEL_LINK, model, 'Downloading the custom model')
166
+ clear_output()
167
+ else:
168
+ print('Model already exists')
169
+ elif src=='gdrive':
170
+ modelname=get_name(MODEL_LINK, True)
171
+ model=f'/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
172
+ if not os.path.exists(model):
173
+ gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
174
+ clear_output()
175
+ else:
176
+ print('Model already exists')
177
+ else:
178
+ modelname=os.path.basename(MODEL_LINK)
179
+ model=f'/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
180
+ if not os.path.exists(model):
181
+ gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
182
+ clear_output()
183
+ else:
184
+ print('Model already exists')
185
+
186
+ if os.path.exists(model) and os.path.getsize(model) > 1810671599:
187
+ print('Model downloaded, using the custom model.')
188
+ else:
189
+ call('rm '+model, shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
190
+ print('Wrong link, check that the link is valid')
191
+
192
+ else:
193
+ if Original_Model_Version == "v1.5":
194
+ model="/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv1-5.ckpt"
195
+ print('Using the original V1.5 model')
196
+ elif Original_Model_Version == "v2-512":
197
+ model='/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv2-512.ckpt'
198
+ if not os.path.exists('/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv2-512.ckpt'):
199
+ print('Downloading the V2-512 model...')
200
+ call('gdown -O '+model+' https://huggingface.co/stabilityai/stable-diffusion-2-1-base/resolve/main/v2-1_512-nonema-pruned.ckpt', shell=True)
201
+ clear_output()
202
+ print('Using the original V2-512 model')
203
+ elif Original_Model_Version == "v2-768":
204
+ model="/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv2-768.ckpt"
205
+ print('Using the original V2-768 model')
206
+ elif Original_Model_Version == "SDXL":
207
+ model="/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/sd_xl_base_1.0.safetensors"
208
+ print('Using the original SDXL model')
209
+
210
+ else:
211
+ model="/workspace/sd/stable-diffusion-webui/models/Stable-diffusion"
212
+ print('Wrong model version, try again')
213
+ try:
214
+ model
215
+ except:
216
+ model="/workspace/sd/stable-diffusion-webui/models/Stable-diffusion"
217
+
218
+ return model
219
+ def modeldwn(model_LINK):
220
+
221
+ if model_LINK=='':
222
+ print('Nothing to do')
223
+ else:
224
+ os.makedirs('/workspace/sd/stable-diffusion-webui/models/Stable-diffusion', exist_ok=True)
225
+
226
+ src=getsrc(model_LINK)
227
+
228
+ if src=='civitai':
229
+ modelname=get_name(model_LINK, False)
230
+ loramodel=f'/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
231
+ if not os.path.exists(loramodel):
232
+ dwn(model_LINK, loramodel, 'Downloading the LoRA model')
233
+ clear_output()
234
+ else:
235
+ print('Model already exists')
236
+ elif src=='gdrive':
237
+ modelname=get_name(model_LINK, True)
238
+ loramodel=f'/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
239
+ if not os.path.exists(loramodel):
240
+ gdown.download(url=model_LINK, output=loramodel, quiet=False, fuzzy=True)
241
+ clear_output()
242
+ else:
243
+ print('Model already exists')
244
+ else:
245
+ modelname=os.path.basename(model_LINK)
246
+ loramodel=f'/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
247
+ if not os.path.exists(loramodel):
248
+ gdown.download(url=model_LINK, output=loramodel, quiet=False, fuzzy=True)
249
+ clear_output()
250
+ else:
251
+ print('Model already exists')
252
+
253
+ if os.path.exists(loramodel) :
254
+ print('LoRA downloaded')
255
+ else:
256
+ print('Wrong link, check that the link is valid')
257
+
258
+ def loradwn(LoRA_LINK):
259
+
260
+ if LoRA_LINK=='':
261
+ print('Nothing to do')
262
+ else:
263
+ os.makedirs('/workspace/sd/stable-diffusion-webui/models/Lora', exist_ok=True)
264
+
265
+ src=getsrc(LoRA_LINK)
266
+
267
+ if src=='civitai':
268
+ modelname=get_name(LoRA_LINK, False)
269
+ loramodel=f'/workspace/sd/stable-diffusion-webui/models/Lora/{modelname}'
270
+ if not os.path.exists(loramodel):
271
+ dwn(LoRA_LINK, loramodel, 'Downloading the LoRA model')
272
+ clear_output()
273
+ else:
274
+ print('Model already exists')
275
+ elif src=='gdrive':
276
+ modelname=get_name(LoRA_LINK, True)
277
+ loramodel=f'/workspace/sd/stable-diffusion-webui/models/Lora/{modelname}'
278
+ if not os.path.exists(loramodel):
279
+ gdown.download(url=LoRA_LINK, output=loramodel, quiet=False, fuzzy=True)
280
+ clear_output()
281
+ else:
282
+ print('Model already exists')
283
+ else:
284
+ modelname=os.path.basename(LoRA_LINK)
285
+ loramodel=f'/workspace/sd/stable-diffusion-webui/models/Lora/{modelname}'
286
+ if not os.path.exists(loramodel):
287
+ gdown.download(url=LoRA_LINK, output=loramodel, quiet=False, fuzzy=True)
288
+ clear_output()
289
+ else:
290
+ print('Model already exists')
291
+
292
+ if os.path.exists(loramodel) :
293
+ print('LoRA downloaded')
294
+ else:
295
+ print('Wrong link, check that the link is valid')
296
+
297
+
298
+
299
+ def CNet(ControlNet_Model, ControlNet_XL_Model):
300
+
301
+ def download(url, model_dir):
302
+
303
+ filename = os.path.basename(urlparse(url).path)
304
+ pth = os.path.abspath(os.path.join(model_dir, filename))
305
+ if not os.path.exists(pth):
306
+ print('Downloading: '+os.path.basename(url))
307
+ download_url_to_file(url, pth, hash_prefix=None, progress=True)
308
+ else:
309
+ print(f"The model {filename} already exists")
310
+
311
+ wrngv1=False
312
+ os.chdir('/workspace/sd/stable-diffusion-webui/extensions')
313
+ if not os.path.exists("sd-webui-controlnet"):
314
+ call('git clone https://github.com/Mikubill/sd-webui-controlnet.git', shell=True)
315
+ os.chdir('/workspace')
316
+ else:
317
+ os.chdir('sd-webui-controlnet')
318
+ call('git reset --hard', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
319
+ call('git pull', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
320
+ os.chdir('/workspace')
321
+
322
+ mdldir="/workspace/sd/stable-diffusion-webui/extensions/sd-webui-controlnet/models"
323
+ for filename in os.listdir(mdldir):
324
+ if "_sd14v1" in filename:
325
+ renamed = re.sub("_sd14v1", "-fp16", filename)
326
+ os.rename(os.path.join(mdldir, filename), os.path.join(mdldir, renamed))
327
+
328
+ call('wget -q -O CN_models.txt https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/CN_models.txt', shell=True)
329
+ call('wget -q -O CN_models_XL.txt https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/CN_models_XL.txt', shell=True)
330
+
331
+ with open("CN_models.txt", 'r') as f:
332
+ mdllnk = f.read().splitlines()
333
+ with open("CN_models_XL.txt", 'r') as d:
334
+ mdllnk_XL = d.read().splitlines()
335
+ call('rm CN_models.txt CN_models_XL.txt', shell=True)
336
+
337
+ os.chdir('/workspace')
338
+
339
+ if ControlNet_Model == "All" or ControlNet_Model == "all" :
340
+ for lnk in mdllnk:
341
+ download(lnk, mdldir)
342
+ clear_output()
343
+
344
+
345
+ elif ControlNet_Model == "15":
346
+ mdllnk=list(filter(lambda x: 't2i' in x, mdllnk))
347
+ for lnk in mdllnk:
348
+ download(lnk, mdldir)
349
+ clear_output()
350
+
351
+
352
+ elif ControlNet_Model.isdigit() and int(ControlNet_Model)-1<14 and int(ControlNet_Model)>0:
353
+ download(mdllnk[int(ControlNet_Model)-1], mdldir)
354
+ clear_output()
355
+
356
+ elif ControlNet_Model == "none":
357
+ pass
358
+ clear_output()
359
+
360
+ else:
361
+ print('Wrong ControlNet V1 choice, try again')
362
+ wrngv1=True
363
+
364
+
365
+ if ControlNet_XL_Model == "All" or ControlNet_XL_Model == "all" :
366
+ for lnk_XL in mdllnk_XL:
367
+ download(lnk_XL, mdldir)
368
+ if not wrngv1:
369
+ clear_output()
370
+ done()
371
+
372
+ elif ControlNet_XL_Model.isdigit() and int(ControlNet_XL_Model)-1<5:
373
+ download(mdllnk_XL[int(ControlNet_XL_Model)-1], mdldir)
374
+ if not wrngv1:
375
+ clear_output()
376
+ done()
377
+
378
+ elif ControlNet_XL_Model == "none":
379
+ pass
380
+ if not wrngv1:
381
+ clear_output()
382
+ done()
383
+
384
+ else:
385
+ print('Wrong ControlNet XL choice, try again')
386
+
387
+
388
+
389
+ def sd(User, Password, model):
390
+
391
+ import gradio
392
+
393
+ gradio.close_all()
394
+
395
+ auth=f"--gradio-auth {User}:{Password}"
396
+ if User =="" or Password=="":
397
+ auth=""
398
+
399
+ call('wget -q -O /usr/local/lib/python3.10/dist-packages/gradio/blocks.py https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/AUTOMATIC1111_files/blocks.py', shell=True)
400
+
401
+ os.chdir('/workspace/sd/stable-diffusion-webui/modules')
402
+
403
+ call("sed -i 's@possible_sd_paths =.*@possible_sd_paths = [\"/workspace/sd/stablediffusion\"]@' /workspace/sd/stable-diffusion-webui/modules/paths.py", shell=True)
404
+ call("sed -i 's@\.\.\/@src/@g' /workspace/sd/stable-diffusion-webui/modules/paths.py", shell=True)
405
+ call("sed -i 's@src\/generative-models@generative-models@g' /workspace/sd/stable-diffusion-webui/modules/paths.py", shell=True)
406
+
407
+ call("sed -i 's@\[\"sd_model_checkpoint\"\]@\[\"sd_model_checkpoint\", \"sd_vae\", \"CLIP_stop_at_last_layers\", \"inpainting_mask_weight\", \"initial_noise_multiplier\"\]@g' /workspace/sd/stable-diffusion-webui/modules/shared.py", shell=True)
408
+
409
+ call("sed -i 's@print(\"No module.*@@' /workspace/sd/stablediffusion/ldm/modules/diffusionmodules/model.py", shell=True)
410
+ os.chdir('/workspace/sd/stable-diffusion-webui')
411
+ clear_output()
412
+
413
+ podid=os.environ.get('RUNPOD_POD_ID')
414
+ localurl=f"{podid}-3001.proxy.runpod.net"
415
+
416
+ for line in fileinput.input('/usr/local/lib/python3.10/dist-packages/gradio/blocks.py', inplace=True):
417
+ if line.strip().startswith('self.server_name ='):
418
+ line = f' self.server_name = "{localurl}"\n'
419
+ if line.strip().startswith('self.protocol = "https"'):
420
+ line = ' self.protocol = "https"\n'
421
+ if line.strip().startswith('if self.local_url.startswith("https") or self.is_colab'):
422
+ line = ''
423
+ if line.strip().startswith('else "http"'):
424
+ line = ''
425
+ sys.stdout.write(line)
426
+
427
+ if model=="":
428
+ mdlpth=""
429
+ else:
430
+ if os.path.isfile(model):
431
+ mdlpth="--ckpt "+model
432
+ else:
433
+ mdlpth="--ckpt-dir "+model
434
+
435
+ configf="--disable-console-progressbars --no-half-vae --disable-safe-unpickle --api --no-download-sd-model --opt-sdp-attention --enable-insecure-extension-access --skip-version-check --listen --port 3000 "+auth+" "+mdlpth
436
+
437
+ return configf
438
+
439
+
440
+
441
+ def save(Huggingface_Write_token):
442
+
443
+ from slugify import slugify
444
+ from huggingface_hub import HfApi, CommitOperationAdd, create_repo
445
+
446
+ if Huggingface_Write_token=="":
447
+ print('A huggingface write token is required')
448
+
449
+ else:
450
+ os.chdir('/workspace')
451
+
452
+ if os.path.exists('sd'):
453
+
454
+ call('tar --exclude="stable-diffusion-webui/models/*/*" --exclude="sd-webui-controlnet/models/*" --zstd -cf sd_backup_rnpd.tar.zst sd', shell=True)
455
+ api = HfApi()
456
+ username = api.whoami(token=Huggingface_Write_token)["name"]
457
+
458
+ repo_id = f"{username}/{slugify('fast-stable-diffusion')}"
459
+
460
+ print("Backing up...")
461
+
462
+ operations = [CommitOperationAdd(path_in_repo="sd_backup_rnpd.tar.zst", path_or_fileobj="/workspace/sd_backup_rnpd.tar.zst")]
463
+
464
+ create_repo(repo_id,private=True, token=Huggingface_Write_token, exist_ok=True, repo_type="dataset")
465
+
466
+ api.create_commit(
467
+ repo_id=repo_id,
468
+ repo_type="dataset",
469
+ operations=operations,
470
+ commit_message="SD folder Backup",
471
+ token=Huggingface_Write_token
472
+ )
473
+
474
+ call('rm sd_backup_rnpd.tar.zst', shell=True)
475
+ clear_output()
476
+
477
+ done()
478
+
479
+ else:
480
+ print('Nothing to backup')
481
+
482
+
483
+
484
+
485
+ def getsrc(url):
486
+
487
+ parsed_url = urlparse(url)
488
+
489
+ if parsed_url.netloc == 'civitai.com':
490
+ src='civitai'
491
+ elif parsed_url.netloc == 'drive.google.com':
492
+ src='gdrive'
493
+ elif parsed_url.netloc == 'huggingface.co':
494
+ src='huggingface'
495
+ else:
496
+ src='others'
497
+ return src
498
+
499
+
500
+
501
+ def get_name(url, gdrive):
502
+
503
+ from gdown.download import get_url_from_gdrive_confirmation
504
+
505
+ if not gdrive:
506
+ response = requests.get(url, allow_redirects=False)
507
+ if "Location" in response.headers:
508
+ redirected_url = response.headers["Location"]
509
+ quer = parse_qs(urlparse(redirected_url).query)
510
+ if "response-content-disposition" in quer:
511
+ disp_val = quer["response-content-disposition"][0].split(";")
512
+ for vals in disp_val:
513
+ if vals.strip().startswith("filename="):
514
+ filenm=unquote(vals.split("=", 1)[1].strip())
515
+ return filenm.replace("\"","")
516
+ else:
517
+ headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}
518
+ lnk="https://drive.google.com/uc?id={id}&export=download".format(id=url[url.find("/d/")+3:url.find("/view")])
519
+ res = requests.session().get(lnk, headers=headers, stream=True, verify=True)
520
+ res = requests.session().get(get_url_from_gdrive_confirmation(res.text), headers=headers, stream=True, verify=True)
521
+ content_disposition = six.moves.urllib_parse.unquote(res.headers["Content-Disposition"])
522
+ filenm = re.search(r"filename\*=UTF-8''(.*)", content_disposition).groups()[0].replace(os.path.sep, "_")
523
+ return filenm
524
+
525
+
526
+
527
+
528
+ def done():
529
+ done = widgets.Button(
530
+ description='Done!',
531
+ disabled=True,
532
+ button_style='success',
533
+ tooltip='',
534
+ icon='check'
535
+ )
536
+ display(done)