John6666 commited on
Commit
9f2f8c6
·
verified ·
1 Parent(s): 1e68e94

Upload 4 files

Browse files
Files changed (3) hide show
  1. app.py +197 -204
  2. env.py +1 -1
  3. modutils.py +3 -3
app.py CHANGED
@@ -2,12 +2,11 @@ import spaces
2
  import gradio as gr
3
  import os
4
  from stablepy import Model_Diffusers
5
- from stablepy.diffusers_vanilla.model import scheduler_names
6
  from stablepy.diffusers_vanilla.style_prompt_config import STYLE_NAMES
 
7
  import torch
8
  import re
9
- import shutil
10
- import random
11
  from stablepy import (
12
  CONTROLNET_MODEL_IDS,
13
  VALID_TASKS,
@@ -23,9 +22,9 @@ from stablepy import (
23
  SD15_TASKS,
24
  SDXL_TASKS,
25
  )
26
- import urllib.parse
27
 
28
- preprocessor_controlnet = {
29
  "openpose": [
30
  "Openpose",
31
  "None",
@@ -97,7 +96,7 @@ preprocessor_controlnet = {
97
  ],
98
  }
99
 
100
- task_stablepy = {
101
  'txt2img': 'txt2img',
102
  'img2img': 'img2img',
103
  'inpaint': 'inpaint',
@@ -123,8 +122,35 @@ task_stablepy = {
123
  'tile ControlNet': 'tile',
124
  }
125
 
126
- task_model_list = list(task_stablepy.keys())
127
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
  def download_things(directory, url, hf_token="", civitai_api_key=""):
130
  url = url.strip()
@@ -155,21 +181,19 @@ def download_things(directory, url, hf_token="", civitai_api_key=""):
155
  else:
156
  os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
157
 
158
-
159
  def get_model_list(directory_path):
160
  model_list = []
161
  valid_extensions = {'.ckpt', '.pt', '.pth', '.safetensors', '.bin'}
162
 
163
  for filename in os.listdir(directory_path):
164
  if os.path.splitext(filename)[1] in valid_extensions:
165
- name_without_extension = os.path.splitext(filename)[0]
166
  file_path = os.path.join(directory_path, filename)
167
  # model_list.append((name_without_extension, file_path))
168
  model_list.append(file_path)
169
  print('\033[34mFILE: ' + file_path + '\033[0m')
170
  return model_list
171
 
172
-
173
  ## BEGIN MOD
174
  from modutils import (list_uniq, download_private_repo, get_model_id_list, get_tupled_embed_list,
175
  get_lora_model_list, get_all_lora_tupled_list, update_loras, apply_lora_prompt, set_prompt_loras,
@@ -178,7 +202,7 @@ from modutils import (list_uniq, download_private_repo, get_model_id_list, get_t
178
  get_tupled_model_list, save_gallery_images, set_optimization, set_sampler_settings,
179
  set_quick_presets, process_style_prompt, optimization_list, save_images,
180
  preset_styles, preset_quality, preset_sampler_setting, translate_to_en)
181
- from env import (hf_token, CIVITAI_API_KEY, HF_LORA_ESSENTIAL_PRIVATE_REPO, HF_VAE_PRIVATE_REPO,
182
  HF_SDXL_EMBEDS_NEGATIVE_PRIVATE_REPO, HF_SDXL_EMBEDS_POSITIVE_PRIVATE_REPO,
183
  directory_models, directory_loras, directory_vaes, directory_embeds, directory_embeds_sdxl,
184
  directory_embeds_positive_sdxl, load_diffusers_format_model,
@@ -200,18 +224,18 @@ load_diffusers_format_model = list_uniq(get_model_id_list() + load_diffusers_for
200
  # Download stuffs
201
  for url in [url.strip() for url in download_model.split(',')]:
202
  if not os.path.exists(f"./models/{url.split('/')[-1]}"):
203
- download_things(directory_models, url, hf_token, CIVITAI_API_KEY)
204
  for url in [url.strip() for url in download_vae.split(',')]:
205
  if not os.path.exists(f"./vaes/{url.split('/')[-1]}"):
206
- download_things(directory_vaes, url, hf_token, CIVITAI_API_KEY)
207
  for url in [url.strip() for url in download_lora.split(',')]:
208
  if not os.path.exists(f"./loras/{url.split('/')[-1]}"):
209
- download_things(directory_loras, url, hf_token, CIVITAI_API_KEY)
210
 
211
  # Download Embeddings
212
  for url_embed in download_embeds:
213
  if not os.path.exists(f"./embedings/{url_embed.split('/')[-1]}"):
214
- download_things(directory_embeds, url_embed, hf_token, CIVITAI_API_KEY)
215
 
216
  # Build list models
217
  embed_list = get_model_list(directory_embeds)
@@ -232,46 +256,80 @@ def get_embed_list(pipeline_name):
232
 
233
  print('\033[33m🏁 Download and listing of valid models completed.\033[0m')
234
 
235
- upscaler_dict_gui = {
236
- None: None,
237
- "Lanczos": "Lanczos",
238
- "Nearest": "Nearest",
239
- 'Latent': 'Latent',
240
- 'Latent (antialiased)': 'Latent (antialiased)',
241
- 'Latent (bicubic)': 'Latent (bicubic)',
242
- 'Latent (bicubic antialiased)': 'Latent (bicubic antialiased)',
243
- 'Latent (nearest)': 'Latent (nearest)',
244
- 'Latent (nearest-exact)': 'Latent (nearest-exact)',
245
- "RealESRGAN_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",
246
- "RealESRNet_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth",
247
- "RealESRGAN_x4plus_anime_6B": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth",
248
- "RealESRGAN_x2plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth",
249
- "realesr-animevideov3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth",
250
- "realesr-general-x4v3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth",
251
- "realesr-general-wdn-x4v3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth",
252
- "4x-UltraSharp": "https://huggingface.co/Shandypur/ESRGAN-4x-UltraSharp/resolve/main/4x-UltraSharp.pth",
253
- "4x_foolhardy_Remacri": "https://huggingface.co/FacehugmanIII/4x_foolhardy_Remacri/resolve/main/4x_foolhardy_Remacri.pth",
254
- "Remacri4xExtraSmoother": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/Remacri%204x%20ExtraSmoother.pth",
255
- "AnimeSharp4x": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/AnimeSharp%204x.pth",
256
- "lollypop": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/lollypop.pth",
257
- "RealisticRescaler4x": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/RealisticRescaler%204x.pth",
258
- "NickelbackFS4x": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/NickelbackFS%204x.pth"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  }
260
 
261
- upscaler_keys = list(upscaler_dict_gui.keys())
 
 
 
 
 
 
 
 
 
 
 
262
 
263
  def extract_parameters(input_string):
264
  parameters = {}
265
  input_string = input_string.replace("\n", "")
266
 
267
- if not "Negative prompt:" in input_string:
268
  print("Negative prompt not detected")
269
  parameters["prompt"] = input_string
270
  return parameters
271
 
272
  parm = input_string.split("Negative prompt:")
273
  parameters["prompt"] = parm[0]
274
- if not "Steps:" in parm[1]:
275
  print("Steps not detected")
276
  parameters["neg_prompt"] = parm[1]
277
  return parameters
@@ -299,45 +357,6 @@ def extract_parameters(input_string):
299
 
300
  return parameters
301
 
302
-
303
- #######################
304
- # GUI
305
- #######################
306
- import gradio as gr
307
- from PIL import Image
308
- import IPython.display
309
- import time, json
310
- from IPython.utils import capture
311
- import logging
312
- logging.getLogger("diffusers").setLevel(logging.ERROR)
313
- import diffusers
314
- diffusers.utils.logging.set_verbosity(40)
315
- import warnings
316
- warnings.filterwarnings(action="ignore", category=FutureWarning, module="diffusers")
317
- warnings.filterwarnings(action="ignore", category=UserWarning, module="diffusers")
318
- warnings.filterwarnings(action="ignore", category=FutureWarning, module="transformers")
319
- ## BEGIN MOD
320
- from stablepy import logger
321
- logger.setLevel(logging.CRITICAL)
322
-
323
- from v2 import V2_ALL_MODELS, v2_random_prompt, v2_upsampling_prompt
324
- from utils import (gradio_copy_text, COPY_ACTION_JS, gradio_copy_prompt,
325
- V2_ASPECT_RATIO_OPTIONS, V2_RATING_OPTIONS, V2_LENGTH_OPTIONS, V2_IDENTITY_OPTIONS)
326
- from tagger import (predict_tags_wd, convert_danbooru_to_e621_prompt,
327
- remove_specific_prompt, insert_recom_prompt, insert_model_recom_prompt,
328
- compose_prompt_to_copy, translate_prompt, select_random_character)
329
- def description_ui():
330
- gr.Markdown(
331
- """
332
- ## Danbooru Tags Transformer V2 Demo with WD Tagger
333
- (Image =>) Prompt => Upsampled longer prompt
334
- - Mod of p1atdev's [Danbooru Tags Transformer V2 Demo](https://huggingface.co/spaces/p1atdev/danbooru-tags-transformer-v2) and [WD Tagger with 🤗 transformers](https://huggingface.co/spaces/p1atdev/wd-tagger-transformers).
335
- - Models: p1atdev's [wd-swinv2-tagger-v3-hf](https://huggingface.co/p1atdev/wd-swinv2-tagger-v3-hf), [dart-v2-moe-sft](https://huggingface.co/p1atdev/dart-v2-moe-sft)
336
- """
337
- )
338
- ## END MOD
339
-
340
-
341
  def info_html(json_data, title, subtitle):
342
  return f"""
343
  <div style='padding: 0; border-radius: 10px;'>
@@ -349,6 +368,18 @@ def info_html(json_data, title, subtitle):
349
  </div>
350
  """
351
 
 
 
 
 
 
 
 
 
 
 
 
 
352
  class GuiSD:
353
  def __init__(self):
354
  self.model = None
@@ -368,23 +399,21 @@ class GuiSD:
368
  yield f"Loading model: {model_name}"
369
 
370
  vae_model = vae_model if vae_model != "None" else None
 
371
 
372
- if model_name in model_list:
373
- model_is_xl = "xl" in model_name.lower()
374
- sdxl_in_vae = vae_model and "sdxl" in vae_model.lower()
375
- model_type = "SDXL" if model_is_xl else "SD 1.5"
376
- incompatible_vae = (model_is_xl and vae_model and not sdxl_in_vae) or (not model_is_xl and sdxl_in_vae)
377
-
378
- if incompatible_vae:
379
- vae_model = None
380
 
381
  self.model.device = torch.device("cpu")
 
382
 
383
  self.model.load_pipe(
384
  model_name,
385
- task_name=task_stablepy[task],
386
  vae_model=vae_model if vae_model != "None" else None,
387
- type_model_precision=torch.float16 if "flux" not in model_name.lower() else torch.bfloat16,
388
  retain_task_model_in_cache=False,
389
  )
390
  yield f"Model loaded: {model_name}"
@@ -504,6 +533,8 @@ class GuiSD:
504
  vae_msg = f"VAE: {vae_model}" if vae_model else ""
505
  msg_lora = []
506
 
 
 
507
  ## BEGIN MOD
508
  global lora_model_list
509
  lora_model_list = get_lora_model_list()
@@ -512,33 +543,8 @@ class GuiSD:
512
  lora_scale3, lora4, lora_scale4, lora5, lora_scale5)
513
  prompt, neg_prompt = insert_model_recom_prompt(prompt, neg_prompt, model_name)
514
  ## END MOD
515
-
516
- if model_name in model_list:
517
- model_is_xl = "xl" in model_name.lower()
518
- sdxl_in_vae = vae_model and "sdxl" in vae_model.lower()
519
- model_type = "SDXL" if model_is_xl else "SD 1.5"
520
- incompatible_vae = (model_is_xl and vae_model and not sdxl_in_vae) or (not model_is_xl and sdxl_in_vae)
521
-
522
- if incompatible_vae:
523
- msg_inc_vae = (
524
- f"The selected VAE is for a { 'SD 1.5' if model_is_xl else 'SDXL' } model, but you"
525
- f" are using a { model_type } model. The default VAE "
526
- "will be used."
527
- )
528
- gr.Info(msg_inc_vae)
529
- vae_msg = msg_inc_vae
530
- vae_model = None
531
 
532
- for la in loras_list:
533
- if la is not None and la != "None" and la != "" and la in lora_model_list:
534
- print(la)
535
- lora_type = ("animetarot" in la.lower() or "Hyper-SD15-8steps".lower() in la.lower())
536
- if (model_is_xl and lora_type) or (not model_is_xl and not lora_type):
537
- msg_inc_lora = f"The LoRA {la} is for { 'SD 1.5' if model_is_xl else 'SDXL' }, but you are using { model_type }."
538
- gr.Info(msg_inc_lora)
539
- msg_lora.append(msg_inc_lora)
540
-
541
- task = task_stablepy[task]
542
 
543
  params_ip_img = []
544
  params_ip_msk = []
@@ -560,18 +566,6 @@ class GuiSD:
560
  params_ip_mode.append(modeip)
561
  params_ip_scale.append(scaleip)
562
 
563
- model_precision = torch.float16 if "flux" not in model_name.lower() else torch.bfloat16
564
-
565
- # First load
566
- if not self.model:
567
- print("Loading model...")
568
- self.model = Model_Diffusers(
569
- base_model_id=model_name,
570
- task_name=task,
571
- vae_model=vae_model if vae_model != "None" else None,
572
- type_model_precision=model_precision,
573
- retain_task_model_in_cache=retain_task_cache_gui,
574
- )
575
  self.model.stream_config(concurrency=5, latent_resize_by=1, vae_decoding=False)
576
 
577
  if task != "txt2img" and not image_control:
@@ -580,62 +574,47 @@ class GuiSD:
580
  if task == "inpaint" and not image_mask:
581
  raise ValueError("No mask image found: Specify one in 'Image Mask'")
582
 
583
- if upscaler_model_path in upscaler_keys[:9]:
584
  upscaler_model = upscaler_model_path
585
  else:
586
  directory_upscalers = 'upscalers'
587
  os.makedirs(directory_upscalers, exist_ok=True)
588
 
589
- url_upscaler = upscaler_dict_gui[upscaler_model_path]
590
 
591
  if not os.path.exists(f"./upscalers/{url_upscaler.split('/')[-1]}"):
592
- download_things(directory_upscalers, url_upscaler, hf_token)
593
 
594
  upscaler_model = f"./upscalers/{url_upscaler.split('/')[-1]}"
595
 
596
  logging.getLogger("ultralytics").setLevel(logging.INFO if adetailer_verbose else logging.ERROR)
597
 
598
- print("Config model:", model_name, vae_model, loras_list)
599
-
600
- self.model.load_pipe(
601
- model_name,
602
- task_name=task,
603
- vae_model=vae_model if vae_model != "None" else None,
604
- type_model_precision=model_precision,
605
- retain_task_model_in_cache=retain_task_cache_gui,
606
- )
607
-
608
- ## BEGIN MOD
609
- # if textual_inversion and self.model.class_name == "StableDiffusionXLPipeline":
610
- # print("No Textual inversion for SDXL")
611
- ## END MOD
612
-
613
  adetailer_params_A = {
614
- "face_detector_ad" : face_detector_ad_a,
615
- "person_detector_ad" : person_detector_ad_a,
616
- "hand_detector_ad" : hand_detector_ad_a,
617
  "prompt": prompt_ad_a,
618
- "negative_prompt" : negative_prompt_ad_a,
619
- "strength" : strength_ad_a,
620
  # "image_list_task" : None,
621
- "mask_dilation" : mask_dilation_a,
622
- "mask_blur" : mask_blur_a,
623
- "mask_padding" : mask_padding_a,
624
- "inpaint_only" : adetailer_inpaint_only,
625
- "sampler" : adetailer_sampler,
626
  }
627
 
628
  adetailer_params_B = {
629
- "face_detector_ad" : face_detector_ad_b,
630
- "person_detector_ad" : person_detector_ad_b,
631
- "hand_detector_ad" : hand_detector_ad_b,
632
  "prompt": prompt_ad_b,
633
- "negative_prompt" : negative_prompt_ad_b,
634
- "strength" : strength_ad_b,
635
  # "image_list_task" : None,
636
- "mask_dilation" : mask_dilation_b,
637
- "mask_blur" : mask_blur_b,
638
- "mask_padding" : mask_padding_b,
639
  }
640
  pipe_params = {
641
  "prompt": prompt,
@@ -748,6 +727,40 @@ class GuiSD:
748
 
749
  yield img, info_state
750
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
751
  sd_gen = GuiSD()
752
 
753
  ## BEGIN MOD
@@ -759,27 +772,7 @@ CSS ="""
759
  .lora { min-width:480px; !important; }
760
  #model-info { text-align:center; }
761
  """
762
- ## END MOD
763
 
764
- sdxl_task = [k for k, v in task_stablepy.items() if v in SDXL_TASKS ]
765
- sd_task = [k for k, v in task_stablepy.items() if v in SD15_TASKS ]
766
- def update_task_options(model_name, task_name):
767
- if model_name in model_list:
768
- if "xl" in model_name.lower() or "pony" in model_name.lower():
769
- new_choices = sdxl_task
770
- else:
771
- new_choices = sd_task
772
-
773
- if task_name not in new_choices:
774
- task_name = "txt2img"
775
-
776
- return gr.update(value=task_name, choices=new_choices)
777
- else:
778
- return gr.update(value=task_name, choices=task_model_list)
779
-
780
- POST_PROCESSING_SAMPLER = ["Use same sampler"] + scheduler_names[:-2]
781
-
782
- ## BEGIN MOD
783
  with gr.Blocks(theme='NoCrypt/miku@>=1.2.2', elem_id="main", fill_width=True, css=CSS, delete_cache=(60, 3600)) as app:
784
  gr.Markdown("# 🧩 DiffuseCraft Mod")
785
  gr.Markdown(
@@ -793,7 +786,7 @@ with gr.Blocks(theme='NoCrypt/miku@>=1.2.2', elem_id="main", fill_width=True, cs
793
  with gr.Column(scale=2):
794
  interface_mode_gui = gr.Radio(label="Quick settings", choices=["Simple", "Standard", "Fast", "LoRA"], value="Standard")
795
  with gr.Accordion("Model and Task", open=False) as menu_model:
796
- task_gui = gr.Dropdown(label="Task", choices=sdxl_task, value=task_model_list[0])
797
  with gr.Group():
798
  model_name_gui = gr.Dropdown(label="Model", info="You can enter a huggingface model repo_id to want to use.", choices=get_tupled_model_list(model_list), value="votepurchase/animagine-xl-3.1", allow_custom_value=True)
799
  model_info_gui = gr.Markdown(elem_id="model-info")
@@ -1036,7 +1029,7 @@ with gr.Blocks(theme='NoCrypt/miku@>=1.2.2', elem_id="main", fill_width=True, cs
1036
 
1037
  with gr.Column() as menu_advanced:
1038
  with gr.Accordion("Hires fix", open=False, visible=True) as menu_hires:
1039
- upscaler_model_path_gui = gr.Dropdown(label="Upscaler", choices=upscaler_keys, value=upscaler_keys[0])
1040
  with gr.Row():
1041
  upscaler_increases_size_gui = gr.Slider(minimum=1.1, maximum=6., step=0.1, value=1.0, label="Upscale by")
1042
  esrgan_tile_gui = gr.Slider(minimum=0, value=100, maximum=500, step=1, label="ESRGAN Tile")
@@ -1108,21 +1101,21 @@ with gr.Blocks(theme='NoCrypt/miku@>=1.2.2', elem_id="main", fill_width=True, cs
1108
  info="This option adjusts the level of changes for img2img and inpainting."
1109
  )
1110
  image_resolution_gui = gr.Slider(minimum=64, maximum=2048, step=64, value=1024, label="Image Resolution")
1111
- preprocessor_name_gui = gr.Dropdown(label="Preprocessor Name", choices=preprocessor_controlnet["canny"], value=preprocessor_controlnet["canny"][0])
1112
-
1113
- def change_preprocessor_choices(task):
1114
- task = task_stablepy[task]
1115
- if task in preprocessor_controlnet.keys():
1116
- choices_task = preprocessor_controlnet[task]
1117
- else:
1118
- choices_task = preprocessor_controlnet["canny"]
1119
- return gr.update(choices=choices_task, value=choices_task[0])
1120
-
1121
- task_gui.change(
1122
- change_preprocessor_choices,
1123
- [task_gui],
1124
- [preprocessor_name_gui],
1125
- )
1126
  with gr.Row():
1127
  preprocess_resolution_gui = gr.Slider(minimum=64, maximum=2048, step=64, value=512, label="Preprocess Resolution")
1128
  low_threshold_gui = gr.Slider(minimum=1, maximum=255, step=1, value=100, label="Canny low threshold")
@@ -1166,7 +1159,7 @@ with gr.Blocks(theme='NoCrypt/miku@>=1.2.2', elem_id="main", fill_width=True, cs
1166
 
1167
  try:
1168
  style_names_found = sd_gen.model.STYLE_NAMES
1169
- except:
1170
  style_names_found = STYLE_NAMES
1171
 
1172
  style_prompt_gui = gr.Dropdown(
@@ -1293,7 +1286,7 @@ with gr.Blocks(theme='NoCrypt/miku@>=1.2.2', elem_id="main", fill_width=True, cs
1293
  img_width_gui,
1294
  model_name_gui,
1295
  ],
1296
- outputs=[result_images],
1297
  cache_examples=False,
1298
  #elem_id="examples",
1299
  )
 
2
  import gradio as gr
3
  import os
4
  from stablepy import Model_Diffusers
 
5
  from stablepy.diffusers_vanilla.style_prompt_config import STYLE_NAMES
6
+ from stablepy.diffusers_vanilla.constants import FLUX_CN_UNION_MODES
7
  import torch
8
  import re
9
+ from huggingface_hub import HfApi
 
10
  from stablepy import (
11
  CONTROLNET_MODEL_IDS,
12
  VALID_TASKS,
 
22
  SD15_TASKS,
23
  SDXL_TASKS,
24
  )
25
+ #import urllib.parse
26
 
27
+ PREPROCESSOR_CONTROLNET = {
28
  "openpose": [
29
  "Openpose",
30
  "None",
 
96
  ],
97
  }
98
 
99
+ TASK_STABLEPY = {
100
  'txt2img': 'txt2img',
101
  'img2img': 'img2img',
102
  'inpaint': 'inpaint',
 
122
  'tile ControlNet': 'tile',
123
  }
124
 
125
+ TASK_MODEL_LIST = list(TASK_STABLEPY.keys())
126
 
127
+ UPSCALER_DICT_GUI = {
128
+ None: None,
129
+ "Lanczos": "Lanczos",
130
+ "Nearest": "Nearest",
131
+ 'Latent': 'Latent',
132
+ 'Latent (antialiased)': 'Latent (antialiased)',
133
+ 'Latent (bicubic)': 'Latent (bicubic)',
134
+ 'Latent (bicubic antialiased)': 'Latent (bicubic antialiased)',
135
+ 'Latent (nearest)': 'Latent (nearest)',
136
+ 'Latent (nearest-exact)': 'Latent (nearest-exact)',
137
+ "RealESRGAN_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",
138
+ "RealESRNet_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth",
139
+ "RealESRGAN_x4plus_anime_6B": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth",
140
+ "RealESRGAN_x2plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth",
141
+ "realesr-animevideov3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth",
142
+ "realesr-general-x4v3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth",
143
+ "realesr-general-wdn-x4v3": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth",
144
+ "4x-UltraSharp": "https://huggingface.co/Shandypur/ESRGAN-4x-UltraSharp/resolve/main/4x-UltraSharp.pth",
145
+ "4x_foolhardy_Remacri": "https://huggingface.co/FacehugmanIII/4x_foolhardy_Remacri/resolve/main/4x_foolhardy_Remacri.pth",
146
+ "Remacri4xExtraSmoother": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/Remacri%204x%20ExtraSmoother.pth",
147
+ "AnimeSharp4x": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/AnimeSharp%204x.pth",
148
+ "lollypop": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/lollypop.pth",
149
+ "RealisticRescaler4x": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/RealisticRescaler%204x.pth",
150
+ "NickelbackFS4x": "https://huggingface.co/hollowstrawberry/upscalers-backup/resolve/main/ESRGAN/NickelbackFS%204x.pth"
151
+ }
152
+
153
+ UPSCALER_KEYS = list(UPSCALER_DICT_GUI.keys())
154
 
155
  def download_things(directory, url, hf_token="", civitai_api_key=""):
156
  url = url.strip()
 
181
  else:
182
  os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
183
 
 
184
  def get_model_list(directory_path):
185
  model_list = []
186
  valid_extensions = {'.ckpt', '.pt', '.pth', '.safetensors', '.bin'}
187
 
188
  for filename in os.listdir(directory_path):
189
  if os.path.splitext(filename)[1] in valid_extensions:
190
+ # name_without_extension = os.path.splitext(filename)[0]
191
  file_path = os.path.join(directory_path, filename)
192
  # model_list.append((name_without_extension, file_path))
193
  model_list.append(file_path)
194
  print('\033[34mFILE: ' + file_path + '\033[0m')
195
  return model_list
196
 
 
197
  ## BEGIN MOD
198
  from modutils import (list_uniq, download_private_repo, get_model_id_list, get_tupled_embed_list,
199
  get_lora_model_list, get_all_lora_tupled_list, update_loras, apply_lora_prompt, set_prompt_loras,
 
202
  get_tupled_model_list, save_gallery_images, set_optimization, set_sampler_settings,
203
  set_quick_presets, process_style_prompt, optimization_list, save_images,
204
  preset_styles, preset_quality, preset_sampler_setting, translate_to_en)
205
+ from env import (HF_TOKEN, CIVITAI_API_KEY, HF_LORA_ESSENTIAL_PRIVATE_REPO, HF_VAE_PRIVATE_REPO,
206
  HF_SDXL_EMBEDS_NEGATIVE_PRIVATE_REPO, HF_SDXL_EMBEDS_POSITIVE_PRIVATE_REPO,
207
  directory_models, directory_loras, directory_vaes, directory_embeds, directory_embeds_sdxl,
208
  directory_embeds_positive_sdxl, load_diffusers_format_model,
 
224
  # Download stuffs
225
  for url in [url.strip() for url in download_model.split(',')]:
226
  if not os.path.exists(f"./models/{url.split('/')[-1]}"):
227
+ download_things(directory_models, url, HF_TOKEN, CIVITAI_API_KEY)
228
  for url in [url.strip() for url in download_vae.split(',')]:
229
  if not os.path.exists(f"./vaes/{url.split('/')[-1]}"):
230
+ download_things(directory_vaes, url, HF_TOKEN, CIVITAI_API_KEY)
231
  for url in [url.strip() for url in download_lora.split(',')]:
232
  if not os.path.exists(f"./loras/{url.split('/')[-1]}"):
233
+ download_things(directory_loras, url, HF_TOKEN, CIVITAI_API_KEY)
234
 
235
  # Download Embeddings
236
  for url_embed in download_embeds:
237
  if not os.path.exists(f"./embedings/{url_embed.split('/')[-1]}"):
238
+ download_things(directory_embeds, url_embed, HF_TOKEN, CIVITAI_API_KEY)
239
 
240
  # Build list models
241
  embed_list = get_model_list(directory_embeds)
 
256
 
257
  print('\033[33m🏁 Download and listing of valid models completed.\033[0m')
258
 
259
+
260
+ #######################
261
+ # GUI
262
+ #######################
263
+ import gradio as gr
264
+ import logging
265
+ logging.getLogger("diffusers").setLevel(logging.ERROR)
266
+ import diffusers
267
+ diffusers.utils.logging.set_verbosity(40)
268
+ import warnings
269
+ warnings.filterwarnings(action="ignore", category=FutureWarning, module="diffusers")
270
+ warnings.filterwarnings(action="ignore", category=UserWarning, module="diffusers")
271
+ warnings.filterwarnings(action="ignore", category=FutureWarning, module="transformers")
272
+ ## BEGIN MOD
273
+ from stablepy import logger
274
+ logger.setLevel(logging.CRITICAL)
275
+
276
+ from v2 import V2_ALL_MODELS, v2_random_prompt, v2_upsampling_prompt
277
+ from utils import (gradio_copy_text, COPY_ACTION_JS, gradio_copy_prompt,
278
+ V2_ASPECT_RATIO_OPTIONS, V2_RATING_OPTIONS, V2_LENGTH_OPTIONS, V2_IDENTITY_OPTIONS)
279
+ from tagger import (predict_tags_wd, convert_danbooru_to_e621_prompt,
280
+ remove_specific_prompt, insert_recom_prompt, insert_model_recom_prompt,
281
+ compose_prompt_to_copy, translate_prompt, select_random_character)
282
+ def description_ui():
283
+ gr.Markdown(
284
+ """
285
+ ## Danbooru Tags Transformer V2 Demo with WD Tagger
286
+ (Image =>) Prompt => Upsampled longer prompt
287
+ - Mod of p1atdev's [Danbooru Tags Transformer V2 Demo](https://huggingface.co/spaces/p1atdev/danbooru-tags-transformer-v2) and [WD Tagger with 🤗 transformers](https://huggingface.co/spaces/p1atdev/wd-tagger-transformers).
288
+ - Models: p1atdev's [wd-swinv2-tagger-v3-hf](https://huggingface.co/p1atdev/wd-swinv2-tagger-v3-hf), [dart-v2-moe-sft](https://huggingface.co/p1atdev/dart-v2-moe-sft)
289
+ """
290
+ )
291
+ ## END MOD
292
+
293
+ msg_inc_vae = (
294
+ "Use the right VAE for your model to maintain image quality. The wrong"
295
+ " VAE can lead to poor results, like blurriness in the generated images."
296
+ )
297
+
298
+ SDXL_TASK = [k for k, v in TASK_STABLEPY.items() if v in SDXL_TASKS]
299
+ SD_TASK = [k for k, v in TASK_STABLEPY.items() if v in SD15_TASKS]
300
+ FLUX_TASK = list(TASK_STABLEPY.keys())[:3] + [k for k, v in TASK_STABLEPY.items() if v in FLUX_CN_UNION_MODES.keys()]
301
+
302
+ MODEL_TYPE_TASK = {
303
+ "SD 1.5": SD_TASK,
304
+ "SDXL": SDXL_TASK,
305
+ "FLUX": FLUX_TASK,
306
  }
307
 
308
+ MODEL_TYPE_CLASS = {
309
+ "diffusers:StableDiffusionPipeline": "SD 1.5",
310
+ "diffusers:StableDiffusionXLPipeline": "SDXL",
311
+ "diffusers:FluxPipeline": "FLUX",
312
+ }
313
+
314
+ POST_PROCESSING_SAMPLER = ["Use same sampler"] + scheduler_names[:-2]
315
+
316
+ SUBTITLE_GUI = (
317
+ "### This demo uses [diffusers](https://github.com/huggingface/diffusers)"
318
+ " to perform different tasks in image generation."
319
+ )
320
 
321
  def extract_parameters(input_string):
322
  parameters = {}
323
  input_string = input_string.replace("\n", "")
324
 
325
+ if "Negative prompt:" not in input_string:
326
  print("Negative prompt not detected")
327
  parameters["prompt"] = input_string
328
  return parameters
329
 
330
  parm = input_string.split("Negative prompt:")
331
  parameters["prompt"] = parm[0]
332
+ if "Steps:" not in parm[1]:
333
  print("Steps not detected")
334
  parameters["neg_prompt"] = parm[1]
335
  return parameters
 
357
 
358
  return parameters
359
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
  def info_html(json_data, title, subtitle):
361
  return f"""
362
  <div style='padding: 0; border-radius: 10px;'>
 
368
  </div>
369
  """
370
 
371
+ def get_model_type(repo_id: str):
372
+ api = HfApi(token=os.environ.get("HF_TOKEN")) # if use private or gated model
373
+ default = "SD 1.5"
374
+ try:
375
+ model = api.model_info(repo_id=repo_id, timeout=5.0)
376
+ tags = model.tags
377
+ for tag in tags:
378
+ if tag in MODEL_TYPE_CLASS.keys(): return MODEL_TYPE_CLASS.get(tag, default)
379
+ except Exception:
380
+ return default
381
+ return default
382
+
383
  class GuiSD:
384
  def __init__(self):
385
  self.model = None
 
399
  yield f"Loading model: {model_name}"
400
 
401
  vae_model = vae_model if vae_model != "None" else None
402
+ model_type = get_model_type(model_name)
403
 
404
+ if vae_model:
405
+ vae_type = "SDXL" if "sdxl" in vae_model.lower() else "SD 1.5"
406
+ if model_type != vae_type:
407
+ gr.Info(msg_inc_vae)
 
 
 
 
408
 
409
  self.model.device = torch.device("cpu")
410
+ dtype_model = torch.bfloat16 if model_type == "FLUX" else torch.float16
411
 
412
  self.model.load_pipe(
413
  model_name,
414
+ task_name=TASK_STABLEPY[task],
415
  vae_model=vae_model if vae_model != "None" else None,
416
+ type_model_precision=dtype_model,
417
  retain_task_model_in_cache=False,
418
  )
419
  yield f"Model loaded: {model_name}"
 
533
  vae_msg = f"VAE: {vae_model}" if vae_model else ""
534
  msg_lora = []
535
 
536
+ print("Config model:", model_name, vae_model, loras_list)
537
+
538
  ## BEGIN MOD
539
  global lora_model_list
540
  lora_model_list = get_lora_model_list()
 
543
  lora_scale3, lora4, lora_scale4, lora5, lora_scale5)
544
  prompt, neg_prompt = insert_model_recom_prompt(prompt, neg_prompt, model_name)
545
  ## END MOD
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
546
 
547
+ task = TASK_STABLEPY[task]
 
 
 
 
 
 
 
 
 
548
 
549
  params_ip_img = []
550
  params_ip_msk = []
 
566
  params_ip_mode.append(modeip)
567
  params_ip_scale.append(scaleip)
568
 
 
 
 
 
 
 
 
 
 
 
 
 
569
  self.model.stream_config(concurrency=5, latent_resize_by=1, vae_decoding=False)
570
 
571
  if task != "txt2img" and not image_control:
 
574
  if task == "inpaint" and not image_mask:
575
  raise ValueError("No mask image found: Specify one in 'Image Mask'")
576
 
577
+ if upscaler_model_path in UPSCALER_KEYS[:9]:
578
  upscaler_model = upscaler_model_path
579
  else:
580
  directory_upscalers = 'upscalers'
581
  os.makedirs(directory_upscalers, exist_ok=True)
582
 
583
+ url_upscaler = UPSCALER_DICT_GUI[upscaler_model_path]
584
 
585
  if not os.path.exists(f"./upscalers/{url_upscaler.split('/')[-1]}"):
586
+ download_things(directory_upscalers, url_upscaler, HF_TOKEN)
587
 
588
  upscaler_model = f"./upscalers/{url_upscaler.split('/')[-1]}"
589
 
590
  logging.getLogger("ultralytics").setLevel(logging.INFO if adetailer_verbose else logging.ERROR)
591
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
592
  adetailer_params_A = {
593
+ "face_detector_ad": face_detector_ad_a,
594
+ "person_detector_ad": person_detector_ad_a,
595
+ "hand_detector_ad": hand_detector_ad_a,
596
  "prompt": prompt_ad_a,
597
+ "negative_prompt": negative_prompt_ad_a,
598
+ "strength": strength_ad_a,
599
  # "image_list_task" : None,
600
+ "mask_dilation": mask_dilation_a,
601
+ "mask_blur": mask_blur_a,
602
+ "mask_padding": mask_padding_a,
603
+ "inpaint_only": adetailer_inpaint_only,
604
+ "sampler": adetailer_sampler,
605
  }
606
 
607
  adetailer_params_B = {
608
+ "face_detector_ad": face_detector_ad_b,
609
+ "person_detector_ad": person_detector_ad_b,
610
+ "hand_detector_ad": hand_detector_ad_b,
611
  "prompt": prompt_ad_b,
612
+ "negative_prompt": negative_prompt_ad_b,
613
+ "strength": strength_ad_b,
614
  # "image_list_task" : None,
615
+ "mask_dilation": mask_dilation_b,
616
+ "mask_blur": mask_blur_b,
617
+ "mask_padding": mask_padding_b,
618
  }
619
  pipe_params = {
620
  "prompt": prompt,
 
727
 
728
  yield img, info_state
729
 
730
+ def update_task_options(model_name, task_name):
731
+ new_choices = MODEL_TYPE_TASK[get_model_type(model_name)]
732
+
733
+ if task_name not in new_choices:
734
+ task_name = "txt2img"
735
+
736
+ return gr.update(value=task_name, choices=new_choices)
737
+
738
+ # def sd_gen_generate_pipeline(*args):
739
+
740
+ # # Load lora in CPU
741
+ # status_lora = sd_gen.model.lora_merge(
742
+ # lora_A=args[7] if args[7] != "None" else None, lora_scale_A=args[8],
743
+ # lora_B=args[9] if args[9] != "None" else None, lora_scale_B=args[10],
744
+ # lora_C=args[11] if args[11] != "None" else None, lora_scale_C=args[12],
745
+ # lora_D=args[13] if args[13] != "None" else None, lora_scale_D=args[14],
746
+ # lora_E=args[15] if args[15] != "None" else None, lora_scale_E=args[16],
747
+ # )
748
+
749
+ # lora_list = [args[7], args[9], args[11], args[13], args[15]]
750
+ # print(status_lora)
751
+ # for status, lora in zip(status_lora, lora_list):
752
+ # if status:
753
+ # gr.Info(f"LoRA loaded: {lora}")
754
+ # elif status is not None:
755
+ # gr.Warning(f"Failed to load LoRA: {lora}")
756
+
757
+ # # if status_lora == [None] * 5 and self.model.lora_memory != [None] * 5:
758
+ # # gr.Info(f"LoRAs in cache: {", ".join(str(x) for x in self.model.lora_memory if x is not None)}")
759
+
760
+ # yield from sd_gen.generate_pipeline(*args)
761
+
762
+
763
+ # sd_gen_generate_pipeline.zerogpu = True
764
  sd_gen = GuiSD()
765
 
766
  ## BEGIN MOD
 
772
  .lora { min-width:480px; !important; }
773
  #model-info { text-align:center; }
774
  """
 
775
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
776
  with gr.Blocks(theme='NoCrypt/miku@>=1.2.2', elem_id="main", fill_width=True, css=CSS, delete_cache=(60, 3600)) as app:
777
  gr.Markdown("# 🧩 DiffuseCraft Mod")
778
  gr.Markdown(
 
786
  with gr.Column(scale=2):
787
  interface_mode_gui = gr.Radio(label="Quick settings", choices=["Simple", "Standard", "Fast", "LoRA"], value="Standard")
788
  with gr.Accordion("Model and Task", open=False) as menu_model:
789
+ task_gui = gr.Dropdown(label="Task", choices=SDXL_TASK, value=TASK_MODEL_LIST[0])
790
  with gr.Group():
791
  model_name_gui = gr.Dropdown(label="Model", info="You can enter a huggingface model repo_id to want to use.", choices=get_tupled_model_list(model_list), value="votepurchase/animagine-xl-3.1", allow_custom_value=True)
792
  model_info_gui = gr.Markdown(elem_id="model-info")
 
1029
 
1030
  with gr.Column() as menu_advanced:
1031
  with gr.Accordion("Hires fix", open=False, visible=True) as menu_hires:
1032
+ upscaler_model_path_gui = gr.Dropdown(label="Upscaler", choices=UPSCALER_KEYS, value=UPSCALER_KEYS[0])
1033
  with gr.Row():
1034
  upscaler_increases_size_gui = gr.Slider(minimum=1.1, maximum=6., step=0.1, value=1.0, label="Upscale by")
1035
  esrgan_tile_gui = gr.Slider(minimum=0, value=100, maximum=500, step=1, label="ESRGAN Tile")
 
1101
  info="This option adjusts the level of changes for img2img and inpainting."
1102
  )
1103
  image_resolution_gui = gr.Slider(minimum=64, maximum=2048, step=64, value=1024, label="Image Resolution")
1104
+ preprocessor_name_gui = gr.Dropdown(label="Preprocessor Name", choices=PREPROCESSOR_CONTROLNET["canny"])
1105
+
1106
+ def change_preprocessor_choices(task):
1107
+ task = TASK_STABLEPY[task]
1108
+ if task in PREPROCESSOR_CONTROLNET.keys():
1109
+ choices_task = PREPROCESSOR_CONTROLNET[task]
1110
+ else:
1111
+ choices_task = PREPROCESSOR_CONTROLNET["canny"]
1112
+ return gr.update(choices=choices_task, value=choices_task[0])
1113
+
1114
+ task_gui.change(
1115
+ change_preprocessor_choices,
1116
+ [task_gui],
1117
+ [preprocessor_name_gui],
1118
+ )
1119
  with gr.Row():
1120
  preprocess_resolution_gui = gr.Slider(minimum=64, maximum=2048, step=64, value=512, label="Preprocess Resolution")
1121
  low_threshold_gui = gr.Slider(minimum=1, maximum=255, step=1, value=100, label="Canny low threshold")
 
1159
 
1160
  try:
1161
  style_names_found = sd_gen.model.STYLE_NAMES
1162
+ except Exception:
1163
  style_names_found = STYLE_NAMES
1164
 
1165
  style_prompt_gui = gr.Dropdown(
 
1286
  img_width_gui,
1287
  model_name_gui,
1288
  ],
1289
+ outputs=[result_images, actual_task_info],
1290
  cache_examples=False,
1291
  #elem_id="examples",
1292
  )
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**
 
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**
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():
@@ -431,7 +431,7 @@ def download_lora(dl_urls: str):
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,7 +693,7 @@ def get_my_lora(link_url):
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:
 
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():
 
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: