John6666 commited on
Commit
0f865da
1 Parent(s): c692b1c

Upload 3 files

Browse files
Files changed (3) hide show
  1. dc.py +145 -138
  2. env.py +10 -3
  3. modutils.py +30 -8
dc.py CHANGED
@@ -1,12 +1,11 @@
1
  import spaces
2
  import os
3
  from stablepy import Model_Diffusers
4
- from stablepy.diffusers_vanilla.model import scheduler_names
5
  from stablepy.diffusers_vanilla.style_prompt_config import STYLE_NAMES
 
6
  import torch
7
  import re
8
- import shutil
9
- import random
10
  from stablepy import (
11
  CONTROLNET_MODEL_IDS,
12
  VALID_TASKS,
@@ -22,7 +21,7 @@ from stablepy import (
22
  SD15_TASKS,
23
  SDXL_TASKS,
24
  )
25
- import urllib.parse
26
  import gradio as gr
27
  from PIL import Image
28
  import IPython.display
@@ -40,7 +39,7 @@ from stablepy import logger
40
  logger.setLevel(logging.CRITICAL)
41
 
42
  from env import (
43
- hf_token, hf_read_token, # to use only for private repos
44
  CIVITAI_API_KEY, HF_LORA_PRIVATE_REPOS1, HF_LORA_PRIVATE_REPOS2,
45
  HF_LORA_ESSENTIAL_PRIVATE_REPO, HF_VAE_PRIVATE_REPO,
46
  HF_SDXL_EMBEDS_NEGATIVE_PRIVATE_REPO, HF_SDXL_EMBEDS_POSITIVE_PRIVATE_REPO,
@@ -49,7 +48,7 @@ from env import (
49
  load_diffusers_format_model, download_model_list, download_lora_list,
50
  download_vae_list, download_embeds)
51
 
52
- preprocessor_controlnet = {
53
  "openpose": [
54
  "Openpose",
55
  "None",
@@ -86,6 +85,13 @@ preprocessor_controlnet = {
86
  "None",
87
  "None (anime)",
88
  ],
 
 
 
 
 
 
 
89
  "shuffle": [
90
  "ContentShuffle",
91
  "None",
@@ -114,7 +120,7 @@ preprocessor_controlnet = {
114
  ],
115
  }
116
 
117
- task_stablepy = {
118
  'txt2img': 'txt2img',
119
  'img2img': 'img2img',
120
  'inpaint': 'inpaint',
@@ -140,7 +146,35 @@ task_stablepy = {
140
  'tile ControlNet': 'tile',
141
  }
142
 
143
- task_model_list = list(task_stablepy.keys())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
  def download_things(directory, url, hf_token="", civitai_api_key=""):
146
  url = url.strip()
@@ -171,21 +205,19 @@ def download_things(directory, url, hf_token="", civitai_api_key=""):
171
  else:
172
  os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
173
 
174
-
175
  def get_model_list(directory_path):
176
  model_list = []
177
  valid_extensions = {'.ckpt', '.pt', '.pth', '.safetensors', '.bin'}
178
 
179
  for filename in os.listdir(directory_path):
180
  if os.path.splitext(filename)[1] in valid_extensions:
181
- name_without_extension = os.path.splitext(filename)[0]
182
  file_path = os.path.join(directory_path, filename)
183
  # model_list.append((name_without_extension, file_path))
184
  model_list.append(file_path)
185
  print('\033[34mFILE: ' + file_path + '\033[0m')
186
  return model_list
187
 
188
-
189
  ## BEGIN MOD
190
  from modutils import (to_list, list_uniq, list_sub, get_model_id_list, get_tupled_embed_list,
191
  get_tupled_model_list, get_lora_model_list, download_private_repo)
@@ -203,24 +235,21 @@ download_private_repo(HF_VAE_PRIVATE_REPO, directory_vaes, False)
203
  load_diffusers_format_model = list_uniq(load_diffusers_format_model + get_model_id_list())
204
  ## END MOD
205
 
206
- CIVITAI_API_KEY = os.environ.get("CIVITAI_API_KEY")
207
- hf_token = os.environ.get("HF_TOKEN")
208
-
209
  # Download stuffs
210
  for url in [url.strip() for url in download_model.split(',')]:
211
  if not os.path.exists(f"./models/{url.split('/')[-1]}"):
212
- download_things(directory_models, url, hf_token, CIVITAI_API_KEY)
213
  for url in [url.strip() for url in download_vae.split(',')]:
214
  if not os.path.exists(f"./vaes/{url.split('/')[-1]}"):
215
- download_things(directory_vaes, url, hf_token, CIVITAI_API_KEY)
216
  for url in [url.strip() for url in download_lora.split(',')]:
217
  if not os.path.exists(f"./loras/{url.split('/')[-1]}"):
218
- download_things(directory_loras, url, hf_token, CIVITAI_API_KEY)
219
 
220
  # Download Embeddings
221
  for url_embed in download_embeds:
222
  if not os.path.exists(f"./embedings/{url_embed.split('/')[-1]}"):
223
- download_things(directory_embeds, url_embed, hf_token, CIVITAI_API_KEY)
224
 
225
  # Build list models
226
  embed_list = get_model_list(directory_embeds)
@@ -237,53 +266,45 @@ embed_sdxl_list = get_model_list(directory_embeds_sdxl) + get_model_list(directo
237
 
238
  def get_embed_list(pipeline_name):
239
  return get_tupled_embed_list(embed_sdxl_list if pipeline_name == "StableDiffusionXLPipeline" else embed_list)
240
-
241
-
242
  ## END MOD
243
 
244
  print('\033[33m🏁 Download and listing of valid models completed.\033[0m')
245
 
246
- upscaler_dict_gui = {
247
- None: None,
248
- "Lanczos": "Lanczos",
249
- "Nearest": "Nearest",
250
- 'Latent': 'Latent',
251
- 'Latent (antialiased)': 'Latent (antialiased)',
252
- 'Latent (bicubic)': 'Latent (bicubic)',
253
- 'Latent (bicubic antialiased)': 'Latent (bicubic antialiased)',
254
- 'Latent (nearest)': 'Latent (nearest)',
255
- 'Latent (nearest-exact)': 'Latent (nearest-exact)',
256
- "RealESRGAN_x4plus" : "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",
257
- "RealESRNet_x4plus" : "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth",
258
- "RealESRGAN_x4plus_anime_6B": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth",
259
- "RealESRGAN_x2plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth",
260
- "realesr-animevideov3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth",
261
- "realesr-general-x4v3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth",
262
- "realesr-general-wdn-x4v3" : "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth",
263
- "4x-UltraSharp" : "https://huggingface.co/Shandypur/ESRGAN-4x-UltraSharp/resolve/main/4x-UltraSharp.pth",
264
- "4x_foolhardy_Remacri" : "https://huggingface.co/FacehugmanIII/4x_foolhardy_Remacri/resolve/main/4x_foolhardy_Remacri.pth",
265
- "Remacri4xExtraSmoother" : "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/Remacri%204x%20ExtraSmoother.pth",
266
- "AnimeSharp4x" : "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/AnimeSharp%204x.pth",
267
- "lollypop" : "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/lollypop.pth",
268
- "RealisticRescaler4x" : "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/RealisticRescaler%204x.pth",
269
- "NickelbackFS4x" : "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/NickelbackFS%204x.pth"
270
  }
271
 
272
- upscaler_keys = list(upscaler_dict_gui.keys())
 
 
 
 
273
 
 
274
 
275
  def extract_parameters(input_string):
276
  parameters = {}
277
  input_string = input_string.replace("\n", "")
278
 
279
- if not "Negative prompt:" in input_string:
280
  print("Negative prompt not detected")
281
  parameters["prompt"] = input_string
282
  return parameters
283
 
284
  parm = input_string.split("Negative prompt:")
285
  parameters["prompt"] = parm[0]
286
- if not "Steps:" in parm[1]:
287
  print("Steps not detected")
288
  parameters["neg_prompt"] = parm[1]
289
  return parameters
@@ -311,6 +332,17 @@ def extract_parameters(input_string):
311
 
312
  return parameters
313
 
 
 
 
 
 
 
 
 
 
 
 
314
 
315
  ## BEGIN MOD
316
  class GuiSD:
@@ -319,12 +351,12 @@ class GuiSD:
319
 
320
  print("Loading model...")
321
  self.model = Model_Diffusers(
322
- base_model_id="cagliostrolab/animagine-xl-3.1",
323
  task_name="txt2img",
324
  vae_model=None,
325
  type_model_precision=torch.float16,
326
  retain_task_model_in_cache=False,
327
- #device="cpu",
328
  )
329
  self.model.device = torch.device("cpu") #
330
 
@@ -344,28 +376,27 @@ class GuiSD:
344
  yield f"Loading model: {model_name}"
345
 
346
  vae_model = vae_model if vae_model != "None" else None
 
347
 
348
- if model_name in model_list:
349
- model_is_xl = "xl" in model_name.lower()
350
- sdxl_in_vae = vae_model and "sdxl" in vae_model.lower()
351
- model_type = "SDXL" if model_is_xl else "SD 1.5"
352
- incompatible_vae = (model_is_xl and vae_model and not sdxl_in_vae) or (not model_is_xl and sdxl_in_vae)
353
-
354
- if incompatible_vae:
355
- vae_model = None
356
 
357
  self.model.device = torch.device("cpu")
 
358
 
359
  self.model.load_pipe(
360
  model_name,
361
- task_name=task_stablepy[task],
362
  vae_model=vae_model if vae_model != "None" else None,
363
- type_model_precision=torch.float16,
364
  retain_task_model_in_cache=False,
365
  )
366
  yield f"Model loaded: {model_name}"
367
 
368
  @spaces.GPU
 
369
  def generate_pipeline(
370
  self,
371
  prompt,
@@ -479,38 +510,15 @@ class GuiSD:
479
  vae_msg = f"VAE: {vae_model}" if vae_model else ""
480
  msg_lora = []
481
 
 
 
482
  ## BEGIN MOD
483
  prompt, neg_prompt = insert_model_recom_prompt(prompt, neg_prompt, model_name)
484
  global lora_model_list
485
  lora_model_list = get_lora_model_list()
486
  ## END MOD
487
 
488
- if model_name in model_list:
489
- model_is_xl = "xl" in model_name.lower()
490
- sdxl_in_vae = vae_model and "sdxl" in vae_model.lower()
491
- model_type = "SDXL" if model_is_xl else "SD 1.5"
492
- incompatible_vae = (model_is_xl and vae_model and not sdxl_in_vae) or (not model_is_xl and sdxl_in_vae)
493
-
494
- if incompatible_vae:
495
- msg_inc_vae = (
496
- f"The selected VAE is for a { 'SD 1.5' if model_is_xl else 'SDXL' } model, but you"
497
- f" are using a { model_type } model. The default VAE "
498
- "will be used."
499
- )
500
- gr.Info(msg_inc_vae)
501
- vae_msg = msg_inc_vae
502
- vae_model = None
503
-
504
- for la in loras_list:
505
- if la is not None and la != "None" and la in lora_model_list:
506
- print(la)
507
- lora_type = ("animetarot" in la.lower() or "Hyper-SD15-8steps".lower() in la.lower())
508
- if (model_is_xl and lora_type) or (not model_is_xl and not lora_type):
509
- msg_inc_lora = f"The LoRA {la} is for { 'SD 1.5' if model_is_xl else 'SDXL' }, but you are using { model_type }."
510
- gr.Info(msg_inc_lora)
511
- msg_lora.append(msg_inc_lora)
512
-
513
- task = task_stablepy[task]
514
 
515
  params_ip_img = []
516
  params_ip_msk = []
@@ -532,83 +540,53 @@ class GuiSD:
532
  params_ip_mode.append(modeip)
533
  params_ip_scale.append(scaleip)
534
 
535
- # First load
536
- self.model.device = torch.device("cuda:0")
537
- model_precision = torch.float16
538
- if not self.model:
539
- from stablepy import Model_Diffusers
540
-
541
- print("Loading model...")
542
- self.model = Model_Diffusers(
543
- base_model_id=model_name,
544
- task_name=task,
545
- vae_model=vae_model if vae_model != "None" else None,
546
- type_model_precision=model_precision,
547
- retain_task_model_in_cache=retain_task_cache_gui,
548
- )
549
-
550
  if task != "txt2img" and not image_control:
551
  raise ValueError("No control image found: To use this function, you have to upload an image in 'Image ControlNet/Inpaint/Img2img'")
552
 
553
  if task == "inpaint" and not image_mask:
554
  raise ValueError("No mask image found: Specify one in 'Image Mask'")
555
 
556
- if upscaler_model_path in upscaler_keys[:9]:
557
  upscaler_model = upscaler_model_path
558
  else:
559
  directory_upscalers = 'upscalers'
560
  os.makedirs(directory_upscalers, exist_ok=True)
561
 
562
- url_upscaler = upscaler_dict_gui[upscaler_model_path]
563
 
564
  if not os.path.exists(f"./upscalers/{url_upscaler.split('/')[-1]}"):
565
- download_things(directory_upscalers, url_upscaler, hf_token)
566
 
567
  upscaler_model = f"./upscalers/{url_upscaler.split('/')[-1]}"
568
 
569
  logging.getLogger("ultralytics").setLevel(logging.INFO if adetailer_verbose else logging.ERROR)
570
 
571
- print("Config model:", model_name, vae_model, loras_list)
572
-
573
- self.model.load_pipe(
574
- model_name,
575
- task_name=task,
576
- vae_model=vae_model if vae_model != "None" else None,
577
- type_model_precision=model_precision,
578
- retain_task_model_in_cache=retain_task_cache_gui,
579
- )
580
-
581
- ## BEGIN MOD
582
- # if textual_inversion and self.model.class_name == "StableDiffusionXLPipeline":
583
- # print("No Textual inversion for SDXL")
584
- ## END MOD
585
-
586
  adetailer_params_A = {
587
- "face_detector_ad" : face_detector_ad_a,
588
- "person_detector_ad" : person_detector_ad_a,
589
- "hand_detector_ad" : hand_detector_ad_a,
590
  "prompt": prompt_ad_a,
591
- "negative_prompt" : negative_prompt_ad_a,
592
- "strength" : strength_ad_a,
593
  # "image_list_task" : None,
594
- "mask_dilation" : mask_dilation_a,
595
- "mask_blur" : mask_blur_a,
596
- "mask_padding" : mask_padding_a,
597
- "inpaint_only" : adetailer_inpaint_only,
598
- "sampler" : adetailer_sampler,
599
  }
600
 
601
  adetailer_params_B = {
602
- "face_detector_ad" : face_detector_ad_b,
603
- "person_detector_ad" : person_detector_ad_b,
604
- "hand_detector_ad" : hand_detector_ad_b,
605
  "prompt": prompt_ad_b,
606
- "negative_prompt" : negative_prompt_ad_b,
607
- "strength" : strength_ad_b,
608
  # "image_list_task" : None,
609
- "mask_dilation" : mask_dilation_b,
610
- "mask_blur" : mask_blur_b,
611
- "mask_padding" : mask_padding_b,
612
  }
613
  pipe_params = {
614
  "prompt": prompt,
@@ -690,8 +668,10 @@ class GuiSD:
690
  "ip_adapter_scale": params_ip_scale,
691
  }
692
 
693
- # Maybe fix lora issue: 'Cannot copy out of meta tensor; no data!''
694
- #self.model.pipe.to("cuda:0" if torch.cuda.is_available() else "cpu")
 
 
695
 
696
  progress(1, desc="Inference preparation completed. Starting inference...")
697
 
@@ -699,8 +679,35 @@ class GuiSD:
699
  return self.infer_short(self.model, pipe_params, progress), info_state
700
  ## END MOD
701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
702
 
703
  from pathlib import Path
 
704
  from modutils import (safe_float, escape_lora_basename, to_lora_key, to_lora_path,
705
  get_local_model_list, get_private_lora_model_lists, get_valid_lora_name,
706
  get_valid_lora_path, get_valid_lora_wt, get_lora_info,
 
1
  import spaces
2
  import os
3
  from stablepy import Model_Diffusers
 
4
  from stablepy.diffusers_vanilla.style_prompt_config import STYLE_NAMES
5
+ from stablepy.diffusers_vanilla.constants import FLUX_CN_UNION_MODES
6
  import torch
7
  import re
8
+ from huggingface_hub import HfApi
 
9
  from stablepy import (
10
  CONTROLNET_MODEL_IDS,
11
  VALID_TASKS,
 
21
  SD15_TASKS,
22
  SDXL_TASKS,
23
  )
24
+ #import urllib.parse
25
  import gradio as gr
26
  from PIL import Image
27
  import IPython.display
 
39
  logger.setLevel(logging.CRITICAL)
40
 
41
  from env import (
42
+ HF_TOKEN, hf_read_token, # to use only for private repos
43
  CIVITAI_API_KEY, HF_LORA_PRIVATE_REPOS1, HF_LORA_PRIVATE_REPOS2,
44
  HF_LORA_ESSENTIAL_PRIVATE_REPO, HF_VAE_PRIVATE_REPO,
45
  HF_SDXL_EMBEDS_NEGATIVE_PRIVATE_REPO, HF_SDXL_EMBEDS_POSITIVE_PRIVATE_REPO,
 
48
  load_diffusers_format_model, download_model_list, download_lora_list,
49
  download_vae_list, download_embeds)
50
 
51
+ PREPROCESSOR_CONTROLNET = {
52
  "openpose": [
53
  "Openpose",
54
  "None",
 
85
  "None",
86
  "None (anime)",
87
  ],
88
+ "lineart_anime": [
89
+ "Lineart",
90
+ "Lineart coarse",
91
+ "Lineart (anime)",
92
+ "None",
93
+ "None (anime)",
94
+ ],
95
  "shuffle": [
96
  "ContentShuffle",
97
  "None",
 
120
  ],
121
  }
122
 
123
+ TASK_STABLEPY = {
124
  'txt2img': 'txt2img',
125
  'img2img': 'img2img',
126
  'inpaint': 'inpaint',
 
146
  'tile ControlNet': 'tile',
147
  }
148
 
149
+ TASK_MODEL_LIST = list(TASK_STABLEPY.keys())
150
+
151
+ UPSCALER_DICT_GUI = {
152
+ None: None,
153
+ "Lanczos": "Lanczos",
154
+ "Nearest": "Nearest",
155
+ 'Latent': 'Latent',
156
+ 'Latent (antialiased)': 'Latent (antialiased)',
157
+ 'Latent (bicubic)': 'Latent (bicubic)',
158
+ 'Latent (bicubic antialiased)': 'Latent (bicubic antialiased)',
159
+ 'Latent (nearest)': 'Latent (nearest)',
160
+ 'Latent (nearest-exact)': 'Latent (nearest-exact)',
161
+ "RealESRGAN_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",
162
+ "RealESRNet_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth",
163
+ "RealESRGAN_x4plus_anime_6B": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth",
164
+ "RealESRGAN_x2plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth",
165
+ "realesr-animevideov3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth",
166
+ "realesr-general-x4v3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth",
167
+ "realesr-general-wdn-x4v3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth",
168
+ "4x-UltraSharp": "https://huggingface.co/Shandypur/ESRGAN-4x-UltraSharp/resolve/main/4x-UltraSharp.pth",
169
+ "4x_foolhardy_Remacri": "https://huggingface.co/FacehugmanIII/4x_foolhardy_Remacri/resolve/main/4x_foolhardy_Remacri.pth",
170
+ "Remacri4xExtraSmoother": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/Remacri%204x%20ExtraSmoother.pth",
171
+ "AnimeSharp4x": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/AnimeSharp%204x.pth",
172
+ "lollypop": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/lollypop.pth",
173
+ "RealisticRescaler4x": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/RealisticRescaler%204x.pth",
174
+ "NickelbackFS4x": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/NickelbackFS%204x.pth"
175
+ }
176
+
177
+ UPSCALER_KEYS = list(UPSCALER_DICT_GUI.keys())
178
 
179
  def download_things(directory, url, hf_token="", civitai_api_key=""):
180
  url = url.strip()
 
205
  else:
206
  os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
207
 
 
208
  def get_model_list(directory_path):
209
  model_list = []
210
  valid_extensions = {'.ckpt', '.pt', '.pth', '.safetensors', '.bin'}
211
 
212
  for filename in os.listdir(directory_path):
213
  if os.path.splitext(filename)[1] in valid_extensions:
214
+ # name_without_extension = os.path.splitext(filename)[0]
215
  file_path = os.path.join(directory_path, filename)
216
  # model_list.append((name_without_extension, file_path))
217
  model_list.append(file_path)
218
  print('\033[34mFILE: ' + file_path + '\033[0m')
219
  return model_list
220
 
 
221
  ## BEGIN MOD
222
  from modutils import (to_list, list_uniq, list_sub, get_model_id_list, get_tupled_embed_list,
223
  get_tupled_model_list, get_lora_model_list, download_private_repo)
 
235
  load_diffusers_format_model = list_uniq(load_diffusers_format_model + get_model_id_list())
236
  ## END MOD
237
 
 
 
 
238
  # Download stuffs
239
  for url in [url.strip() for url in download_model.split(',')]:
240
  if not os.path.exists(f"./models/{url.split('/')[-1]}"):
241
+ download_things(directory_models, url, HF_TOKEN, CIVITAI_API_KEY)
242
  for url in [url.strip() for url in download_vae.split(',')]:
243
  if not os.path.exists(f"./vaes/{url.split('/')[-1]}"):
244
+ download_things(directory_vaes, url, HF_TOKEN, CIVITAI_API_KEY)
245
  for url in [url.strip() for url in download_lora.split(',')]:
246
  if not os.path.exists(f"./loras/{url.split('/')[-1]}"):
247
+ download_things(directory_loras, url, HF_TOKEN, CIVITAI_API_KEY)
248
 
249
  # Download Embeddings
250
  for url_embed in download_embeds:
251
  if not os.path.exists(f"./embedings/{url_embed.split('/')[-1]}"):
252
+ download_things(directory_embeds, url_embed, HF_TOKEN, CIVITAI_API_KEY)
253
 
254
  # Build list models
255
  embed_list = get_model_list(directory_embeds)
 
266
 
267
  def get_embed_list(pipeline_name):
268
  return get_tupled_embed_list(embed_sdxl_list if pipeline_name == "StableDiffusionXLPipeline" else embed_list)
 
 
269
  ## END MOD
270
 
271
  print('\033[33m🏁 Download and listing of valid models completed.\033[0m')
272
 
273
+ msg_inc_vae = (
274
+ "Use the right VAE for your model to maintain image quality. The wrong"
275
+ " VAE can lead to poor results, like blurriness in the generated images."
276
+ )
277
+
278
+ SDXL_TASK = [k for k, v in TASK_STABLEPY.items() if v in SDXL_TASKS]
279
+ SD_TASK = [k for k, v in TASK_STABLEPY.items() if v in SD15_TASKS]
280
+ FLUX_TASK = list(TASK_STABLEPY.keys())[:3] + [k for k, v in TASK_STABLEPY.items() if v in FLUX_CN_UNION_MODES.keys()]
281
+
282
+ MODEL_TYPE_TASK = {
283
+ "SD 1.5": SD_TASK,
284
+ "SDXL": SDXL_TASK,
285
+ "FLUX": FLUX_TASK,
 
 
 
 
 
 
 
 
 
 
 
286
  }
287
 
288
+ MODEL_TYPE_CLASS = {
289
+ "diffusers:StableDiffusionPipeline": "SD 1.5",
290
+ "diffusers:StableDiffusionXLPipeline": "SDXL",
291
+ "diffusers:FluxPipeline": "FLUX",
292
+ }
293
 
294
+ POST_PROCESSING_SAMPLER = ["Use same sampler"] + scheduler_names[:-2]
295
 
296
  def extract_parameters(input_string):
297
  parameters = {}
298
  input_string = input_string.replace("\n", "")
299
 
300
+ if "Negative prompt:" not in input_string:
301
  print("Negative prompt not detected")
302
  parameters["prompt"] = input_string
303
  return parameters
304
 
305
  parm = input_string.split("Negative prompt:")
306
  parameters["prompt"] = parm[0]
307
+ if "Steps:" not in parm[1]:
308
  print("Steps not detected")
309
  parameters["neg_prompt"] = parm[1]
310
  return parameters
 
332
 
333
  return parameters
334
 
335
+ def get_model_type(repo_id: str):
336
+ api = HfApi(token=os.environ.get("HF_TOKEN")) # if use private or gated model
337
+ default = "SD 1.5"
338
+ try:
339
+ model = api.model_info(repo_id=repo_id, timeout=5.0)
340
+ tags = model.tags
341
+ for tag in tags:
342
+ if tag in MODEL_TYPE_CLASS.keys(): return MODEL_TYPE_CLASS.get(tag, default)
343
+ except Exception:
344
+ return default
345
+ return default
346
 
347
  ## BEGIN MOD
348
  class GuiSD:
 
351
 
352
  print("Loading model...")
353
  self.model = Model_Diffusers(
354
+ base_model_id="Lykon/dreamshaper-8",
355
  task_name="txt2img",
356
  vae_model=None,
357
  type_model_precision=torch.float16,
358
  retain_task_model_in_cache=False,
359
+ device="cpu",
360
  )
361
  self.model.device = torch.device("cpu") #
362
 
 
376
  yield f"Loading model: {model_name}"
377
 
378
  vae_model = vae_model if vae_model != "None" else None
379
+ model_type = get_model_type(model_name)
380
 
381
+ if vae_model:
382
+ vae_type = "SDXL" if "sdxl" in vae_model.lower() else "SD 1.5"
383
+ if model_type != vae_type:
384
+ gr.Info(msg_inc_vae)
 
 
 
 
385
 
386
  self.model.device = torch.device("cpu")
387
+ dtype_model = torch.bfloat16 if model_type == "FLUX" else torch.float16
388
 
389
  self.model.load_pipe(
390
  model_name,
391
+ task_name=TASK_STABLEPY[task],
392
  vae_model=vae_model if vae_model != "None" else None,
393
+ type_model_precision=dtype_model,
394
  retain_task_model_in_cache=False,
395
  )
396
  yield f"Model loaded: {model_name}"
397
 
398
  @spaces.GPU
399
+ @torch.inference_mode()
400
  def generate_pipeline(
401
  self,
402
  prompt,
 
510
  vae_msg = f"VAE: {vae_model}" if vae_model else ""
511
  msg_lora = []
512
 
513
+ print("Config model:", model_name, vae_model, loras_list)
514
+
515
  ## BEGIN MOD
516
  prompt, neg_prompt = insert_model_recom_prompt(prompt, neg_prompt, model_name)
517
  global lora_model_list
518
  lora_model_list = get_lora_model_list()
519
  ## END MOD
520
 
521
+ task = TASK_STABLEPY[task]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
522
 
523
  params_ip_img = []
524
  params_ip_msk = []
 
540
  params_ip_mode.append(modeip)
541
  params_ip_scale.append(scaleip)
542
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
543
  if task != "txt2img" and not image_control:
544
  raise ValueError("No control image found: To use this function, you have to upload an image in 'Image ControlNet/Inpaint/Img2img'")
545
 
546
  if task == "inpaint" and not image_mask:
547
  raise ValueError("No mask image found: Specify one in 'Image Mask'")
548
 
549
+ if upscaler_model_path in UPSCALER_KEYS[:9]:
550
  upscaler_model = upscaler_model_path
551
  else:
552
  directory_upscalers = 'upscalers'
553
  os.makedirs(directory_upscalers, exist_ok=True)
554
 
555
+ url_upscaler = UPSCALER_DICT_GUI[upscaler_model_path]
556
 
557
  if not os.path.exists(f"./upscalers/{url_upscaler.split('/')[-1]}"):
558
+ download_things(directory_upscalers, url_upscaler, HF_TOKEN)
559
 
560
  upscaler_model = f"./upscalers/{url_upscaler.split('/')[-1]}"
561
 
562
  logging.getLogger("ultralytics").setLevel(logging.INFO if adetailer_verbose else logging.ERROR)
563
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
564
  adetailer_params_A = {
565
+ "face_detector_ad": face_detector_ad_a,
566
+ "person_detector_ad": person_detector_ad_a,
567
+ "hand_detector_ad": hand_detector_ad_a,
568
  "prompt": prompt_ad_a,
569
+ "negative_prompt": negative_prompt_ad_a,
570
+ "strength": strength_ad_a,
571
  # "image_list_task" : None,
572
+ "mask_dilation": mask_dilation_a,
573
+ "mask_blur": mask_blur_a,
574
+ "mask_padding": mask_padding_a,
575
+ "inpaint_only": adetailer_inpaint_only,
576
+ "sampler": adetailer_sampler,
577
  }
578
 
579
  adetailer_params_B = {
580
+ "face_detector_ad": face_detector_ad_b,
581
+ "person_detector_ad": person_detector_ad_b,
582
+ "hand_detector_ad": hand_detector_ad_b,
583
  "prompt": prompt_ad_b,
584
+ "negative_prompt": negative_prompt_ad_b,
585
+ "strength": strength_ad_b,
586
  # "image_list_task" : None,
587
+ "mask_dilation": mask_dilation_b,
588
+ "mask_blur": mask_blur_b,
589
+ "mask_padding": mask_padding_b,
590
  }
591
  pipe_params = {
592
  "prompt": prompt,
 
668
  "ip_adapter_scale": params_ip_scale,
669
  }
670
 
671
+ self.model.device = torch.device("cuda:0")
672
+ if hasattr(self.model.pipe, "transformer") and loras_list != ["None"] * 5:
673
+ self.model.pipe.transformer.to(self.model.device)
674
+ print("transformer to cuda")
675
 
676
  progress(1, desc="Inference preparation completed. Starting inference...")
677
 
 
679
  return self.infer_short(self.model, pipe_params, progress), info_state
680
  ## END MOD
681
 
682
+ # def sd_gen_generate_pipeline(*args):
683
+
684
+ # # Load lora in CPU
685
+ # status_lora = sd_gen.model.lora_merge(
686
+ # lora_A=args[7] if args[7] != "None" else None, lora_scale_A=args[8],
687
+ # lora_B=args[9] if args[9] != "None" else None, lora_scale_B=args[10],
688
+ # lora_C=args[11] if args[11] != "None" else None, lora_scale_C=args[12],
689
+ # lora_D=args[13] if args[13] != "None" else None, lora_scale_D=args[14],
690
+ # lora_E=args[15] if args[15] != "None" else None, lora_scale_E=args[16],
691
+ # )
692
+
693
+ # lora_list = [args[7], args[9], args[11], args[13], args[15]]
694
+ # print(status_lora)
695
+ # for status, lora in zip(status_lora, lora_list):
696
+ # if status:
697
+ # gr.Info(f"LoRA loaded: {lora}")
698
+ # elif status is not None:
699
+ # gr.Warning(f"Failed to load LoRA: {lora}")
700
+
701
+ # # if status_lora == [None] * 5 and self.model.lora_memory != [None] * 5:
702
+ # # gr.Info(f"LoRAs in cache: {", ".join(str(x) for x in self.model.lora_memory if x is not None)}")
703
+
704
+ # yield from sd_gen.generate_pipeline(*args)
705
+
706
+
707
+ # sd_gen_generate_pipeline.zerogpu = True
708
 
709
  from pathlib import Path
710
+ import random
711
  from modutils import (safe_float, escape_lora_basename, to_lora_key, to_lora_path,
712
  get_local_model_list, get_private_lora_model_lists, get_valid_lora_name,
713
  get_valid_lora_path, get_valid_lora_wt, get_lora_info,
env.py CHANGED
@@ -1,7 +1,7 @@
1
  import os
2
 
3
  CIVITAI_API_KEY = os.environ.get("CIVITAI_API_KEY")
4
- hf_token = os.environ.get("HF_TOKEN")
5
  hf_read_token = os.environ.get('HF_READ_TOKEN') # only use for private repo
6
 
7
  # - **List Models**
@@ -50,8 +50,9 @@ load_diffusers_format_model = [
50
  'eienmojiki/Anything-XL',
51
  'eienmojiki/Starry-XL-v5.2',
52
  'gsdf/CounterfeitXL',
53
- 'kitty7779/ponyDiffusionV6XL',
54
  'WhiteAiZ/autismmixSDXL_autismmixConfetti_diffusers',
 
55
  'GraydientPlatformAPI/aniverse-pony',
56
  'John6666/mistoon-anime-ponyalpha-sdxl',
57
  'John6666/ebara-mfcg-pony-mix-v12-sdxl',
@@ -61,10 +62,10 @@ load_diffusers_format_model = [
61
  'John6666/cyberrealistic-pony-v63-sdxl',
62
  'GraydientPlatformAPI/realcartoon-pony-diffusion',
63
  'John6666/nova-anime-xl-pony-v5-sdxl',
 
64
  'yodayo-ai/kivotos-xl-2.0',
65
  'yodayo-ai/holodayo-xl-2.1',
66
  'yodayo-ai/clandestine-xl-1.0',
67
- 'John6666/silvermoon-mix-01xl-v11-sdxl',
68
  'digiplay/majicMIX_sombre_v2',
69
  'digiplay/majicMIX_realistic_v6',
70
  'digiplay/majicMIX_realistic_v7',
@@ -93,6 +94,12 @@ load_diffusers_format_model = [
93
  'Eugeoter/artiwaifu-diffusion-2.0',
94
  'Raelina/Rae-Diffusion-XL-V2',
95
  'Raelina/Raemu-XL-V4',
 
 
 
 
 
 
96
  ]
97
 
98
  # List all Models for specified user
 
1
  import os
2
 
3
  CIVITAI_API_KEY = os.environ.get("CIVITAI_API_KEY")
4
+ HF_TOKEN = os.environ.get("HF_TOKEN")
5
  hf_read_token = os.environ.get('HF_READ_TOKEN') # only use for private repo
6
 
7
  # - **List Models**
 
50
  'eienmojiki/Anything-XL',
51
  'eienmojiki/Starry-XL-v5.2',
52
  'gsdf/CounterfeitXL',
53
+ 'John6666/silvermoon-mix-01xl-v11-sdxl',
54
  'WhiteAiZ/autismmixSDXL_autismmixConfetti_diffusers',
55
+ 'kitty7779/ponyDiffusionV6XL',
56
  'GraydientPlatformAPI/aniverse-pony',
57
  'John6666/mistoon-anime-ponyalpha-sdxl',
58
  'John6666/ebara-mfcg-pony-mix-v12-sdxl',
 
62
  'John6666/cyberrealistic-pony-v63-sdxl',
63
  'GraydientPlatformAPI/realcartoon-pony-diffusion',
64
  'John6666/nova-anime-xl-pony-v5-sdxl',
65
+ 'John6666/autismmix-sdxl-autismmix-pony-sdxl',
66
  'yodayo-ai/kivotos-xl-2.0',
67
  'yodayo-ai/holodayo-xl-2.1',
68
  'yodayo-ai/clandestine-xl-1.0',
 
69
  'digiplay/majicMIX_sombre_v2',
70
  'digiplay/majicMIX_realistic_v6',
71
  'digiplay/majicMIX_realistic_v7',
 
94
  'Eugeoter/artiwaifu-diffusion-2.0',
95
  'Raelina/Rae-Diffusion-XL-V2',
96
  'Raelina/Raemu-XL-V4',
97
+ "camenduru/FLUX.1-dev-diffusers",
98
+ "black-forest-labs/FLUX.1-schnell",
99
+ "sayakpaul/FLUX.1-merged",
100
+ "ostris/OpenFLUX.1",
101
+ "multimodalart/FLUX.1-dev2pro-full",
102
+ "Raelina/Raemu-Flux",
103
  ]
104
 
105
  # List all Models for specified user
modutils.py CHANGED
@@ -8,7 +8,7 @@ from pathlib import Path
8
 
9
  from env import (HF_LORA_PRIVATE_REPOS1, HF_LORA_PRIVATE_REPOS2,
10
  HF_MODEL_USER_EX, HF_MODEL_USER_LIKES,
11
- directory_loras, hf_read_token, hf_token, CIVITAI_API_KEY)
12
 
13
 
14
  def get_user_agent():
@@ -100,6 +100,24 @@ def safe_float(input):
100
  return output
101
 
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  def save_gallery_images(images, progress=gr.Progress(track_tqdm=True)):
104
  from datetime import datetime, timezone, timedelta
105
  progress(0, desc="Updating gallery...")
@@ -209,11 +227,16 @@ def get_model_id_list():
209
  model_ids.append(model.id) if not model.private else ""
210
  anime_models = []
211
  real_models = []
 
 
212
  for model in models_ex:
213
- if not model.private and not model.gated and "diffusers:FluxPipeline" not in model.tags:
214
- anime_models.append(model.id) if "anime" in model.tags else real_models.append(model.id)
 
215
  model_ids.extend(anime_models)
216
  model_ids.extend(real_models)
 
 
217
  model_id_list = model_ids.copy()
218
  return model_ids
219
 
@@ -408,7 +431,7 @@ def download_lora(dl_urls: str):
408
  for url in [url.strip() for url in dl_urls.split(',')]:
409
  local_path = f"{directory_loras}/{url.split('/')[-1]}"
410
  if not Path(local_path).exists():
411
- download_things(directory_loras, url, hf_token, CIVITAI_API_KEY)
412
  urls.append(url)
413
  after = get_local_model_list(directory_loras)
414
  new_files = list_sub(after, before)
@@ -670,7 +693,7 @@ def get_my_lora(link_url):
670
  before = get_local_model_list(directory_loras)
671
  for url in [url.strip() for url in link_url.split(',')]:
672
  if not Path(f"{directory_loras}/{url.split('/')[-1]}").exists():
673
- download_things(directory_loras, url, hf_token, CIVITAI_API_KEY)
674
  after = get_local_model_list(directory_loras)
675
  new_files = list_sub(after, before)
676
  for file in new_files:
@@ -727,8 +750,7 @@ def move_file_lora(filepaths):
727
 
728
 
729
  def get_civitai_info(path):
730
- global civitai_not_exists_list
731
- global loras_url_to_path_dict
732
  import requests
733
  from requests.adapters import HTTPAdapter
734
  from urllib3.util import Retry
@@ -1224,7 +1246,7 @@ def get_model_pipeline(repo_id: str):
1224
  try:
1225
  if " " in repo_id or not api.repo_exists(repo_id): return default
1226
  model = api.model_info(repo_id=repo_id)
1227
- except Exception as e:
1228
  return default
1229
  if model.private or model.gated: return default
1230
  tags = model.tags
 
8
 
9
  from env import (HF_LORA_PRIVATE_REPOS1, HF_LORA_PRIVATE_REPOS2,
10
  HF_MODEL_USER_EX, HF_MODEL_USER_LIKES,
11
+ directory_loras, hf_read_token, HF_TOKEN, CIVITAI_API_KEY)
12
 
13
 
14
  def get_user_agent():
 
100
  return output
101
 
102
 
103
+ from PIL import Image
104
+ def save_images(images: list[Image.Image], metadatas: list[str]):
105
+ from PIL import PngImagePlugin
106
+ import uuid
107
+ try:
108
+ output_images = []
109
+ for image, metadata in zip(images, metadatas):
110
+ info = PngImagePlugin.PngInfo()
111
+ info.add_text("metadata", metadata)
112
+ savefile = f"{str(uuid.uuid4())}.png"
113
+ image.save(savefile, "PNG", pnginfo=info)
114
+ output_images.append(str(Path(savefile).resolve()))
115
+ return output_images
116
+ except Exception as e:
117
+ print(f"Failed to save image file: {e}")
118
+ raise Exception(f"Failed to save image file:") from e
119
+
120
+
121
  def save_gallery_images(images, progress=gr.Progress(track_tqdm=True)):
122
  from datetime import datetime, timezone, timedelta
123
  progress(0, desc="Updating gallery...")
 
227
  model_ids.append(model.id) if not model.private else ""
228
  anime_models = []
229
  real_models = []
230
+ anime_models_flux = []
231
+ real_models_flux = []
232
  for model in models_ex:
233
+ if not model.private and not model.gated:
234
+ if "diffusers:FluxPipeline" in model.tags: anime_models_flux.append(model.id) if "anime" in model.tags else real_models_flux.append(model.id)
235
+ else: anime_models.append(model.id) if "anime" in model.tags else real_models.append(model.id)
236
  model_ids.extend(anime_models)
237
  model_ids.extend(real_models)
238
+ model_ids.extend(anime_models_flux)
239
+ model_ids.extend(real_models_flux)
240
  model_id_list = model_ids.copy()
241
  return model_ids
242
 
 
431
  for url in [url.strip() for url in dl_urls.split(',')]:
432
  local_path = f"{directory_loras}/{url.split('/')[-1]}"
433
  if not Path(local_path).exists():
434
+ download_things(directory_loras, url, HF_TOKEN, CIVITAI_API_KEY)
435
  urls.append(url)
436
  after = get_local_model_list(directory_loras)
437
  new_files = list_sub(after, before)
 
693
  before = get_local_model_list(directory_loras)
694
  for url in [url.strip() for url in link_url.split(',')]:
695
  if not Path(f"{directory_loras}/{url.split('/')[-1]}").exists():
696
+ download_things(directory_loras, url, HF_TOKEN, CIVITAI_API_KEY)
697
  after = get_local_model_list(directory_loras)
698
  new_files = list_sub(after, before)
699
  for file in new_files:
 
750
 
751
 
752
  def get_civitai_info(path):
753
+ global civitai_not_exists_list, loras_url_to_path_dict
 
754
  import requests
755
  from requests.adapters import HTTPAdapter
756
  from urllib3.util import Retry
 
1246
  try:
1247
  if " " in repo_id or not api.repo_exists(repo_id): return default
1248
  model = api.model_info(repo_id=repo_id)
1249
+ except Exception:
1250
  return default
1251
  if model.private or model.gated: return default
1252
  tags = model.tags