stlaurentjr commited on
Commit
9d08232
1 Parent(s): 0ea9934

Update scripts/mainrunpodA1111.py

Browse files
Files changed (1) hide show
  1. scripts/mainrunpodA1111.py +609 -379
scripts/mainrunpodA1111.py CHANGED
@@ -14,41 +14,68 @@ import gdown
14
 
15
  from urllib.request import urlopen, Request
16
  import tempfile
17
- from tqdm import tqdm
18
  from bs4 import BeautifulSoup
19
  import zipfile
20
 
21
 
22
-
23
  def Deps(force_reinstall):
24
 
25
- if not force_reinstall and os.path.exists('/usr/local/lib/python3.10/dist-packages/safetensors'):
 
 
26
  ntbks()
27
- print('Modules and notebooks updated, dependencies already installed')
28
- os.environ['TORCH_HOME'] = '/workspace/cache/torch'
29
- os.environ['PYTHONWARNINGS'] = 'ignore'
30
  else:
31
- 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'))
 
 
 
 
32
  ntbks()
33
- if os.path.exists('deps'):
34
  call("rm -r deps", shell=True)
35
- if os.path.exists('diffusers'):
36
  call("rm -r diffusers", shell=True)
37
- call('mkdir deps', shell=True)
38
- if not os.path.exists('cache'):
39
- call('mkdir cache', shell=True)
40
- os.chdir('deps')
41
- dwn("https://huggingface.co/TheLastBen/dependencies/resolve/main/rnpddeps-t2.tar.zst", "/workspace/deps/rnpddeps-t2.tar.zst", "Installing dependencies")
42
- call('tar -C / --zstd -xf rnpddeps-t2.tar.zst', shell=True, stdout=open('/dev/null', 'w'))
43
- call("sed -i 's@~/.cache@/workspace/cache@' /usr/local/lib/python3.10/dist-packages/transformers/utils/hub.py", shell=True)
44
- os.chdir('/workspace')
45
- call("git clone --depth 1 -q --branch main https://github.com/TheLastBen/diffusers", shell=True, stdout=open('/dev/null', 'w'))
46
- call('pip install --root-user-action=ignore --disable-pip-version-check -qq gradio==3.41.2', shell=True, stdout=open('/dev/null', 'w'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  call("rm -r deps", shell=True)
48
- os.chdir('/workspace')
49
- os.environ['TORCH_HOME'] = '/workspace/cache/torch'
50
- os.environ['PYTHONWARNINGS'] = 'ignore'
51
- call("sed -i 's@text = _formatwarnmsg(msg)@text =\"\"@g' /usr/lib/python3.10/warnings.py", shell=True)
 
 
 
52
  clear_output()
53
 
54
  done()
@@ -59,15 +86,19 @@ def dwn(url, dst, msg):
59
  req = Request(url, headers={"User-Agent": "torch.hub"})
60
  u = urlopen(req)
61
  meta = u.info()
62
- if hasattr(meta, 'getheaders'):
63
  content_length = meta.getheaders("Content-Length")
64
  else:
65
  content_length = meta.get_all("Content-Length")
66
  if content_length is not None and len(content_length) > 0:
67
  file_size = int(content_length[0])
68
 
69
- with tqdm(total=file_size, disable=False, mininterval=0.5,
70
- bar_format=msg+' |{bar:20}| {percentage:3.0f}%') as pbar:
 
 
 
 
71
  with open(dst, "wb") as f:
72
  while True:
73
  buffer = u.read(8192)
@@ -80,520 +111,706 @@ def dwn(url, dst, msg):
80
 
81
  def ntbks():
82
 
83
- os.chdir('/workspace')
84
- if not os.path.exists('Latest_Notebooks'):
85
- call('mkdir Latest_Notebooks', shell=True)
86
  else:
87
- call('rm -r Latest_Notebooks', shell=True)
88
- call('mkdir Latest_Notebooks', shell=True)
89
- os.chdir('/workspace/Latest_Notebooks')
90
- call('wget -q -i https://huggingface.co/datasets/TheLastBen/RNPD/raw/main/Notebooks.txt', shell=True)
91
- call('rm Notebooks.txt', shell=True)
92
- os.chdir('/workspace')
 
 
 
93
 
94
 
95
  def repo(Huggingface_token_optional):
96
 
97
  from slugify import slugify
98
  from huggingface_hub import HfApi, CommitOperationAdd, create_repo
99
-
100
- os.chdir('/workspace')
101
- if Huggingface_token_optional!="":
102
- username = HfApi().whoami(Huggingface_token_optional)["name"]
103
- backup=f"https://huggingface.co/datasets/{username}/fast-stable-diffusion/resolve/main/sd_backup_rnpd.tar.zst"
104
- headers = {"Authorization": f"Bearer {Huggingface_token_optional}"}
105
- response = requests.head(backup, headers=headers)
106
- if response.status_code == 302:
107
- print('Restoring the SD folder...')
108
- open('/workspace/sd_backup_rnpd.tar.zst', 'wb').write(requests.get(backup, headers=headers).content)
109
- call('tar --zstd -xf sd_backup_rnpd.tar.zst', shell=True)
110
- call('rm sd_backup_rnpd.tar.zst', shell=True)
111
- else:
112
- print('Backup not found, using a fresh/existing repo...')
113
- time.sleep(2)
114
- if not os.path.exists('/workspace/sd/stablediffusiond'): #reset later
115
- call('wget -q -O sd_mrep.tar.zst https://huggingface.co/TheLastBen/dependencies/resolve/main/sd_mrep.tar.zst', shell=True)
116
- call('tar --zstd -xf sd_mrep.tar.zst', shell=True)
117
- call('rm sd_mrep.tar.zst', shell=True)
118
- os.chdir('/workspace/sd')
119
- if not os.path.exists('stable-diffusion-webui'):
120
- call('git clone -q --depth 1 --branch master https://github.com/AUTOMATIC1111/stable-diffusion-webui', shell=True)
121
-
 
 
 
 
 
 
 
 
122
  else:
123
- print('Installing/Updating the repo...')
124
- os.chdir('/workspace')
125
- if not os.path.exists('/workspace/sd/stablediffusiond'): #reset later
126
- call('wget -q -O sd_mrep.tar.zst https://huggingface.co/TheLastBen/dependencies/resolve/main/sd_mrep.tar.zst', shell=True)
127
- call('tar --zstd -xf sd_mrep.tar.zst', shell=True)
128
- call('rm sd_mrep.tar.zst', shell=True)
129
-
130
- os.chdir('/workspace/sd')
131
- if not os.path.exists('stable-diffusion-webui'):
132
- call('git clone -q --depth 1 --branch master https://github.com/AUTOMATIC1111/stable-diffusion-webui', shell=True)
133
-
134
- os.chdir('/workspace/sd/stable-diffusion-webui/')
135
- call('git reset --hard', shell=True)
136
- print('')
137
- call('git pull', shell=True)
138
- os.chdir('/workspace')
 
 
 
 
 
 
139
  clear_output()
140
  done()
141
 
142
 
143
-
144
  def mdl(Original_Model_Version, Path_to_MODEL, MODEL_LINK):
145
 
146
  import gdown
147
-
148
- src=getsrc(MODEL_LINK)
149
-
150
- if not os.path.exists('/workspace/sd/stable-diffusion-webui/models/VAE'):
151
- call('mkdir -p /workspace/sd/stable-diffusion-webui/models/VAE', shell=True)
152
-
153
  # Получаем список файлов в директории /workspace/auto-VAE
154
- files = os.listdir('/workspace/auto-VAE')
155
-
156
  for file in files:
157
- source_path = os.path.join('/workspace/auto-VAE', file)
158
- target_path = os.path.join('/workspace/sd/stable-diffusion-webui/models/VAE', file)
 
 
159
  # Проверяем, существует ли уже символическая ссылка
160
  if not os.path.exists(target_path):
161
- call(f'ln -s {source_path} {target_path}', shell=True)
162
 
163
- #if os.path.exists('/workspace/sd/stable-diffusion-webui/models/VAE'):
164
  # call('ln -s /workspace/auto-VAE/* /workspace/sd/stable-diffusion-webui/models/VAE', shell=True)
165
- #else:
166
  # call('mkdir -p /workspace/sd/stable-diffusion-webui/models/VAE', shell=True)
167
  # call('ln -s /workspace/auto-VAE/* /workspace/sd/stable-diffusion-webui/models/VAE', shell=True)
168
 
169
- if not os.path.exists('/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv1-5.ckpt'):
170
- call('ln -s /workspace/auto-models/* /workspace/sd/stable-diffusion-webui/models/Stable-diffusion', shell=True)
171
-
172
- if not os.path.exists('/workspace/sd/stable-diffusion-webui/models/Lora'):
173
- call('mkdir -p /workspace/sd/stable-diffusion-webui/models/Lora', shell=True)
174
- call('ln -s /workspace/auto-lora/* /workspace/sd/stable-diffusion-webui/models/Lora', shell=True)
175
-
176
- if Path_to_MODEL !='':
177
- if os.path.exists(str(Path_to_MODEL)):
178
- print('Using the custom model')
179
- model=Path_to_MODEL
180
- else:
181
- print('Wrong path, check that the path to the model is correct')
182
-
183
- elif MODEL_LINK !="":
184
-
185
- if src=='civitai':
186
- modelname=get_name(MODEL_LINK, False)
187
- model=f'/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
188
- if not os.path.exists(model):
189
- dwn(MODEL_LINK, model, 'Downloading the custom model')
190
- clear_output()
191
- else:
192
- print('Model already exists')
193
- elif src=='gdrive':
194
- modelname=get_name(MODEL_LINK, True)
195
- model=f'/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
196
- if not os.path.exists(model):
197
- gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
198
- clear_output()
199
- else:
200
- print('Model already exists')
201
- else:
202
- modelname=os.path.basename(MODEL_LINK)
203
- model=f'/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
204
- if not os.path.exists(model):
205
- gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
206
- clear_output()
207
- else:
208
- print('Model already exists')
 
 
 
 
 
 
 
 
209
 
210
- if os.path.exists(model) and os.path.getsize(model) > 1810671599:
211
- print('Model downloaded, using the custom model.')
212
- else:
213
- call('rm '+model, shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
214
- print('Wrong link, check that the link is valid')
 
 
 
 
 
215
 
216
  else:
217
  if Original_Model_Version == "v1.5":
218
- model="/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv1-5.ckpt"
219
- print('Using the original V1.5 model')
220
  elif Original_Model_Version == "v2-512":
221
- model='/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv2-512.ckpt'
222
- if not os.path.exists('/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv2-512.ckpt'):
223
- print('Downloading the V2-512 model...')
224
- call('gdown -O '+model+' https://huggingface.co/stabilityai/stable-diffusion-2-1-base/resolve/main/v2-1_512-nonema-pruned.ckpt', shell=True)
225
- clear_output()
226
- print('Using the original V2-512 model')
 
 
 
 
 
 
 
227
  elif Original_Model_Version == "v2-768":
228
- model="/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv2-768.ckpt"
229
- print('Using the original V2-768 model')
230
  elif Original_Model_Version == "SDXL":
231
- model="/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/sd_xl_base_1.0.safetensors"
232
- print('Using the original SDXL model')
233
 
234
  else:
235
- model="/workspace/sd/stable-diffusion-webui/models/Stable-diffusion"
236
- print('Wrong model version, try again')
237
  try:
238
  model
239
  except:
240
- model="/workspace/sd/stable-diffusion-webui/models/Stable-diffusion"
241
 
242
  return model
 
 
243
  def modeldwn(model_LINK):
244
 
245
- if model_LINK=='':
246
- print('Nothing to do')
247
  else:
248
- os.makedirs('/workspace/sd/stable-diffusion-webui/models/Stable-diffusion', exist_ok=True)
 
 
 
249
 
250
- src=getsrc(model_LINK)
251
 
252
- if src=='civitai':
253
- modelname=get_name(model_LINK, False)
254
- loramodel=f'/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
255
  if not os.path.exists(loramodel):
256
- dwn(model_LINK, loramodel, 'Downloading the LoRA model')
257
- clear_output()
258
  else:
259
- print('Model already exists')
260
- elif src=='gdrive':
261
- modelname=get_true_name(model_LINK)
262
- loramodel=f'/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
263
  if not os.path.exists(loramodel):
264
- gdown.download(url=model_LINK.replace('/file/d/', '/uc?id=').replace('/view', ''), output=loramodel, quiet=False)
265
- clear_output()
 
 
 
 
266
  else:
267
- print('Model already exists')
268
  else:
269
- modelname=os.path.basename(model_LINK)
270
- loramodel=f'/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
271
  if not os.path.exists(loramodel):
272
- gdown.download(url=model_LINK, output=loramodel, quiet=False, fuzzy=True)
273
- clear_output()
 
 
274
  else:
275
- print('Model already exists')
276
 
277
- if os.path.exists(loramodel) :
278
- print('Checkpoints downloaded')
279
  else:
280
- print('Wrong link, check that the link is valid')
 
281
 
282
  def loradwn(LoRA_LINK):
283
 
284
- if LoRA_LINK=='':
285
- print('Nothing to do')
286
  else:
287
- os.makedirs('/workspace/sd/stable-diffusion-webui/models/Lora', exist_ok=True)
288
 
289
- src=getsrc(LoRA_LINK)
290
 
291
- if src=='civitai':
292
- modelname=get_name(LoRA_LINK, False)
293
- loramodel=f'/workspace/sd/stable-diffusion-webui/models/Lora/{modelname}'
294
  if not os.path.exists(loramodel):
295
- dwn(LoRA_LINK, loramodel, 'Downloading the LoRA model')
296
- clear_output()
297
  else:
298
- print('Model already exists')
299
- elif src=='gdrive':
300
- modelname=get_true_name(LoRA_LINK)
301
- loramodel=f'/workspace/sd/stable-diffusion-webui/models/Lora/{modelname}'
302
  if not os.path.exists(loramodel):
303
- gdown.download(url=LoRA_LINK.replace('/file/d/', '/uc?id=').replace('/view', ''), output=loramodel, quiet=False)
304
- clear_output()
 
 
 
 
305
  else:
306
- print('Model already exists')
307
  else:
308
- modelname=os.path.basename(LoRA_LINK)
309
- loramodel=f'/workspace/sd/stable-diffusion-webui/models/Lora/{modelname}'
310
  if not os.path.exists(loramodel):
311
- gdown.download(url=LoRA_LINK, output=loramodel, quiet=False, fuzzy=True)
312
- clear_output()
313
  else:
314
- print('Model already exists')
315
 
316
- if os.path.exists(loramodel) :
317
- print('LoRA downloaded')
318
  else:
319
- print('Wrong link, check that the link is valid')
 
320
 
321
  def download_and_install_config():
322
- target_directory = '/workspace/sd/stable-diffusion-webui/'
323
- config_url = "https://huggingface.co/spaces/stlaurentjr/RNPD/raw/main/config/config.json"
324
- config_file_path = os.path.join(target_directory, 'config.json')
325
-
 
 
326
  # Check if the config file already exists
327
  if not os.path.exists(config_file_path):
328
  # Change the directory
329
  os.chdir(target_directory)
330
  # Download the file using curl command
331
- call(f'curl -o config.json {config_url}', shell=True)
332
- print(f'Config file downloaded successfully.')
333
  else:
334
- print('Config file already exists, download skipped.')
 
335
 
336
- def InstallDeforum():
337
- os.chdir('/workspace/sd/stable-diffusion-webui/extensions')
 
 
 
338
  if not os.path.exists("deforum-for-automatic1111-webui"):
339
- call('git clone https://github.com/deforum-art/sd-webui-deforum.git', shell=True)
340
- os.chdir('/workspace')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  else:
342
- os.chdir('deforum-for-automatic1111-webui')
343
- call('git reset --hard', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
344
- call('git pull', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
345
- os.chdir('/workspace')
346
 
347
- def InstallWildCards():
348
  # Путь к целевой директории
349
- target_dir = '/workspace/sd/stable-diffusion-webui/extensions/stable-diffusion-webui-wildcards/wildcards/'
350
 
351
  # Перемещаемся в директорию расширений
352
- os.chdir('/workspace/sd/stable-diffusion-webui/extensions')
353
 
354
  if not os.path.exists("stable-diffusion-webui-wildcards"):
355
  # Клонирование репозитория, если он ещё не существует
356
- call('git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui-wildcards.git', shell=True)
357
-
 
 
 
358
  # Перемещаемся в клонированный репозиторий
359
- os.chdir('stable-diffusion-webui-wildcards')
360
 
361
  # Скачиваем файл по ID
362
- gdown.download(id='1sY9Yv29cCYZuxBvszkmLVgw--aRdwT1P', output='wildcards.zip', quiet=False)
 
 
363
 
364
  # Создаем целевую директорию, если она ещё не существует
365
  os.makedirs(target_dir, exist_ok=True)
366
 
367
  # Распаковываем архив
368
- with zipfile.ZipFile('wildcards.zip', 'r') as zip_ref:
369
  zip_ref.extractall(target_dir)
370
  else:
371
  # Если репозиторий уже существует, обновляем его
372
- os.chdir('stable-diffusion-webui-wildcards')
373
- call('git reset --hard', shell=True, stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w'))
374
- call('git pull', shell=True, stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w'))
 
 
 
 
 
 
 
 
 
 
375
 
376
  # Возвращаемся в исходную рабочую директорию
377
- os.chdir('/workspace')
 
378
 
379
  def CNet(ControlNet_Model, ControlNet_XL_Model):
380
-
381
  def download(url, model_dir):
382
 
383
  filename = os.path.basename(urlparse(url).path)
384
  pth = os.path.abspath(os.path.join(model_dir, filename))
385
  if not os.path.exists(pth):
386
- print('Downloading: '+os.path.basename(url))
387
  download_url_to_file(url, pth, hash_prefix=None, progress=True)
388
  else:
389
- print(f"The model {filename} already exists")
390
 
391
- wrngv1=False
392
- os.chdir('/workspace/sd/stable-diffusion-webui/extensions')
393
  if not os.path.exists("sd-webui-controlnet"):
394
- call('git clone https://github.com/Mikubill/sd-webui-controlnet.git', shell=True)
395
- os.chdir('/workspace')
 
 
396
  else:
397
- os.chdir('sd-webui-controlnet')
398
- call('git reset --hard', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
399
- call('git pull', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
400
- os.chdir('/workspace')
401
-
402
- mdldir="/workspace/sd/stable-diffusion-webui/extensions/sd-webui-controlnet/models"
403
- call('ln -s /workspace/auto-controlnet-models/* /workspace/sd/stable-diffusion-webui/extensions/sd-webui-controlnet/models', shell=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
 
405
  for filename in os.listdir(mdldir):
406
- if "_sd14v1" in filename:
407
- renamed = re.sub("_sd14v1", "-fp16", filename)
408
- os.rename(os.path.join(mdldir, filename), os.path.join(mdldir, renamed))
409
-
410
- call('wget -q -O CN_models.txt https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/CN_models.txt', shell=True)
411
- 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)
412
-
413
- with open("CN_models.txt", 'r') as f:
 
 
 
 
 
 
414
  mdllnk = f.read().splitlines()
415
- with open("CN_models_XL.txt", 'r') as d:
416
  mdllnk_XL = d.read().splitlines()
417
- call('rm CN_models.txt CN_models_XL.txt', shell=True)
418
-
419
- os.chdir('/workspace')
420
 
421
- if ControlNet_Model == "All" or ControlNet_Model == "all" :
422
- for lnk in mdllnk:
423
- download(lnk, mdldir)
424
- clear_output()
 
 
425
 
426
-
427
  elif ControlNet_Model == "15":
428
- mdllnk=list(filter(lambda x: 't2i' in x, mdllnk))
429
- for lnk in mdllnk:
430
- download(lnk, mdldir)
431
- clear_output()
432
 
 
 
 
 
 
 
 
433
 
434
- elif ControlNet_Model.isdigit() and int(ControlNet_Model)-1<14 and int(ControlNet_Model)>0:
435
- download(mdllnk[int(ControlNet_Model)-1], mdldir)
436
- clear_output()
437
-
438
  elif ControlNet_Model == "none":
439
- pass
440
- clear_output()
441
 
442
  else:
443
- print('Wrong ControlNet V1 choice, try again')
444
- wrngv1=True
445
 
 
 
 
 
 
 
446
 
447
- if ControlNet_XL_Model == "All" or ControlNet_XL_Model == "all" :
448
- for lnk_XL in mdllnk_XL:
449
- download(lnk_XL, mdldir)
450
- if not wrngv1:
451
- clear_output()
452
- done()
453
 
454
- elif ControlNet_XL_Model.isdigit() and int(ControlNet_XL_Model)-1<5:
455
- download(mdllnk_XL[int(ControlNet_XL_Model)-1], mdldir)
456
- if not wrngv1:
457
- clear_output()
458
- done()
459
-
460
  elif ControlNet_XL_Model == "none":
461
- pass
462
- if not wrngv1:
463
- clear_output()
464
- done()
465
 
466
  else:
467
- print('Wrong ControlNet XL choice, try again')
468
-
469
 
470
 
471
  def sd(User, Password, model):
472
 
473
  import gradio
474
-
475
  gradio.close_all()
476
-
477
- auth=f"--gradio-auth {User}:{Password}"
478
- if User =="" or Password=="":
479
- auth=""
480
-
481
- 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)
482
-
483
- os.chdir('/workspace/sd/stable-diffusion-webui/modules')
484
-
485
- call("sed -i 's@possible_sd_paths =.*@possible_sd_paths = [\"/workspace/sd/stablediffusion\"]@' /workspace/sd/stable-diffusion-webui/modules/paths.py", shell=True)
486
- call("sed -i 's@\.\.\/@src/@g' /workspace/sd/stable-diffusion-webui/modules/paths.py", shell=True)
487
- call("sed -i 's@src\/generative-models@generative-models@g' /workspace/sd/stable-diffusion-webui/modules/paths.py", shell=True)
488
-
489
- 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)
490
-
491
- 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)
492
-
493
- call("sed -i 's/\"CLIP_stop_at_last_layers\": 1/\"CLIP_stop_at_last_layers\": 2/g' /workspace/sd/stable-diffusion-webui/config.json", shell=True)
494
-
495
- call("sed -i 's@print(\"No module.*@@' /workspace/sd/stablediffusion/ldm/modules/diffusionmodules/model.py", shell=True)
496
-
497
- os.chdir('/workspace/sd/stable-diffusion-webui')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
498
  clear_output()
499
 
500
- podid=os.environ.get('RUNPOD_POD_ID')
501
- localurl=f"{podid}-3001.proxy.runpod.net"
502
-
503
- for line in fileinput.input('/usr/local/lib/python3.10/dist-packages/gradio/blocks.py', inplace=True):
504
- if line.strip().startswith('self.server_name ='):
505
- line = f' self.server_name = "{localurl}"\n'
506
- if line.strip().startswith('self.protocol = "https"'):
507
- line = ' self.protocol = "https"\n'
508
- if line.strip().startswith('if self.local_url.startswith("https") or self.is_colab'):
509
- line = ''
510
- if line.strip().startswith('else "http"'):
511
- line = ''
512
- sys.stdout.write(line)
513
-
514
- if model=="":
515
- mdlpth=""
 
 
 
 
516
  else:
517
  if os.path.isfile(model):
518
- mdlpth="--ckpt "+model
519
  else:
520
- mdlpth="--ckpt-dir "+model
521
  vae_path = "--vae-path /workspace/sd/stable-diffusion-webui/models/VAE/vae-ft-mse-840000-ema-pruned.safetensors"
522
- 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+" "+vae_path
 
 
 
 
 
 
 
523
 
524
  return configf
525
 
526
 
527
-
528
  def save(Huggingface_Write_token):
529
-
530
  from slugify import slugify
531
  from huggingface_hub import HfApi, CommitOperationAdd, create_repo
532
-
533
- if Huggingface_Write_token=="":
534
- print('A huggingface write token is required')
535
-
536
  else:
537
- os.chdir('/workspace')
538
-
539
- if os.path.exists('sd'):
540
-
541
- call('tar --exclude="stable-diffusion-webui/models/*/*" --exclude="sd-webui-controlnet/models/*" --zstd -cf sd_backup_rnpd.tar.zst sd', shell=True)
 
 
 
542
  api = HfApi()
543
  username = api.whoami(token=Huggingface_Write_token)["name"]
544
 
545
  repo_id = f"{username}/{slugify('fast-stable-diffusion')}"
546
 
547
- print("Backing up...")
548
-
549
- operations = [CommitOperationAdd(path_in_repo="sd_backup_rnpd.tar.zst", path_or_fileobj="/workspace/sd_backup_rnpd.tar.zst")]
550
-
551
- create_repo(repo_id,private=True, token=Huggingface_Write_token, exist_ok=True, repo_type="dataset")
 
 
 
 
 
 
 
 
 
 
 
552
 
553
  api.create_commit(
554
- repo_id=repo_id,
555
- repo_type="dataset",
556
- operations=operations,
557
- commit_message="SD folder Backup",
558
- token=Huggingface_Write_token
559
  )
560
 
561
- call('rm sd_backup_rnpd.tar.zst', shell=True)
562
  clear_output()
563
 
564
  done()
565
-
566
- else:
567
- print('Nothing to backup')
568
-
569
 
 
 
570
 
571
 
572
  def getsrc(url):
573
 
574
  parsed_url = urlparse(url)
575
-
576
- if parsed_url.netloc == 'civitai.com':
577
- src='civitai'
578
- elif parsed_url.netloc == 'drive.google.com':
579
- src='gdrive'
580
- elif parsed_url.netloc == 'huggingface.co':
581
- src='huggingface'
582
  else:
583
- src='others'
584
  return src
585
 
 
586
  def get_true_name(url):
587
  response = requests.get(url)
588
- soup = BeautifulSoup(response.text, 'html.parser')
589
- title_tag = soup.find('title')
590
  if title_tag:
591
  title_text = title_tag.text
592
  # Извлечение имени файла из тега title (предполагая, что имя файла указано в теге title)
593
- file_name = title_text.split(' - ')[0]
594
  return file_name
595
  else:
596
- raise RuntimeError('Could not find the title tag in the HTML')
 
597
 
598
  def get_name(url, gdrive):
599
 
@@ -608,26 +825,39 @@ def get_name(url, gdrive):
608
  disp_val = quer["response-content-disposition"][0].split(";")
609
  for vals in disp_val:
610
  if vals.strip().startswith("filename="):
611
- filenm=unquote(vals.split("=", 1)[1].strip())
612
- return filenm.replace("\"","")
613
  else:
614
- 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"}
615
- lnk="https://drive.google.com/uc?id={id}&export=download".format(id=url[url.find("/d/")+3:url.find("/view")])
 
 
 
 
616
  res = requests.session().get(lnk, headers=headers, stream=True, verify=True)
617
- res = requests.session().get(get_url_from_gdrive_confirmation(res.text), headers=headers, stream=True, verify=True)
618
- content_disposition = six.moves.urllib_parse.unquote(res.headers["Content-Disposition"])
619
- filenm = re.search(r"filename\*=UTF-8''(.*)", content_disposition).groups()[0].replace(os.path.sep, "_")
620
- return filenm
621
-
622
-
 
 
 
 
 
 
 
 
 
623
 
624
 
625
  def done():
626
  done = widgets.Button(
627
- description='Done!',
628
  disabled=True,
629
- button_style='success',
630
- tooltip='',
631
- icon='check'
632
  )
633
- display(done)
 
14
 
15
  from urllib.request import urlopen, Request
16
  import tempfile
17
+ from tqdm import tqdm
18
  from bs4 import BeautifulSoup
19
  import zipfile
20
 
21
 
 
22
  def Deps(force_reinstall):
23
 
24
+ if not force_reinstall and os.path.exists(
25
+ "/usr/local/lib/python3.10/dist-packages/safetensors"
26
+ ):
27
  ntbks()
28
+ print("[1;32mModules and notebooks updated, dependencies already installed")
29
+ os.environ["TORCH_HOME"] = "/workspace/cache/torch"
30
+ os.environ["PYTHONWARNINGS"] = "ignore"
31
  else:
32
+ call(
33
+ "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",
34
+ shell=True,
35
+ stdout=open("/dev/null", "w"),
36
+ )
37
  ntbks()
38
+ if os.path.exists("deps"):
39
  call("rm -r deps", shell=True)
40
+ if os.path.exists("diffusers"):
41
  call("rm -r diffusers", 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
+ dwn(
47
+ "https://huggingface.co/TheLastBen/dependencies/resolve/main/rnpddeps-t2.tar.zst",
48
+ "/workspace/deps/rnpddeps-t2.tar.zst",
49
+ "Installing dependencies",
50
+ )
51
+ call(
52
+ "tar -C / --zstd -xf rnpddeps-t2.tar.zst",
53
+ shell=True,
54
+ stdout=open("/dev/null", "w"),
55
+ )
56
+ call(
57
+ "sed -i 's@~/.cache@/workspace/cache@' /usr/local/lib/python3.10/dist-packages/transformers/utils/hub.py",
58
+ shell=True,
59
+ )
60
+ os.chdir("/workspace")
61
+ call(
62
+ "git clone --depth 1 -q --branch main https://github.com/TheLastBen/diffusers",
63
+ shell=True,
64
+ stdout=open("/dev/null", "w"),
65
+ )
66
+ call(
67
+ "pip install --root-user-action=ignore --disable-pip-version-check -qq gradio==3.41.2",
68
+ shell=True,
69
+ stdout=open("/dev/null", "w"),
70
+ )
71
  call("rm -r deps", shell=True)
72
+ os.chdir("/workspace")
73
+ os.environ["TORCH_HOME"] = "/workspace/cache/torch"
74
+ os.environ["PYTHONWARNINGS"] = "ignore"
75
+ call(
76
+ "sed -i 's@text = _formatwarnmsg(msg)@text =\"\"@g' /usr/lib/python3.10/warnings.py",
77
+ shell=True,
78
+ )
79
  clear_output()
80
 
81
  done()
 
86
  req = Request(url, headers={"User-Agent": "torch.hub"})
87
  u = urlopen(req)
88
  meta = u.info()
89
+ if hasattr(meta, "getheaders"):
90
  content_length = meta.getheaders("Content-Length")
91
  else:
92
  content_length = meta.get_all("Content-Length")
93
  if content_length is not None and len(content_length) > 0:
94
  file_size = int(content_length[0])
95
 
96
+ with tqdm(
97
+ total=file_size,
98
+ disable=False,
99
+ mininterval=0.5,
100
+ bar_format=msg + " |{bar:20}| {percentage:3.0f}%",
101
+ ) as pbar:
102
  with open(dst, "wb") as f:
103
  while True:
104
  buffer = u.read(8192)
 
111
 
112
  def ntbks():
113
 
114
+ os.chdir("/workspace")
115
+ if not os.path.exists("Latest_Notebooks"):
116
+ call("mkdir Latest_Notebooks", shell=True)
117
  else:
118
+ call("rm -r Latest_Notebooks", shell=True)
119
+ call("mkdir Latest_Notebooks", shell=True)
120
+ os.chdir("/workspace/Latest_Notebooks")
121
+ call(
122
+ "wget -q -i https://huggingface.co/datasets/TheLastBen/RNPD/raw/main/Notebooks.txt",
123
+ shell=True,
124
+ )
125
+ call("rm Notebooks.txt", shell=True)
126
+ os.chdir("/workspace")
127
 
128
 
129
  def repo(Huggingface_token_optional):
130
 
131
  from slugify import slugify
132
  from huggingface_hub import HfApi, CommitOperationAdd, create_repo
133
+
134
+ os.chdir("/workspace")
135
+ if Huggingface_token_optional != "":
136
+ username = HfApi().whoami(Huggingface_token_optional)["name"]
137
+ backup = f"https://huggingface.co/datasets/{username}/fast-stable-diffusion/resolve/main/sd_backup_rnpd.tar.zst"
138
+ headers = {"Authorization": f"Bearer {Huggingface_token_optional}"}
139
+ response = requests.head(backup, headers=headers)
140
+ if response.status_code == 302:
141
+ print("[1;33mRestoring the SD folder...")
142
+ open("/workspace/sd_backup_rnpd.tar.zst", "wb").write(
143
+ requests.get(backup, headers=headers).content
144
+ )
145
+ call("tar --zstd -xf sd_backup_rnpd.tar.zst", shell=True)
146
+ call("rm sd_backup_rnpd.tar.zst", shell=True)
147
+ else:
148
+ print("[1;33mBackup not found, using a fresh/existing repo...")
149
+ time.sleep(2)
150
+ if not os.path.exists("/workspace/sd/stablediffusiond"): # reset later
151
+ call(
152
+ "wget -q -O sd_mrep.tar.zst https://huggingface.co/TheLastBen/dependencies/resolve/main/sd_mrep.tar.zst",
153
+ shell=True,
154
+ )
155
+ call("tar --zstd -xf sd_mrep.tar.zst", shell=True)
156
+ call("rm sd_mrep.tar.zst", shell=True)
157
+ os.chdir("/workspace/sd")
158
+ if not os.path.exists("stable-diffusion-webui"):
159
+ call(
160
+ "git clone -q --depth 1 --branch master https://github.com/AUTOMATIC1111/stable-diffusion-webui",
161
+ shell=True,
162
+ )
163
+
164
  else:
165
+ print("[1;33mInstalling/Updating the repo...")
166
+ os.chdir("/workspace")
167
+ if not os.path.exists("/workspace/sd/stablediffusiond"): # reset later
168
+ call(
169
+ "wget -q -O sd_mrep.tar.zst https://huggingface.co/TheLastBen/dependencies/resolve/main/sd_mrep.tar.zst",
170
+ shell=True,
171
+ )
172
+ call("tar --zstd -xf sd_mrep.tar.zst", shell=True)
173
+ call("rm sd_mrep.tar.zst", shell=True)
174
+
175
+ os.chdir("/workspace/sd")
176
+ if not os.path.exists("stable-diffusion-webui"):
177
+ call(
178
+ "git clone -q --depth 1 --branch master https://github.com/AUTOMATIC1111/stable-diffusion-webui",
179
+ shell=True,
180
+ )
181
+
182
+ os.chdir("/workspace/sd/stable-diffusion-webui/")
183
+ call("git reset --hard", shell=True)
184
+ print("[1;32m")
185
+ call("git pull", shell=True)
186
+ os.chdir("/workspace")
187
  clear_output()
188
  done()
189
 
190
 
 
191
  def mdl(Original_Model_Version, Path_to_MODEL, MODEL_LINK):
192
 
193
  import gdown
194
+
195
+ src = getsrc(MODEL_LINK)
196
+
197
+ if not os.path.exists("/workspace/sd/stable-diffusion-webui/models/VAE"):
198
+ call("mkdir -p /workspace/sd/stable-diffusion-webui/models/VAE", shell=True)
199
+
200
  # Получаем список файлов в директории /workspace/auto-VAE
201
+ files = os.listdir("/workspace/auto-VAE")
202
+
203
  for file in files:
204
+ source_path = os.path.join("/workspace/auto-VAE", file)
205
+ target_path = os.path.join(
206
+ "/workspace/sd/stable-diffusion-webui/models/VAE", file
207
+ )
208
  # Проверяем, существует ли уже символическая ссылка
209
  if not os.path.exists(target_path):
210
+ call(f"ln -s {source_path} {target_path}", shell=True)
211
 
212
+ # if os.path.exists('/workspace/sd/stable-diffusion-webui/models/VAE'):
213
  # call('ln -s /workspace/auto-VAE/* /workspace/sd/stable-diffusion-webui/models/VAE', shell=True)
214
+ # else:
215
  # call('mkdir -p /workspace/sd/stable-diffusion-webui/models/VAE', shell=True)
216
  # call('ln -s /workspace/auto-VAE/* /workspace/sd/stable-diffusion-webui/models/VAE', shell=True)
217
 
218
+ if not os.path.exists(
219
+ "/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv1-5.ckpt"
220
+ ):
221
+ call(
222
+ "ln -s /workspace/auto-models/* /workspace/sd/stable-diffusion-webui/models/Stable-diffusion",
223
+ shell=True,
224
+ )
225
+
226
+ if not os.path.exists("/workspace/sd/stable-diffusion-webui/models/Lora"):
227
+ call("mkdir -p /workspace/sd/stable-diffusion-webui/models/Lora", shell=True)
228
+ call(
229
+ "ln -s /workspace/auto-lora/* /workspace/sd/stable-diffusion-webui/models/Lora",
230
+ shell=True,
231
+ )
232
+
233
+ if Path_to_MODEL != "":
234
+ if os.path.exists(str(Path_to_MODEL)):
235
+ print("[1;32mUsing the custom model")
236
+ model = Path_to_MODEL
237
+ else:
238
+ print("[1;31mWrong path, check that the path to the model is correct")
239
+
240
+ elif MODEL_LINK != "":
241
+
242
+ if src == "civitai":
243
+ modelname = get_name(MODEL_LINK, False)
244
+ model = f"/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}"
245
+ if not os.path.exists(model):
246
+ dwn(MODEL_LINK, model, "Downloading the custom model")
247
+ clear_output()
248
+ else:
249
+ print("[1;33mModel already exists")
250
+ elif src == "gdrive":
251
+ modelname = get_name(MODEL_LINK, True)
252
+ model = f"/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}"
253
+ if not os.path.exists(model):
254
+ gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
255
+ clear_output()
256
+ else:
257
+ print("[1;33mModel already exists")
258
+ else:
259
+ modelname = os.path.basename(MODEL_LINK)
260
+ model = f"/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}"
261
+ if not os.path.exists(model):
262
+ gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
263
+ clear_output()
264
+ else:
265
+ print("[1;33mModel already exists")
266
 
267
+ if os.path.exists(model) and os.path.getsize(model) > 1810671599:
268
+ print("[1;32mModel downloaded, using the custom model.")
269
+ else:
270
+ call(
271
+ "rm " + model,
272
+ shell=True,
273
+ stdout=open("/dev/null", "w"),
274
+ stderr=open("/dev/null", "w"),
275
+ )
276
+ print("[1;31mWrong link, check that the link is valid")
277
 
278
  else:
279
  if Original_Model_Version == "v1.5":
280
+ model = "/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv1-5.ckpt"
281
+ print("[1;32mUsing the original V1.5 model")
282
  elif Original_Model_Version == "v2-512":
283
+ model = "/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv2-512.ckpt"
284
+ if not os.path.exists(
285
+ "/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv2-512.ckpt"
286
+ ):
287
+ print("[1;33mDownloading the V2-512 model...")
288
+ call(
289
+ "gdown -O "
290
+ + model
291
+ + " https://huggingface.co/stabilityai/stable-diffusion-2-1-base/resolve/main/v2-1_512-nonema-pruned.ckpt",
292
+ shell=True,
293
+ )
294
+ clear_output()
295
+ print("[1;32mUsing the original V2-512 model")
296
  elif Original_Model_Version == "v2-768":
297
+ model = "/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/SDv2-768.ckpt"
298
+ print("[1;32mUsing the original V2-768 model")
299
  elif Original_Model_Version == "SDXL":
300
+ model = "/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/sd_xl_base_1.0.safetensors"
301
+ print("[1;32mUsing the original SDXL model")
302
 
303
  else:
304
+ model = "/workspace/sd/stable-diffusion-webui/models/Stable-diffusion"
305
+ print("[1;31mWrong model version, try again")
306
  try:
307
  model
308
  except:
309
+ model = "/workspace/sd/stable-diffusion-webui/models/Stable-diffusion"
310
 
311
  return model
312
+
313
+
314
  def modeldwn(model_LINK):
315
 
316
+ if model_LINK == "":
317
+ print("[1;33mNothing to do")
318
  else:
319
+ os.makedirs(
320
+ "/workspace/sd/stable-diffusion-webui/models/Stable-diffusion",
321
+ exist_ok=True,
322
+ )
323
 
324
+ src = getsrc(model_LINK)
325
 
326
+ if src == "civitai":
327
+ modelname = get_name(model_LINK, False)
328
+ loramodel = f"/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}"
329
  if not os.path.exists(loramodel):
330
+ dwn(model_LINK, loramodel, "Downloading the LoRA model")
331
+ clear_output()
332
  else:
333
+ print("[1;33mModel already exists")
334
+ elif src == "gdrive":
335
+ modelname = get_true_name(model_LINK)
336
+ loramodel = f"/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}"
337
  if not os.path.exists(loramodel):
338
+ gdown.download(
339
+ url=model_LINK.replace("/file/d/", "/uc?id=").replace("/view", ""),
340
+ output=loramodel,
341
+ quiet=False,
342
+ )
343
+ clear_output()
344
  else:
345
+ print("[1;33mModel already exists")
346
  else:
347
+ modelname = os.path.basename(model_LINK)
348
+ loramodel = f"/workspace/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}"
349
  if not os.path.exists(loramodel):
350
+ gdown.download(
351
+ url=model_LINK, output=loramodel, quiet=False, fuzzy=True
352
+ )
353
+ clear_output()
354
  else:
355
+ print("[1;33mModel already exists")
356
 
357
+ if os.path.exists(loramodel):
358
+ print("[1;32mCheckpoints downloaded")
359
  else:
360
+ print("[1;31mWrong link, check that the link is valid")
361
+
362
 
363
  def loradwn(LoRA_LINK):
364
 
365
+ if LoRA_LINK == "":
366
+ print("[1;33mNothing to do")
367
  else:
368
+ os.makedirs("/workspace/sd/stable-diffusion-webui/models/Lora", exist_ok=True)
369
 
370
+ src = getsrc(LoRA_LINK)
371
 
372
+ if src == "civitai":
373
+ modelname = get_name(LoRA_LINK, False)
374
+ loramodel = f"/workspace/sd/stable-diffusion-webui/models/Lora/{modelname}"
375
  if not os.path.exists(loramodel):
376
+ dwn(LoRA_LINK, loramodel, "Downloading the LoRA model")
377
+ clear_output()
378
  else:
379
+ print("[1;33mModel already exists")
380
+ elif src == "gdrive":
381
+ modelname = get_true_name(LoRA_LINK)
382
+ loramodel = f"/workspace/sd/stable-diffusion-webui/models/Lora/{modelname}"
383
  if not os.path.exists(loramodel):
384
+ gdown.download(
385
+ url=LoRA_LINK.replace("/file/d/", "/uc?id=").replace("/view", ""),
386
+ output=loramodel,
387
+ quiet=False,
388
+ )
389
+ clear_output()
390
  else:
391
+ print("[1;33mModel already exists")
392
  else:
393
+ modelname = os.path.basename(LoRA_LINK)
394
+ loramodel = f"/workspace/sd/stable-diffusion-webui/models/Lora/{modelname}"
395
  if not os.path.exists(loramodel):
396
+ gdown.download(url=LoRA_LINK, output=loramodel, quiet=False, fuzzy=True)
397
+ clear_output()
398
  else:
399
+ print("[1;33mModel already exists")
400
 
401
+ if os.path.exists(loramodel):
402
+ print("[1;32mLoRA downloaded")
403
  else:
404
+ print("[1;31mWrong link, check that the link is valid")
405
+
406
 
407
  def download_and_install_config():
408
+ target_directory = "/workspace/sd/stable-diffusion-webui/"
409
+ config_url = (
410
+ "https://huggingface.co/spaces/stlaurentjr/RNPD/raw/main/config/config.json"
411
+ )
412
+ config_file_path = os.path.join(target_directory, "config.json")
413
+
414
  # Check if the config file already exists
415
  if not os.path.exists(config_file_path):
416
  # Change the directory
417
  os.chdir(target_directory)
418
  # Download the file using curl command
419
+ call(f"curl -o config.json {config_url}", shell=True)
420
+ print(f"Config file downloaded successfully.")
421
  else:
422
+ print("Config file already exists, download skipped.")
423
+
424
 
425
+ def InstallDeforum():
426
+ # Переход в директорию расширений
427
+ os.chdir("/workspace/sd/stable-diffusion-webui/extensions")
428
+
429
+ # Проверка наличия директории с расширением
430
  if not os.path.exists("deforum-for-automatic1111-webui"):
431
+ # Клонирование репозитория, если он не существует
432
+ call(
433
+ "git clone https://github.com/deforum-art/sd-webui-deforum.git", shell=True
434
+ )
435
+ # Возврат в корневую директорию
436
+ os.chdir("/workspace")
437
+ else:
438
+ # Если директория существует, переходим в нее
439
+ # os.chdir('deforum-for-automatic1111-webui')
440
+ # Сброс изменений и обновление репозитория
441
+ # call('git reset --hard', shell=True, stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w'))
442
+ # call('git pull', shell=True, stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w'))
443
+ # Возврат в корневую директорию
444
+ os.chdir("/workspace")
445
+
446
+
447
+ def InstallAnimateDiff():
448
+ # Переход в директорию расширений
449
+ os.chdir("/workspace/sd/stable-diffusion-webui/extensions")
450
+
451
+ # Проверка наличия директории с расширением
452
+ if not os.path.exists("sd-webui-animatediff"):
453
+ # Клонирование репозитория, если он не существует
454
+ call(
455
+ "git clone https://github.com/continue-revolution/sd-webui-animatediff.git",
456
+ shell=True,
457
+ )
458
+ # Переход в папку с моделями
459
+ os.chdir(
460
+ "/workspace/sd/stable-diffusion-webui/extensions/sd-webui-animatediff/model"
461
+ )
462
+ # Скачивание моделей для animatediff
463
+ call(
464
+ "wget https://huggingface.co/guoyww/animatediff/resolve/refs%2Fpr%2F3/mm_sd_v15_v2.ckpt",
465
+ shell=True,
466
+ )
467
+ call(
468
+ "wget https://huggingface.co/manshoety/AD_Stabilized_Motion/resolve/main/mm-Stabilized_high.pth",
469
+ shell=True,
470
+ )
471
+ # Вовзрат в корневую директорию
472
+ os.chdir("/workspace")
473
  else:
474
+ # Возврат в корневую директорию
475
+ os.chdir("/workspace")
476
+
 
477
 
478
+ def InstallWildCards():
479
  # Путь к целевой директории
480
+ target_dir = "/workspace/sd/stable-diffusion-webui/extensions/stable-diffusion-webui-wildcards/wildcards/"
481
 
482
  # Перемещаемся в директорию расширений
483
+ os.chdir("/workspace/sd/stable-diffusion-webui/extensions")
484
 
485
  if not os.path.exists("stable-diffusion-webui-wildcards"):
486
  # Клонирование репозитория, если он ещё не существует
487
+ call(
488
+ "git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui-wildcards.git",
489
+ shell=True,
490
+ )
491
+
492
  # Перемещаемся в клонированный репозиторий
493
+ os.chdir("stable-diffusion-webui-wildcards")
494
 
495
  # Скачиваем файл по ID
496
+ gdown.download(
497
+ id="1sY9Yv29cCYZuxBvszkmLVgw--aRdwT1P", output="wildcards.zip", quiet=False
498
+ )
499
 
500
  # Создаем целевую директорию, если она ещё не существует
501
  os.makedirs(target_dir, exist_ok=True)
502
 
503
  # Распаковываем архив
504
+ with zipfile.ZipFile("wildcards.zip", "r") as zip_ref:
505
  zip_ref.extractall(target_dir)
506
  else:
507
  # Если репозиторий уже существует, обновляем его
508
+ os.chdir("stable-diffusion-webui-wildcards")
509
+ call(
510
+ "git reset --hard",
511
+ shell=True,
512
+ stdout=open(os.devnull, "w"),
513
+ stderr=open(os.devnull, "w"),
514
+ )
515
+ call(
516
+ "git pull",
517
+ shell=True,
518
+ stdout=open(os.devnull, "w"),
519
+ stderr=open(os.devnull, "w"),
520
+ )
521
 
522
  # Возвращаемся в исходную рабочую директорию
523
+ os.chdir("/workspace")
524
+
525
 
526
  def CNet(ControlNet_Model, ControlNet_XL_Model):
 
527
  def download(url, model_dir):
528
 
529
  filename = os.path.basename(urlparse(url).path)
530
  pth = os.path.abspath(os.path.join(model_dir, filename))
531
  if not os.path.exists(pth):
532
+ print("Downloading: " + os.path.basename(url))
533
  download_url_to_file(url, pth, hash_prefix=None, progress=True)
534
  else:
535
+ print(f"[1;32mThe model {filename} already exists[0m")
536
 
537
+ wrngv1 = False
538
+ os.chdir("/workspace/sd/stable-diffusion-webui/extensions")
539
  if not os.path.exists("sd-webui-controlnet"):
540
+ call(
541
+ "git clone https://github.com/Mikubill/sd-webui-controlnet.git", shell=True
542
+ )
543
+ os.chdir("/workspace")
544
  else:
545
+ os.chdir("sd-webui-controlnet")
546
+ call(
547
+ "git reset --hard",
548
+ shell=True,
549
+ stdout=open("/dev/null", "w"),
550
+ stderr=open("/dev/null", "w"),
551
+ )
552
+ call(
553
+ "git pull",
554
+ shell=True,
555
+ stdout=open("/dev/null", "w"),
556
+ stderr=open("/dev/null", "w"),
557
+ )
558
+ os.chdir("/workspace")
559
+
560
+ mdldir = (
561
+ "/workspace/sd/stable-diffusion-webui/extensions/sd-webui-controlnet/models"
562
+ )
563
+ call(
564
+ "ln -s /workspace/auto-controlnet-models/* /workspace/sd/stable-diffusion-webui/extensions/sd-webui-controlnet/models",
565
+ shell=True,
566
+ )
567
 
568
  for filename in os.listdir(mdldir):
569
+ if "_sd14v1" in filename:
570
+ renamed = re.sub("_sd14v1", "-fp16", filename)
571
+ os.rename(os.path.join(mdldir, filename), os.path.join(mdldir, renamed))
572
+
573
+ call(
574
+ "wget -q -O CN_models.txt https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/CN_models.txt",
575
+ shell=True,
576
+ )
577
+ call(
578
+ "wget -q -O CN_models_XL.txt https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/CN_models_XL.txt",
579
+ shell=True,
580
+ )
581
+
582
+ with open("CN_models.txt", "r") as f:
583
  mdllnk = f.read().splitlines()
584
+ with open("CN_models_XL.txt", "r") as d:
585
  mdllnk_XL = d.read().splitlines()
586
+ call("rm CN_models.txt CN_models_XL.txt", shell=True)
 
 
587
 
588
+ os.chdir("/workspace")
589
+
590
+ if ControlNet_Model == "All" or ControlNet_Model == "all":
591
+ for lnk in mdllnk:
592
+ download(lnk, mdldir)
593
+ clear_output()
594
 
 
595
  elif ControlNet_Model == "15":
596
+ mdllnk = list(filter(lambda x: "t2i" in x, mdllnk))
597
+ for lnk in mdllnk:
598
+ download(lnk, mdldir)
599
+ clear_output()
600
 
601
+ elif (
602
+ ControlNet_Model.isdigit()
603
+ and int(ControlNet_Model) - 1 < 14
604
+ and int(ControlNet_Model) > 0
605
+ ):
606
+ download(mdllnk[int(ControlNet_Model) - 1], mdldir)
607
+ clear_output()
608
 
 
 
 
 
609
  elif ControlNet_Model == "none":
610
+ pass
611
+ clear_output()
612
 
613
  else:
614
+ print("[1;31mWrong ControlNet V1 choice, try again")
615
+ wrngv1 = True
616
 
617
+ if ControlNet_XL_Model == "All" or ControlNet_XL_Model == "all":
618
+ for lnk_XL in mdllnk_XL:
619
+ download(lnk_XL, mdldir)
620
+ if not wrngv1:
621
+ clear_output()
622
+ done()
623
 
624
+ elif ControlNet_XL_Model.isdigit() and int(ControlNet_XL_Model) - 1 < 5:
625
+ download(mdllnk_XL[int(ControlNet_XL_Model) - 1], mdldir)
626
+ if not wrngv1:
627
+ clear_output()
628
+ done()
 
629
 
 
 
 
 
 
 
630
  elif ControlNet_XL_Model == "none":
631
+ pass
632
+ if not wrngv1:
633
+ clear_output()
634
+ done()
635
 
636
  else:
637
+ print("[1;31mWrong ControlNet XL choice, try again")
 
638
 
639
 
640
  def sd(User, Password, model):
641
 
642
  import gradio
643
+
644
  gradio.close_all()
645
+
646
+ auth = f"--gradio-auth {User}:{Password}"
647
+ if User == "" or Password == "":
648
+ auth = ""
649
+
650
+ call(
651
+ "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",
652
+ shell=True,
653
+ )
654
+
655
+ os.chdir("/workspace/sd/stable-diffusion-webui/modules")
656
+
657
+ call(
658
+ "sed -i 's@possible_sd_paths =.*@possible_sd_paths = [\"/workspace/sd/stablediffusion\"]@' /workspace/sd/stable-diffusion-webui/modules/paths.py",
659
+ shell=True,
660
+ )
661
+ call(
662
+ "sed -i 's@\.\.\/@src/@g' /workspace/sd/stable-diffusion-webui/modules/paths.py",
663
+ shell=True,
664
+ )
665
+ call(
666
+ "sed -i 's@src\/generative-models@generative-models@g' /workspace/sd/stable-diffusion-webui/modules/paths.py",
667
+ shell=True,
668
+ )
669
+
670
+ call(
671
+ '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',
672
+ shell=True,
673
+ )
674
+
675
+ call(
676
+ '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',
677
+ shell=True,
678
+ )
679
+
680
+ call(
681
+ 'sed -i \'s/"CLIP_stop_at_last_layers": 1/"CLIP_stop_at_last_layers": 2/g\' /workspace/sd/stable-diffusion-webui/config.json',
682
+ shell=True,
683
+ )
684
+
685
+ call(
686
+ "sed -i 's@print(\"No module.*@@' /workspace/sd/stablediffusion/ldm/modules/diffusionmodules/model.py",
687
+ shell=True,
688
+ )
689
+
690
+ os.chdir("/workspace/sd/stable-diffusion-webui")
691
  clear_output()
692
 
693
+ podid = os.environ.get("RUNPOD_POD_ID")
694
+ localurl = f"{podid}-3001.proxy.runpod.net"
695
+
696
+ for line in fileinput.input(
697
+ "/usr/local/lib/python3.10/dist-packages/gradio/blocks.py", inplace=True
698
+ ):
699
+ if line.strip().startswith("self.server_name ="):
700
+ line = f' self.server_name = "{localurl}"\n'
701
+ if line.strip().startswith('self.protocol = "https"'):
702
+ line = ' self.protocol = "https"\n'
703
+ if line.strip().startswith(
704
+ 'if self.local_url.startswith("https") or self.is_colab'
705
+ ):
706
+ line = ""
707
+ if line.strip().startswith('else "http"'):
708
+ line = ""
709
+ sys.stdout.write(line)
710
+
711
+ if model == "":
712
+ mdlpth = ""
713
  else:
714
  if os.path.isfile(model):
715
+ mdlpth = "--ckpt " + model
716
  else:
717
+ mdlpth = "--ckpt-dir " + model
718
  vae_path = "--vae-path /workspace/sd/stable-diffusion-webui/models/VAE/vae-ft-mse-840000-ema-pruned.safetensors"
719
+ configf = (
720
+ "--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 "
721
+ + auth
722
+ + " "
723
+ + mdlpth
724
+ + " "
725
+ + vae_path
726
+ )
727
 
728
  return configf
729
 
730
 
 
731
  def save(Huggingface_Write_token):
732
+
733
  from slugify import slugify
734
  from huggingface_hub import HfApi, CommitOperationAdd, create_repo
735
+
736
+ if Huggingface_Write_token == "":
737
+ print("[1;31mA huggingface write token is required")
738
+
739
  else:
740
+ os.chdir("/workspace")
741
+
742
+ if os.path.exists("sd"):
743
+
744
+ call(
745
+ 'tar --exclude="stable-diffusion-webui/models/*/*" --exclude="sd-webui-controlnet/models/*" --zstd -cf sd_backup_rnpd.tar.zst sd',
746
+ shell=True,
747
+ )
748
  api = HfApi()
749
  username = api.whoami(token=Huggingface_Write_token)["name"]
750
 
751
  repo_id = f"{username}/{slugify('fast-stable-diffusion')}"
752
 
753
+ print("[1;32mBacking up...")
754
+
755
+ operations = [
756
+ CommitOperationAdd(
757
+ path_in_repo="sd_backup_rnpd.tar.zst",
758
+ path_or_fileobj="/workspace/sd_backup_rnpd.tar.zst",
759
+ )
760
+ ]
761
+
762
+ create_repo(
763
+ repo_id,
764
+ private=True,
765
+ token=Huggingface_Write_token,
766
+ exist_ok=True,
767
+ repo_type="dataset",
768
+ )
769
 
770
  api.create_commit(
771
+ repo_id=repo_id,
772
+ repo_type="dataset",
773
+ operations=operations,
774
+ commit_message="SD folder Backup",
775
+ token=Huggingface_Write_token,
776
  )
777
 
778
+ call("rm sd_backup_rnpd.tar.zst", shell=True)
779
  clear_output()
780
 
781
  done()
 
 
 
 
782
 
783
+ else:
784
+ print("[1;33mNothing to backup")
785
 
786
 
787
  def getsrc(url):
788
 
789
  parsed_url = urlparse(url)
790
+
791
+ if parsed_url.netloc == "civitai.com":
792
+ src = "civitai"
793
+ elif parsed_url.netloc == "drive.google.com":
794
+ src = "gdrive"
795
+ elif parsed_url.netloc == "huggingface.co":
796
+ src = "huggingface"
797
  else:
798
+ src = "others"
799
  return src
800
 
801
+
802
  def get_true_name(url):
803
  response = requests.get(url)
804
+ soup = BeautifulSoup(response.text, "html.parser")
805
+ title_tag = soup.find("title")
806
  if title_tag:
807
  title_text = title_tag.text
808
  # Извлечение имени файла из тега title (предполагая, что имя файла указано в теге title)
809
+ file_name = title_text.split(" - ")[0]
810
  return file_name
811
  else:
812
+ raise RuntimeError("Could not find the title tag in the HTML")
813
+
814
 
815
  def get_name(url, gdrive):
816
 
 
825
  disp_val = quer["response-content-disposition"][0].split(";")
826
  for vals in disp_val:
827
  if vals.strip().startswith("filename="):
828
+ filenm = unquote(vals.split("=", 1)[1].strip())
829
+ return filenm.replace('"', "")
830
  else:
831
+ headers = {
832
+ "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"
833
+ }
834
+ lnk = "https://drive.google.com/uc?id={id}&export=download".format(
835
+ id=url[url.find("/d/") + 3 : url.find("/view")]
836
+ )
837
  res = requests.session().get(lnk, headers=headers, stream=True, verify=True)
838
+ res = requests.session().get(
839
+ get_url_from_gdrive_confirmation(res.text),
840
+ headers=headers,
841
+ stream=True,
842
+ verify=True,
843
+ )
844
+ content_disposition = six.moves.urllib_parse.unquote(
845
+ res.headers["Content-Disposition"]
846
+ )
847
+ filenm = (
848
+ re.search(r"filename\*=UTF-8''(.*)", content_disposition)
849
+ .groups()[0]
850
+ .replace(os.path.sep, "_")
851
+ )
852
+ return filenm
853
 
854
 
855
  def done():
856
  done = widgets.Button(
857
+ description="Done!",
858
  disabled=True,
859
+ button_style="success",
860
+ tooltip="",
861
+ icon="check",
862
  )
863
+ display(done)