AhhhhCraaaap commited on
Commit
622904d
·
1 Parent(s): 3652de7

Update app.py

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