TheLastBen commited on
Commit
ce93ff0
1 Parent(s): a0f43c3

Upload mainppsComfy.py

Browse files
Files changed (1) hide show
  1. Scripts/mainppsComfy.py +415 -0
Scripts/mainppsComfy.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.9/dist-packages/safetensors'):
24
+ ntbk()
25
+ call('pip install --root-user-action=ignore --disable-pip-version-check -qq diffusers==0.18.1', shell=True, stdout=open('/dev/null', 'w'))
26
+ os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
27
+ os.environ['PYTHONWARNINGS'] = 'ignore'
28
+ print('Modules and notebooks updated, dependencies already installed')
29
+
30
+ else:
31
+ call("pip install --root-user-action=ignore --no-deps -q accelerate==0.12.0", shell=True, stdout=open('/dev/null', 'w'))
32
+ if not os.path.exists('/usr/local/lib/python3.9/dist-packages/safetensors'):
33
+ os.chdir('/usr/local/lib/python3.9/dist-packages')
34
+ call("rm -r torch torch-1.12.1+cu116.dist-info torchaudio* torchvision* PIL Pillow* transformers* numpy* gdown*", shell=True, stdout=open('/dev/null', 'w'))
35
+ ntbk()
36
+ if not os.path.exists('/models'):
37
+ call('mkdir /models', shell=True)
38
+ if not os.path.exists('/notebooks/models'):
39
+ call('ln -s /models /notebooks', shell=True)
40
+ if os.path.exists('/deps'):
41
+ call("rm -r /deps", shell=True)
42
+ call('mkdir /deps', shell=True)
43
+ if not os.path.exists('cache'):
44
+ call('mkdir cache', shell=True)
45
+ os.chdir('/deps')
46
+ call('wget -q -i https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dependencies/aptdeps.txt', shell=True)
47
+ call('dpkg -i *.deb', shell=True, stdout=open('/dev/null', 'w'))
48
+ depsinst("https://huggingface.co/TheLastBen/dependencies/resolve/main/ppsdeps.tar.zst", "/deps/ppsdeps.tar.zst")
49
+ call('tar -C / --zstd -xf ppsdeps.tar.zst', shell=True, stdout=open('/dev/null', 'w'))
50
+ call("sed -i 's@~/.cache@/notebooks/cache@' /usr/local/lib/python3.9/dist-packages/transformers/utils/hub.py", shell=True)
51
+ os.chdir('/notebooks')
52
+ call('pip install --root-user-action=ignore --disable-pip-version-check -qq diffusers==0.18.1', shell=True, stdout=open('/dev/null', 'w'))
53
+ call("git clone --depth 1 -q --branch main https://github.com/TheLastBen/diffusers /diffusers", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
54
+ os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
55
+ os.environ['PYTHONWARNINGS'] = 'ignore'
56
+ call("sed -i 's@text = _formatwarnmsg(msg)@text =\"\"@g' /usr/lib/python3.9/warnings.py", shell=True)
57
+ call('pip install --root-user-action=ignore --disable-pip-version-check -qq gradio==3.41.2', shell=True, stdout=open('/dev/null', 'w'))
58
+ if not os.path.exists('/notebooks/diffusers'):
59
+ call('ln -s /diffusers /notebooks', shell=True)
60
+ call("rm -r /deps", shell=True)
61
+ os.chdir('/notebooks')
62
+ clear_output()
63
+
64
+ done()
65
+
66
+
67
+ def depsinst(url, dst):
68
+ file_size = None
69
+ req = Request(url, headers={"User-Agent": "torch.hub"})
70
+ u = urlopen(req)
71
+ meta = u.info()
72
+ if hasattr(meta, 'getheaders'):
73
+ content_length = meta.getheaders("Content-Length")
74
+ else:
75
+ content_length = meta.get_all("Content-Length")
76
+ if content_length is not None and len(content_length) > 0:
77
+ file_size = int(content_length[0])
78
+
79
+ with tqdm(total=file_size, disable=False, mininterval=0.5,
80
+ bar_format='Installing dependencies |{bar:20}| {percentage:3.0f}%') as pbar:
81
+ with open(dst, "wb") as f:
82
+ while True:
83
+ buffer = u.read(8192)
84
+ if len(buffer) == 0:
85
+ break
86
+ f.write(buffer)
87
+ pbar.update(len(buffer))
88
+ f.close()
89
+
90
+
91
+
92
+ def dwn(url, dst, msg):
93
+ file_size = None
94
+ req = Request(url, headers={"User-Agent": "torch.hub"})
95
+ u = urlopen(req)
96
+ meta = u.info()
97
+ if hasattr(meta, 'getheaders'):
98
+ content_length = meta.getheaders("Content-Length")
99
+ else:
100
+ content_length = meta.get_all("Content-Length")
101
+ if content_length is not None and len(content_length) > 0:
102
+ file_size = int(content_length[0])
103
+
104
+ with tqdm(total=file_size, disable=False, mininterval=0.5,
105
+ bar_format=msg+' |{bar:20}| {percentage:3.0f}%') as pbar:
106
+ with open(dst, "wb") as f:
107
+ while True:
108
+ buffer = u.read(8192)
109
+ if len(buffer) == 0:
110
+ break
111
+ f.write(buffer)
112
+ pbar.update(len(buffer))
113
+ f.close()
114
+
115
+
116
+
117
+
118
+ def ntbk():
119
+
120
+ os.chdir('/notebooks')
121
+ if not os.path.exists('Latest_Notebooks'):
122
+ call('mkdir Latest_Notebooks', shell=True)
123
+ else:
124
+ call('rm -r Latest_Notebooks', shell=True)
125
+ call('mkdir Latest_Notebooks', shell=True)
126
+ os.chdir('/notebooks/Latest_Notebooks')
127
+ call('wget -q -i https://huggingface.co/datasets/TheLastBen/PPS/raw/main/Notebooks.txt', shell=True)
128
+ call('rm Notebooks.txt', shell=True)
129
+ os.chdir('/notebooks')
130
+
131
+
132
+
133
+
134
+ def repo():
135
+
136
+ os.chdir('/notebooks')
137
+
138
+ print('Installing/Updating the repo...')
139
+ os.chdir('/notebooks')
140
+ if not os.path.exists('ComfyUI'):
141
+ call('git clone -q --depth 1 https://github.com/comfyanonymous/ComfyUI', shell=True)
142
+
143
+ os.chdir('ComfyUI')
144
+ call('git reset --hard', shell=True)
145
+ print('')
146
+ call('git pull', shell=True)
147
+ os.chdir('/notebooks')
148
+ clear_output()
149
+ done()
150
+
151
+
152
+
153
+ def mdls(Original_Model_Version, Path_to_MODEL, MODEL_LINK, Temporary_Storage):
154
+
155
+ import gdown
156
+
157
+
158
+ src=getsrc(MODEL_LINK)
159
+
160
+
161
+ call('ln -s /datasets/stable-diffusion-classic/SDv1.5.ckpt /notebooks/ComfyUI/models/checkpoints/Stable-diffusion', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
162
+ call('ln -s /datasets/stable-diffusion-v2-1-base-diffusers/stable-diffusion-2-1-base/v2-1_512-nonema-pruned.safetensors /notebooks/ComfyUI/models/checkpoints/Stable-diffusion', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
163
+ call('ln -s /datasets/stable-diffusion-v2-1/stable-diffusion-2-1/v2-1_768-nonema-pruned.safetensors /notebooks/ComfyUI/models/checkpoints/Stable-diffusion', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
164
+ call('ln -s /datasets/stable-diffusion-xl/sd_xl_base_1.0.safetensors /notebooks/ComfyUI/models/checkpoints/Stable-diffusion', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
165
+
166
+ if Path_to_MODEL !='':
167
+ if os.path.exists(str(Path_to_MODEL)):
168
+ print('Using the custom model.')
169
+ model=Path_to_MODEL
170
+ else:
171
+ print('Wrong path, check that the path to the model is correct')
172
+
173
+ elif MODEL_LINK !="":
174
+
175
+ if src=='civitai':
176
+ modelname=get_name(MODEL_LINK, False)
177
+ if Temporary_Storage:
178
+ model=f'/models/{modelname}'
179
+ else:
180
+ model=f'/notebooks/ComfyUI/models/checkpoints/Stable-diffusion/{modelname}'
181
+ if not os.path.exists(model):
182
+ dwn(MODEL_LINK, model, 'Downloading the custom model')
183
+ clear_output()
184
+ else:
185
+ print('Model already exists')
186
+ elif src=='gdrive':
187
+ modelname=get_name(MODEL_LINK, True)
188
+ if Temporary_Storage:
189
+ model=f'/models/{modelname}'
190
+ else:
191
+ model=f'/notebooks/ComfyUI/models/checkpoints/Stable-diffusion/{modelname}'
192
+ if not os.path.exists(model):
193
+ gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
194
+ clear_output()
195
+ else:
196
+ print('Model already exists')
197
+ else:
198
+ modelname=os.path.basename(MODEL_LINK)
199
+ if Temporary_Storage:
200
+ model=f'/models/{modelname}'
201
+ else:
202
+ model=f'/notebooks/ComfyUI/models/checkpoints/Stable-diffusion/{modelname}'
203
+ if not os.path.exists(model):
204
+ gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
205
+ clear_output()
206
+ else:
207
+ print('Model already exists')
208
+
209
+ if os.path.exists(model) and os.path.getsize(model) > 1810671599:
210
+ print('Model downloaded, using the custom model.')
211
+ else:
212
+ call('rm '+model, shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
213
+ print('Wrong link, check that the link is valid')
214
+
215
+ else:
216
+ if Original_Model_Version == "v1.5":
217
+ model="/notebooks/ComfyUI/models/checkpoints/Stable-diffusion/SDv1.5.ckpt"
218
+ print('Using the original V1.5 model')
219
+ elif Original_Model_Version == "v2-512":
220
+ model="/notebooks/ComfyUI/models/checkpoints/Stable-diffusion/v2-1_512-nonema-pruned.safetensors"
221
+ print('Using the original V2-512 model')
222
+ elif Original_Model_Version == "v2-768":
223
+ model="/notebooks/ComfyUI/models/checkpoints/Stable-diffusion/v2-1_768-nonema-pruned.safetensors"
224
+ print('Using the original V2-768 model')
225
+ elif Original_Model_Version == "SDXL":
226
+ model="/notebooks/ComfyUI/models/checkpoints/Stable-diffusion/sd_xl_base_1.0.safetensors"
227
+ print('Using the original SDXL model')
228
+ else:
229
+ model="/notebooks/ComfyUI/models/checkpoints/Stable-diffusion"
230
+ print('Wrong model version, try again')
231
+ try:
232
+ model
233
+ except:
234
+ model="/notebooks/ComfyUI/models/checkpoints/Stable-diffusion"
235
+
236
+ return model
237
+
238
+
239
+
240
+ def loradwn(LoRA_LINK):
241
+
242
+ if LoRA_LINK=='':
243
+ print('Nothing to do')
244
+ else:
245
+ src=getsrc(LoRA_LINK)
246
+
247
+ if src=='civitai':
248
+ modelname=get_name(LoRA_LINK, False)
249
+ loramodel=f'/notebooks/ComfyUI/models/loras/{modelname}'
250
+ if not os.path.exists(loramodel):
251
+ dwn(LoRA_LINK, loramodel, 'Downloading the LoRA model')
252
+ clear_output()
253
+ else:
254
+ print('Model already exists')
255
+ elif src=='gdrive':
256
+ modelname=get_name(LoRA_LINK, True)
257
+ loramodel=f'/notebooks/ComfyUI/models/loras/{modelname}'
258
+ if not os.path.exists(loramodel):
259
+ gdown.download(url=LoRA_LINK, output=loramodel, quiet=False, fuzzy=True)
260
+ clear_output()
261
+ else:
262
+ print('Model already exists')
263
+ else:
264
+ modelname=os.path.basename(LoRA_LINK)
265
+ loramodel=f'/notebooks/ComfyUI/models/loras/{modelname}'
266
+ if not os.path.exists(loramodel):
267
+ gdown.download(url=LoRA_LINK, output=loramodel, quiet=False, fuzzy=True)
268
+ clear_output()
269
+ else:
270
+ print('Model already exists')
271
+
272
+ if os.path.exists(loramodel) :
273
+ print('LoRA downloaded')
274
+ else:
275
+ print('Wrong link, check that the link is valid')
276
+
277
+
278
+
279
+ def CNet(ControlNet_Model, ControlNet_XL_Model):
280
+
281
+ def download(url, model_dir):
282
+
283
+ filename = os.path.basename(urlparse(url).path)
284
+ pth = os.path.abspath(os.path.join(model_dir, filename))
285
+ if not os.path.exists(pth):
286
+ print('Downloading: '+os.path.basename(url))
287
+ download_url_to_file(url, pth, hash_prefix=None, progress=True)
288
+ else:
289
+ print(f"The model {filename} already exists")
290
+
291
+ wrngv1=False
292
+ mdldir="/notebooks/ComfyUI/models/controlnet"
293
+ for filename in os.listdir(mdldir):
294
+ if "_sd14v1" in filename:
295
+ renamed = re.sub("_sd14v1", "-fp16", filename)
296
+ os.rename(os.path.join(mdldir, filename), os.path.join(mdldir, renamed))
297
+
298
+ call('wget -q -O CN_models.txt https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/CN_models.txt', shell=True)
299
+ 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)
300
+
301
+ with open("CN_models.txt", 'r') as f:
302
+ mdllnk = f.read().splitlines()
303
+ with open("CN_models_XL.txt", 'r') as d:
304
+ mdllnk_XL = d.read().splitlines()
305
+ call('rm CN_models.txt CN_models_XL.txt', shell=True)
306
+
307
+ os.chdir('/notebooks')
308
+ if ControlNet_Model == "All" or ControlNet_Model == "all" :
309
+ for lnk in mdllnk:
310
+ download(lnk, mdldir)
311
+ clear_output()
312
+
313
+ elif ControlNet_Model == "15":
314
+ mdllnk=list(filter(lambda x: 't2i' in x, mdllnk))
315
+ for lnk in mdllnk:
316
+ download(lnk, mdldir)
317
+ clear_output()
318
+
319
+
320
+ elif ControlNet_Model.isdigit() and int(ControlNet_Model)-1<14 and int(ControlNet_Model)>0:
321
+ download(mdllnk[int(ControlNet_Model)-1], mdldir)
322
+ clear_output()
323
+
324
+ elif ControlNet_Model == "none":
325
+ pass
326
+ clear_output()
327
+
328
+ else:
329
+ print('Wrong ControlNet V1 choice, try again')
330
+ wrngv1=True
331
+
332
+
333
+ if ControlNet_XL_Model == "All" or ControlNet_XL_Model == "all" :
334
+ for lnk_XL in mdllnk_XL:
335
+ download(lnk_XL, mdldir)
336
+ if not wrngv1:
337
+ clear_output()
338
+ done()
339
+
340
+ elif ControlNet_XL_Model.isdigit() and int(ControlNet_XL_Model)-1<5:
341
+ download(mdllnk_XL[int(ControlNet_XL_Model)-1], mdldir)
342
+ if not wrngv1:
343
+ clear_output()
344
+ done()
345
+
346
+ elif ControlNet_XL_Model == "none":
347
+ pass
348
+ if not wrngv1:
349
+ clear_output()
350
+ done()
351
+
352
+ else:
353
+ print('Wrong ControlNet V2 choice, try again')
354
+
355
+
356
+
357
+ def sd():
358
+
359
+ localurl="https://tensorboard-"+os.environ.get('PAPERSPACE_FQDN')
360
+ call("sed -i 's@print(\"To see the GUI go to: http://{}:{}\".format(address, port))@print(\"\u2714 Connected\")\\n print(\""+localurl+"\")@' /notebooks/ComfyUI/server.py", shell=True)
361
+ os.chdir('/notebooks')
362
+
363
+
364
+
365
+
366
+ def getsrc(url):
367
+ parsed_url = urlparse(url)
368
+ if parsed_url.netloc == 'civitai.com':
369
+ src='civitai'
370
+ elif parsed_url.netloc == 'drive.google.com':
371
+ src='gdrive'
372
+ elif parsed_url.netloc == 'huggingface.co':
373
+ src='huggingface'
374
+ else:
375
+ src='others'
376
+ return src
377
+
378
+
379
+
380
+ def get_name(url, gdrive):
381
+
382
+ from gdown.download import get_url_from_gdrive_confirmation
383
+
384
+ if not gdrive:
385
+ response = requests.get(url, allow_redirects=False)
386
+ if "Location" in response.headers:
387
+ redirected_url = response.headers["Location"]
388
+ quer = parse_qs(urlparse(redirected_url).query)
389
+ if "response-content-disposition" in quer:
390
+ disp_val = quer["response-content-disposition"][0].split(";")
391
+ for vals in disp_val:
392
+ if vals.strip().startswith("filename="):
393
+ filenm=unquote(vals.split("=", 1)[1].strip())
394
+ return filenm.replace("\"","")
395
+ else:
396
+ 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"}
397
+ lnk="https://drive.google.com/uc?id={id}&export=download".format(id=url[url.find("/d/")+3:url.find("/view")])
398
+ res = requests.session().get(lnk, headers=headers, stream=True, verify=True)
399
+ res = requests.session().get(get_url_from_gdrive_confirmation(res.text), headers=headers, stream=True, verify=True)
400
+ content_disposition = six.moves.urllib_parse.unquote(res.headers["Content-Disposition"])
401
+ filenm = re.search(r"filename\*=UTF-8''(.*)", content_disposition).groups()[0].replace(os.path.sep, "_")
402
+ return filenm
403
+
404
+
405
+
406
+
407
+ def done():
408
+ done = widgets.Button(
409
+ description='Done!',
410
+ disabled=True,
411
+ button_style='success',
412
+ tooltip='',
413
+ icon='check'
414
+ )
415
+ display(done)