Disisthe commited on
Commit
2e9a517
1 Parent(s): 2f81da8

Upload stable_diffusion_1_5_webui_stable.py

Browse files
Files changed (1) hide show
  1. stable_diffusion_1_5_webui_stable.py +324 -0
stable_diffusion_1_5_webui_stable.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """stable_diffusion_1_5_webui_STABLE.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1f_rCor24FJmMPx4Uu8UxbQjvnhFA9MtM
8
+
9
+ # AUTOMATIC1111 Stable Diffusion WebUI 1.5 + ChilloutMix Checkpoint
10
+
11
+ For generating AI Onlyfans
12
+
13
+ > [@nang](https://github.com/nathan-149)
14
+ > Based off of: [@wibus-wee](https://github.com/wibus-wee)
15
+ > Reference: [camenduru/stable-diffusion-webui-colab](https://github.com/camenduru/stable-diffusion-webui-colab)
16
+ """
17
+
18
+ # Commented out IPython magic to ensure Python compatibility.
19
+ #@title 2. Check GPU & Dev Environment
20
+
21
+ from IPython.display import display
22
+ import ipywidgets as widgets
23
+ import requests
24
+
25
+ import os, subprocess
26
+ paperspace_m4000 = False
27
+ #@markdown Paperspace platform?
28
+ isPaperspace = False #@param {type:"boolean"}
29
+ try:
30
+ subprocess.run(['nvidia-smi', '--query-gpu=name', '--format=csv,noheader'], stdout=subprocess.PIPE)
31
+ if 'M4000' in subprocess.run(['nvidia-smi', '--query-gpu=name', '--format=csv,noheader'], stdout=subprocess.PIPE).stdout.decode('utf-8'):
32
+ print("WARNING: You're using Quadro M4000 GPU,xformers won't work。")
33
+ paperspace_m4000 = True
34
+ isPaperspace = True
35
+ else:
36
+ print("Your GPU is suitable - " + subprocess.run(['nvidia-smi', '--query-gpu=name', '--format=csv,noheader'], stdout=subprocess.PIPE).stdout.decode('utf-8') + "。")
37
+ print("Platform: Paperspace" if isPaperspace else "Platform: Colab")
38
+ except:
39
+ print("No GPU appears to be available. Please check your runtime type")
40
+ exit()
41
+
42
+ rootDir = isPaperspace and '/tmp' or '/content'
43
+ stableDiffusionWebUIInstalled = os.path.exists(rootDir + '/stable-diffusion-webui')
44
+ # %store rootDir
45
+ # %store paperspace_m4000
46
+ # %store isPaperspace
47
+ # %store stableDiffusionWebUIInstalled
48
+
49
+ # Commented out IPython magic to ensure Python compatibility.
50
+ import requests
51
+ #@title 3. Install dependencies and extensions
52
+
53
+ #@markdown ## **Extensions**
54
+
55
+ #@markdown xformer
56
+ xformersInstall = True #@param {type:"boolean"}
57
+ #@markdown ControlNet
58
+ controlNetExtension = False #@param {type:"boolean"}
59
+ #@markdown OpenPose Editor
60
+ openPoseExtension = False #@param {type:"boolean"}
61
+ #@markdown Civitai Browser
62
+ civitaiBrowserExtension = False #@param {type:"boolean"}
63
+ #@markdown HuggingFace
64
+ huggingFaceExtension = False #@param {type:"boolean"}
65
+ #@markdown Images Browser
66
+ imagesBrowserExtension = False #@param {type:"boolean"}
67
+ #@markdown Additional Networks
68
+ additionalNetworksExtension = True #@param {type:"boolean"}
69
+ #@markdown Deforum
70
+ deforumExtension = False #@param {type:"boolean"}
71
+ #@markdown Kohya sd-scripts
72
+ kohyaExtension = False #@param {type:"boolean"}
73
+ #@markdown DreamBooth
74
+ dreamBoothExtension = False #@param {type:"boolean"}
75
+
76
+
77
+ #@markdown ---
78
+ #@markdown ## **Textual Inversion**
79
+ #@markdown Ulzzang-6500 (Korean doll aesthetic)
80
+ ulzzang6500 = True #@param {type:"boolean"}
81
+ #@markdown Pure Eros Face
82
+ pureErosFace = True #@param {type:"boolean"}
83
+
84
+ #@markdown ---
85
+
86
+ #@markdown ## **Startup Options**
87
+
88
+ #@markdown API Support
89
+ apiSupport = True #@param {type:"boolean"}
90
+
91
+ textualInversionDownloadIDs = {
92
+ 'ulzzang6500': 8109,
93
+ 'pureErosFace': 4514,
94
+ }
95
+
96
+ def getLatestModelDownloadURL(id):
97
+ try:
98
+ if type(id) == int:
99
+ res = requests.get(endpoint + '/' + str(id)).json()
100
+ latest = res['modelVersions'][0]
101
+ downloadLink = latest['files'][0]['downloadUrl']
102
+ name = latest['files'][0]['name']
103
+ return {
104
+ 'url': downloadLink,
105
+ 'name': name
106
+ }
107
+ else:
108
+ return {
109
+ 'url': id,
110
+ 'name': id.split('/')[-1]
111
+ }
112
+ except:
113
+ print("Lora model " + str(id) + " not found. Skip.")
114
+ return None
115
+
116
+ def getSpecificModelDownloadURL(id, version):
117
+ try:
118
+ if type(id) == int:
119
+ res = requests.get(endpoint + '/' + str(id)).json()
120
+ for modelVersion in res['modelVersions']:
121
+ if modelVersion['name'] == version:
122
+ # if modelVersion["baseModel"] != "SD 1.5":
123
+ # print("Lora model " + str(id) + " is not SD 1.5, may not work. Skip.")
124
+ # return None
125
+ downloadLink = modelVersion['files'][0]['downloadUrl']
126
+ name = modelVersion['files'][0]['name']
127
+ return {
128
+ 'url': downloadLink,
129
+ 'name': name
130
+ }
131
+ else:
132
+ return {
133
+ 'url': id,
134
+ 'name': id.split('/')[-1]
135
+ }
136
+ except:
137
+ print("Lora model " + str(id) + " version " + version + " not found. Skip.")
138
+ return None
139
+
140
+ def getTextualInversionDownloadURLs():
141
+ downloadURLs = []
142
+ for key in textualInversionDownloadIDs:
143
+ if not eval(key): # skip if not selected
144
+ continue
145
+ if type(textualInversionDownloadIDs[key]) is int:
146
+ downloadURLs.append(getLatestModelDownloadURL(textualInversionDownloadIDs[key]))
147
+ elif type(textualInversionDownloadIDs[key]) is dict: # {'id': 123, 'version': 'v1.0'}
148
+ downloadURLs.append(getSpecificModelDownloadURL(textualInversionDownloadIDs[key]['id'], textualInversionDownloadIDs[key]['version']))
149
+ elif type(textualInversionDownloadIDs[key]) is str: # url
150
+ downloadURLs.append({ 'url': textualInversionDownloadIDs[key], 'name': textualInversionDownloadIDs[key].split('/')[-1] })
151
+ downloadURLs = [x for x in downloadURLs if x is not None]
152
+ return downloadURLs
153
+
154
+ textualInversionDownloadURLs = getTextualInversionDownloadURLs()
155
+
156
+ # %store -r paperspace_m4000
157
+ # %store -r isPaperspace
158
+ # %store -r rootDir
159
+ # %store -r checkpoints
160
+ # %store -r downloadLinks
161
+ # %store -r stableDiffusionWebUIInstalled
162
+
163
+ import subprocess
164
+
165
+ !apt-get -y install -qq aria2
166
+ ariaInstalled = False
167
+
168
+ try:
169
+ subprocess.run(['aria2c', '--version'], stdout=subprocess.PIPE)
170
+ ariaInstalled = True
171
+ except:
172
+ pass
173
+
174
+ if paperspace_m4000:
175
+ if xformersInstall:
176
+ !pip install ninja
177
+ !pip install -v -U git+https://github.com/facebookresearch/xformers.git@main#egg=xformers
178
+ !pip install -q --pre triton
179
+ else:
180
+ !pip install -q https://github.com/camenduru/stable-diffusion-webui-colab/releases/download/0.0.16/xformers-0.0.16+814314d.d20230118-cp38-cp38-linux_x86_64.whl
181
+ !pip install -q --pre triton
182
+
183
+
184
+ !git clone -b v2.0 https://github.com/nathan-149/stable-diffusion-webui {rootDir}/stable-diffusion-webui
185
+ !wget https://raw.githubusercontent.com/nathan-149/stable-diffusion-webui-scripts/main/run_n_times.py -O {rootDir}/stable-diffusion-webui/scripts/run_n_times.py
186
+ if deforumExtension:
187
+ !git clone https://github.com/deforum-art/deforum-for-automatic1111-webui {rootDir}/stable-diffusion-webui/extensions/deforum-for-automatic1111-webui
188
+ if imagesBrowserExtension:
189
+ !git clone https://github.com/AlUlkesh/stable-diffusion-webui-images-browser {rootDir}/stable-diffusion-webui/extensions/stable-diffusion-webui-images-browser
190
+ if huggingFaceExtension:
191
+ !git clone https://github.com/camenduru/stable-diffusion-webui-huggingface {rootDir}/stable-diffusion-webui/extensions/stable-diffusion-webui-huggingface
192
+ if civitaiBrowserExtension:
193
+ !git clone -b v2.0 https://github.com/camenduru/sd-civitai-browser {rootDir}/stable-diffusion-webui/extensions/sd-civitai-browser
194
+ if openPoseExtension:
195
+ !git clone https://github.com/camenduru/openpose-editor {rootDir}/stable-diffusion-webui/extensions/openpose-editor
196
+ if controlNetExtension:
197
+ !git clone https://github.com/Mikubill/sd-webui-controlnet {rootDir}/stable-diffusion-webui/extensions/sd-webui-controlnet
198
+ if additionalNetworksExtension:
199
+ !git clone https://github.com/kohya-ss/sd-webui-additional-networks {rootDir}/stable-diffusion-webui/extensions/sd-webui-additional-networks
200
+ if kohyaExtension:
201
+ !git clone https://github.com/ddpn08/kohya-sd-scripts-webui.git {rootDir}/stable-diffusion-webui/extensions/kohya-sd-scripts-webui
202
+ if dreamBoothExtension:
203
+ !git clone https://github.com/d8ahazard/sd_dreambooth_extension {rootDir}/stable-diffusion-webui/extensions/sd_dreambooth_extension
204
+
205
+ if isPaperspace:
206
+ # %cd /stable-diffusion-webui
207
+ else:
208
+ # %cd {rootDir}/stable-diffusion-webui
209
+
210
+
211
+ webuiControlNetModels = [
212
+ "https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/control_canny-fp16.safetensors",
213
+ "https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/control_depth-fp16.safetensors",
214
+ "https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/control_hed-fp16.safetensors",
215
+ "https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/control_mlsd-fp16.safetensors",
216
+ "https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/control_normal-fp16.safetensors",
217
+ "https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/control_openpose-fp16.safetensors",
218
+ "https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/control_scribble-fp16.safetensors",
219
+ "https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/control_seg-fp16.safetensors",
220
+ ]
221
+ annotatorLink = [
222
+ "https://huggingface.co/ckpt/ControlNet/resolve/main/hand_pose_model.pth",
223
+ "https://huggingface.co/ckpt/ControlNet/resolve/main/body_pose_model.pth",
224
+ "https://huggingface.co/ckpt/ControlNet/resolve/main/dpt_hybrid-midas-501f0c75.pt",
225
+ "https://huggingface.co/ckpt/ControlNet/resolve/main/mlsd_large_512_fp32.pth",
226
+ "https://huggingface.co/ckpt/ControlNet/resolve/main/mlsd_tiny_512_fp32.pth",
227
+ "https://huggingface.co/ckpt/ControlNet/resolve/main/network-bsds500.pth",
228
+ "https://huggingface.co/ckpt/ControlNet/resolve/main/upernet_global_small.pth",
229
+ ]
230
+
231
+ def ariaDownload(downloadLink, checkpoint, path):
232
+ if (type(downloadLink) == list and type(checkpoint) == list):
233
+ for i in downloadLink:
234
+ !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M {i} -d {path} -o {checkpoint[downloadLink.index(i)]}
235
+ else:
236
+ !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M {downloadLink} -d {path} -o {checkpoint}
237
+ def wgetDownload(downloadLink, checkpoint, path):
238
+ if (type(downloadLink) == list and type(checkpoint) == list):
239
+ for i in downloadLink:
240
+ !wget -c {i} -P {path} -O {checkpoint[downloadLink.index(i)]}
241
+ else:
242
+ !wget -c {downloadLink} -P {path} -O {checkpoint}
243
+ def autoDetectDownload(downloadLink, checkpoint, path):
244
+ if ariaInstalled:
245
+ ariaDownload(downloadLink, checkpoint, path)
246
+ else:
247
+ wgetDownload(downloadLink, checkpoint, path)
248
+
249
+ if controlNetExtension:
250
+ for model in webuiControlNetModels:
251
+ autoDetectDownload(model, model.split('/')[-1], rootDir + "/stable-diffusion-webui/extensions/sd-webui-controlnet/models")
252
+ for model in annotatorLink:
253
+ autoDetectDownload(model, model.split('/')[-1], rootDir + "/stable-diffusion-webui/extensions/sd-webui-controlnet/annotator")
254
+ for model in textualInversionDownloadURLs:
255
+ autoDetectDownload(model["url"], model["name"], rootDir + "/stable-diffusion-webui/embeddings")
256
+
257
+ if additionalNetworksExtension:
258
+ !ln -s {rootDir}/stable-diffusion-webui/extensions/sd-webui-additional-networks/models/lora {rootDir}/stable-diffusion-webui/models/Lora
259
+
260
+
261
+ stableDiffusionWebUIInstalled = True
262
+ # %store stableDiffusionWebUIInstalled
263
+
264
+ # %cd {rootDir}/stable-diffusion-webui
265
+ !sed -i -e '''/prepare_environment()/a\ os.system\(f\"""sed -i -e ''\"s/self.logvar\\[t\\]/self.logvar\\[t.item()\\]/g\"'' {rootDir}/stable-diffusion-webui/repositories/stable-diffusion-stability-ai/ldm/models/diffusion/ddpm.py""")''' {rootDir}/stable-diffusion-webui/launch.py
266
+ !sed -i -e '''/prepare_environment()/a\ os.system\(f\"""sed -i -e ''\"s/dict()))/dict())).cuda()/g\"'' {rootDir}/stable-diffusion-webui/repositories/stable-diffusion-stability-ai/ldm/util.py""")''' {rootDir}/stable-diffusion-webui/launch.py
267
+ if dreamBoothExtension:
268
+ !export REQS_FILE="./extensions/sd_dreambooth_extension/requirements.txt"
269
+
270
+ #@title Download Chilloutmix Checkpoint
271
+
272
+ checkpoint = 'chilloutmix.safetensors' #@param ["chilloutmix.safetensors"]
273
+
274
+ downloadLink = 'https://civitai.com/api/download/models/11745' #@param
275
+
276
+
277
+ !wget -c {downloadLink} -O /content/stable-diffusion-webui/models/Stable-diffusion/{checkpoint}
278
+ !aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/ckpt/sd14/resolve/main/sd-v1-4.ckpt -d /content/stable-diffusion-webui/models/Stable-diffusion -o sd-v1-4.ckpt
279
+
280
+ #@title Download Loras
281
+
282
+ loraLinks = dict((
283
+ ('koreanDollLikeness_v15.safetensors', 'https://civitai.com/api/download/models/31284'),
284
+ ('xswltry1.safetensors', 'https://civitai.com/api/download/models/29131'),
285
+ ('liyuuLora_liyuuV1.safetensors', 'https://civitai.com/models/9997/liyuu-lora'),
286
+ ('aiBeautyIthlinni_ithlinniV1.safetensors', 'https://civitai.com/api/download/models/19671'),
287
+ ('Cute_girl_mix4.safetensors', 'https://civitai.com/api/download/models/16677'),
288
+ ('breastinclassBetter_v141.safetensors', 'https://civitai.com/api/download/models/23250'),
289
+ ('chilloutmixss_xss10.safetensors', 'https://huggingface.co/HankChang/chilloutmixss_xss10/resolve/main/chilloutmixss_xss10.safetensors'),
290
+ ('moxin.safetensors', 'https://civitai.com/api/download/models/14856'),
291
+ ('legspread10.safetensors', 'https://civitai.com/api/download/models/29760'),
292
+ ('taiwan.safetensors', 'https://civitai.com/api/download/models/20684')
293
+ ))
294
+
295
+
296
+ for lora, link in loraLinks.items():
297
+ print('\nKey: %s' % lora)
298
+ print('Value: %s' % link)
299
+ !wget -c {link} -O /content/stable-diffusion-webui/models/Lora/{lora}
300
+
301
+ # Commented out IPython magic to ensure Python compatibility.
302
+ #@title Run UI!
303
+ # %pip install torch==1.13.1+cu117 torchvision==0.14.1+cu117 torchtext==0.14.1 torchaudio==0.13.1 torchdata==0.5.1 --extra-index-url https://download.pytorch.org/whl/cu117
304
+ !cd /content/stable-diffusion-webui/ && python launch.py --enable-insecure-extension-access --share
305
+
306
+ # Commented out IPython magic to ensure Python compatibility.
307
+ #@title 5. Export Photos to /export
308
+ # %store -r rootDir
309
+
310
+ from pathlib import Path
311
+ import os, subprocess
312
+
313
+ export_storage_dir = Path(rootDir, 'export')
314
+ export_storage_dir.mkdir(exist_ok=True)
315
+
316
+ !if [ $(dpkg-query -W -f='${Status}' p7zip-full 2>/dev/null | grep -c "ok installed") = 0 ]; then sudo apt update && sudo apt install -y p7zip-full; fi # install 7z if it isn't already installed
317
+ from datetime import datetime
318
+ datetime_str = datetime.now().strftime('%m-%d-%Y_%H-%M-%S')
319
+ # %cd "{export_storage_dir}"
320
+ !mkdir -p "{datetime_str}/log"
321
+ !cd "{rootDir}/stable-diffusion-webui/log" && mv * "{export_storage_dir / datetime_str / 'log'}"
322
+ !cd "{rootDir}/stable-diffusion-webui/outputs" && mv * "{export_storage_dir / datetime_str}"
323
+ s = subprocess.run(f'find "{Path(export_storage_dir, datetime_str)}" -type d -name .ipynb_checkpoints -exec rm -rv {{}} +', shell=True)
324
+ !7z a -t7z -m0=lzma2 -mx=9 -mfb=64 -md=32m -ms=on "{datetime_str}.7z" "{export_storage_dir / datetime_str}"