q6 commited on
Commit
1b72208
·
1 Parent(s): c78d1eb

Add grouped custom sampling options

Browse files
Files changed (2) hide show
  1. app.py +191 -27
  2. workflow_api.py +57 -19
app.py CHANGED
@@ -140,7 +140,11 @@ REQUIRED_CUSTOM_NODES = (
140
  "ComfyUI-Impact-Subpack",
141
  "ComfyUI-ppm",
142
  "ComfyUI_IPAdapter_plus",
 
143
  )
 
 
 
144
  CUSTOM_NODE_MODULES = {
145
  "ComfyUI-Impact-Pack": (
146
  "segment_anything", "skimage", "piexif", "transformers", "cv2",
@@ -810,10 +814,19 @@ def ensure_custom_nodes():
810
  CUSTOM_NODES_DIR.mkdir(parents=True)
811
  for name in REQUIRED_CUSTOM_NODES:
812
  source = MOUNTED_CUSTOM_NODES_DIR / name
813
- if not source.is_dir():
814
- raise FileNotFoundError(f"Missing required custom node: {source}")
815
  target = CUSTOM_NODES_DIR / name
816
- target.symlink_to(source, target_is_directory=True)
 
 
 
 
 
 
 
 
 
 
 
817
  modules = CUSTOM_NODE_MODULES.get(name)
818
  if modules and not any(importlib.util.find_spec(item) is None for item in modules):
819
  continue
@@ -844,6 +857,16 @@ def write_detector_whitelist():
844
  path.write_text("\n".join(sorted(names, key=str.casefold)) + "\n")
845
 
846
 
 
 
 
 
 
 
 
 
 
 
847
  def init_comfy():
848
  if state:
849
  return
@@ -882,7 +905,11 @@ def init_comfy():
882
  VAELoader,
883
  )
884
  from comfy_extras.nodes_align_your_steps import AlignYourStepsScheduler
885
- from comfy_extras.nodes_custom_sampler import KSamplerSelect, SamplerCustom
 
 
 
 
886
  from comfy_extras.nodes_upscale_model import (
887
  ImageUpscaleWithModel,
888
  UpscaleModelLoader,
@@ -901,10 +928,51 @@ def init_comfy():
901
  str(LOCAL_MODEL_DIR / "ultralytics"),
902
  )
903
 
 
 
 
 
 
 
 
904
  folder_paths.add_model_folder_path("custom_nodes", str(CUSTOM_NODES_DIR))
905
  import_custom_nodes()
906
  from nodes import NODE_CLASS_MAPPINGS
907
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
908
  state.update(
909
  apply_lora=comfy.sd.load_lora_for_models,
910
  chains={},
@@ -926,6 +994,7 @@ def init_comfy():
926
  latent=EmptyLatentImage(),
927
  sample=KSampler(),
928
  align=AlignYourStepsScheduler(),
 
929
  sampler_select=KSamplerSelect(),
930
  sample_custom=SamplerCustom(),
931
  decode=VAEDecode(),
@@ -944,11 +1013,46 @@ def init_comfy():
944
  style_model_loader=NODE_CLASS_MAPPINGS["IPAdapterModelLoader"](),
945
  style_apply=NODE_CLASS_MAPPINGS["IPAdapterAdvanced"](),
946
  style_pipeline=None,
 
 
 
 
 
 
 
947
  )
948
 
949
  log("ComfyUI initialization complete")
950
 
951
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
952
  def run_sampler(
953
  model,
954
  seed,
@@ -961,7 +1065,8 @@ def run_sampler(
961
  latent_image,
962
  denoise,
963
  ):
964
- if scheduler != ALIGN_SCHEDULER:
 
965
  return state["sample"].sample(
966
  model=model,
967
  seed=seed,
@@ -975,14 +1080,21 @@ def run_sampler(
975
  denoise=denoise,
976
  )[0]
977
 
978
- output = state["align"].get_sigmas(
979
- ALIGN_MODEL_TYPE,
980
- steps,
981
- denoise,
982
- )
983
- sigmas = getattr(output, "result", output)[0]
984
- output = state["sampler_select"].get_sampler(sampler_name)
985
- sampler = getattr(output, "result", output)[0]
 
 
 
 
 
 
 
986
  output = state["sample_custom"].sample(
987
  model=model,
988
  add_noise=True,
@@ -994,7 +1106,7 @@ def run_sampler(
994
  sigmas=sigmas,
995
  latent_image=latent_image,
996
  )
997
- return getattr(output, "result", output)[0]
998
 
999
 
1000
  def convert_latent(samples, source_vae, target_vae):
@@ -1986,17 +2098,15 @@ def generate_images(request, from_api=True):
1986
 
1987
  with lock:
1988
  init_comfy()
1989
- options = state["sample"].INPUT_TYPES()["required"]
1990
  detailer_options = state["face_detailer"].INPUT_TYPES()["required"]
1991
  samplers = [request.sampler]
1992
  schedulers = [request.scheduler]
1993
  if request.upscale:
1994
  samplers.append(request.second_sampler)
1995
  schedulers.append(request.second_scheduler)
1996
- if any(value not in options["sampler_name"][0] for value in samplers):
1997
  raise ValueError("Unsupported sampler or scheduler")
1998
- scheduler_names = [*options["scheduler"][0], ALIGN_SCHEDULER]
1999
- if any(value not in scheduler_names for value in schedulers):
2000
  raise ValueError("Unsupported sampler or scheduler")
2001
  if any(
2002
  detailer.sampler not in detailer_options["sampler_name"][0]
@@ -2789,25 +2899,79 @@ def api_health(p=""):
2789
  return {"status": True}
2790
 
2791
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2792
  def api_options(p=""):
2793
  if not valid_pass(p):
2794
  raise gr.Error("Invalid password")
2795
 
2796
  data = object_info()
2797
  detailer = state["face_detailer"].INPUT_TYPES()["required"]
 
 
 
 
 
 
2798
  return {
2799
  "models": data["CheckpointLoaderSimple"]["input"]["required"][
2800
  "ckpt_name"
2801
  ][0],
2802
  "loras": data["LoraLoader"]["input"]["required"]["lora_name"][0],
2803
- "samplers": data["KSampler"]["input"]["required"]["sampler_name"][0],
2804
- "schedulers": data["KSampler"]["input"]["required"]["scheduler"][0],
2805
- "detailer-samplers": detailer["sampler_name"][0],
2806
- "detailer-schedulers": detailer["scheduler"][0],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2807
  "instant-style-scopes": list(STYLE_SCOPES),
2808
- "upscale-methods": data["LatentUpscaleBy"]["input"]["required"][
2809
- "upscale_method"
2810
- ][0],
 
 
 
2811
  "upscale-models": data["UpscaleModelLoader"]["input"]["required"][
2812
  "model_name"
2813
  ][0],
@@ -3818,8 +3982,8 @@ cleanup_mount()
3818
  init_comfy()
3819
  MODEL_NAMES = generation_models()
3820
  SAMPLE_OPTIONS = state["sample"].INPUT_TYPES()["required"]
3821
- SAMPLER_NAMES = SAMPLE_OPTIONS["sampler_name"][0]
3822
- SCHEDULER_NAMES = [*SAMPLE_OPTIONS["scheduler"][0], ALIGN_SCHEDULER]
3823
  DETAILER_OPTIONS = state["face_detailer"].INPUT_TYPES()["required"]
3824
  DETAILER_SAMPLER_NAMES = DETAILER_OPTIONS["sampler_name"][0]
3825
  DETAILER_SCHEDULER_NAMES = DETAILER_OPTIONS["scheduler"][0]
 
140
  "ComfyUI-Impact-Subpack",
141
  "ComfyUI-ppm",
142
  "ComfyUI_IPAdapter_plus",
143
+ "RES4LYF",
144
  )
145
+ CUSTOM_NODE_REPOS = {
146
+ "RES4LYF": "https://github.com/ClownsharkBatwing/RES4LYF",
147
+ }
148
  CUSTOM_NODE_MODULES = {
149
  "ComfyUI-Impact-Pack": (
150
  "segment_anything", "skimage", "piexif", "transformers", "cv2",
 
814
  CUSTOM_NODES_DIR.mkdir(parents=True)
815
  for name in REQUIRED_CUSTOM_NODES:
816
  source = MOUNTED_CUSTOM_NODES_DIR / name
 
 
817
  target = CUSTOM_NODES_DIR / name
818
+ if source.is_dir():
819
+ target.symlink_to(source, target_is_directory=True)
820
+ elif name in CUSTOM_NODE_REPOS:
821
+ subprocess.run(
822
+ [
823
+ "git", "clone", "-q", "--depth", "1",
824
+ CUSTOM_NODE_REPOS[name], str(target),
825
+ ],
826
+ check=True,
827
+ )
828
+ else:
829
+ raise FileNotFoundError(f"Missing required custom node: {source}")
830
  modules = CUSTOM_NODE_MODULES.get(name)
831
  if modules and not any(importlib.util.find_spec(item) is None for item in modules):
832
  continue
 
857
  path.write_text("\n".join(sorted(names, key=str.casefold)) + "\n")
858
 
859
 
860
+ def node_input_options(node, name):
861
+ spec = node.INPUT_TYPES()["required"][name]
862
+ if isinstance(spec, tuple):
863
+ if isinstance(spec[0], (list, tuple)):
864
+ return list(spec[0])
865
+ if len(spec) > 1 and isinstance(spec[1], dict):
866
+ return list(spec[1].get("options", []))
867
+ return []
868
+
869
+
870
  def init_comfy():
871
  if state:
872
  return
 
905
  VAELoader,
906
  )
907
  from comfy_extras.nodes_align_your_steps import AlignYourStepsScheduler
908
+ from comfy_extras.nodes_custom_sampler import (
909
+ BasicScheduler,
910
+ KSamplerSelect,
911
+ SamplerCustom,
912
+ )
913
  from comfy_extras.nodes_upscale_model import (
914
  ImageUpscaleWithModel,
915
  UpscaleModelLoader,
 
928
  str(LOCAL_MODEL_DIR / "ultralytics"),
929
  )
930
 
931
+ default_sample_options = KSampler.INPUT_TYPES()["required"]
932
+ default_samplers = list(default_sample_options["sampler_name"][0])
933
+ default_schedulers = list(default_sample_options["scheduler"][0])
934
+ default_upscale_methods = list(
935
+ LatentUpscaleBy.INPUT_TYPES()["required"]["upscale_method"][0]
936
+ )
937
+
938
  folder_paths.add_model_folder_path("custom_nodes", str(CUSTOM_NODES_DIR))
939
  import_custom_nodes()
940
  from nodes import NODE_CLASS_MAPPINGS
941
 
942
+ custom_samplers = {}
943
+ custom_sampler_nodes = {}
944
+ for node_name, prefix in (
945
+ ("DynSamplerSelect", "ppm-dyn"),
946
+ ("CFGPPSamplerSelect", "ppm-cfgpp"),
947
+ ("PPMSamplerSelect", "ppm"),
948
+ ):
949
+ node = NODE_CLASS_MAPPINGS.get(node_name)
950
+ if node is None:
951
+ continue
952
+ custom_sampler_nodes[node_name] = node()
953
+ for name in node_input_options(node, "sampler_name"):
954
+ if name not in default_samplers:
955
+ custom_samplers[f"{prefix}:{name}"] = (node_name, name)
956
+
957
+ current_options = KSampler.INPUT_TYPES()["required"]
958
+ sampler_sources = {
959
+ name: "RES4LYF"
960
+ for name in current_options["sampler_name"][0]
961
+ if name not in default_samplers
962
+ }
963
+ ppm_schedulers = {
964
+ "ays", "ays+", "ays_30", "ays_30+", "gits", "beta_1_1",
965
+ }
966
+ scheduler_sources = {
967
+ name: (
968
+ "ComfyUI-ppm" if name in ppm_schedulers
969
+ else "RES4LYF" if name in {"beta57", "bong_tangent"}
970
+ else "Custom node"
971
+ )
972
+ for name in current_options["scheduler"][0]
973
+ if name not in default_schedulers
974
+ }
975
+
976
  state.update(
977
  apply_lora=comfy.sd.load_lora_for_models,
978
  chains={},
 
994
  latent=EmptyLatentImage(),
995
  sample=KSampler(),
996
  align=AlignYourStepsScheduler(),
997
+ basic_scheduler=BasicScheduler(),
998
  sampler_select=KSamplerSelect(),
999
  sample_custom=SamplerCustom(),
1000
  decode=VAEDecode(),
 
1013
  style_model_loader=NODE_CLASS_MAPPINGS["IPAdapterModelLoader"](),
1014
  style_apply=NODE_CLASS_MAPPINGS["IPAdapterAdvanced"](),
1015
  style_pipeline=None,
1016
+ custom_samplers=custom_samplers,
1017
+ custom_sampler_nodes=custom_sampler_nodes,
1018
+ default_samplers=default_samplers,
1019
+ default_schedulers=default_schedulers,
1020
+ default_upscale_methods=default_upscale_methods,
1021
+ sampler_sources=sampler_sources,
1022
+ scheduler_sources=scheduler_sources,
1023
  )
1024
 
1025
  log("ComfyUI initialization complete")
1026
 
1027
 
1028
+ def output_item(output):
1029
+ return getattr(output, "result", output)[0]
1030
+
1031
+
1032
+ def sampler_names():
1033
+ options = state["sample"].INPUT_TYPES()["required"]
1034
+ return [*options["sampler_name"][0], *state["custom_samplers"]]
1035
+
1036
+
1037
+ def scheduler_names():
1038
+ options = state["sample"].INPUT_TYPES()["required"]
1039
+ return [*options["scheduler"][0], ALIGN_SCHEDULER]
1040
+
1041
+
1042
+ def select_sampler(model, seed, name):
1043
+ custom = state["custom_samplers"].get(name)
1044
+ if custom is None:
1045
+ return output_item(state["sampler_select"].get_sampler(name))
1046
+
1047
+ node_name, sampler_name = custom
1048
+ node = state["custom_sampler_nodes"][node_name]
1049
+ if node_name == "PPMSamplerSelect":
1050
+ output = node.get_sampler(sampler_name=sampler_name, model=model)
1051
+ else:
1052
+ output = node.get_sampler(sampler_name=sampler_name)
1053
+ return output_item(output)
1054
+
1055
+
1056
  def run_sampler(
1057
  model,
1058
  seed,
 
1065
  latent_image,
1066
  denoise,
1067
  ):
1068
+ custom_sampler = sampler_name in state["custom_samplers"]
1069
+ if scheduler != ALIGN_SCHEDULER and not custom_sampler:
1070
  return state["sample"].sample(
1071
  model=model,
1072
  seed=seed,
 
1080
  denoise=denoise,
1081
  )[0]
1082
 
1083
+ if scheduler == ALIGN_SCHEDULER:
1084
+ output = state["align"].get_sigmas(
1085
+ ALIGN_MODEL_TYPE,
1086
+ steps,
1087
+ denoise,
1088
+ )
1089
+ else:
1090
+ output = state["basic_scheduler"].get_sigmas(
1091
+ model,
1092
+ scheduler,
1093
+ steps,
1094
+ denoise,
1095
+ )
1096
+ sigmas = output_item(output)
1097
+ sampler = select_sampler(model, seed, sampler_name)
1098
  output = state["sample_custom"].sample(
1099
  model=model,
1100
  add_noise=True,
 
1106
  sigmas=sigmas,
1107
  latent_image=latent_image,
1108
  )
1109
+ return output_item(output)
1110
 
1111
 
1112
  def convert_latent(samples, source_vae, target_vae):
 
2098
 
2099
  with lock:
2100
  init_comfy()
 
2101
  detailer_options = state["face_detailer"].INPUT_TYPES()["required"]
2102
  samplers = [request.sampler]
2103
  schedulers = [request.scheduler]
2104
  if request.upscale:
2105
  samplers.append(request.second_sampler)
2106
  schedulers.append(request.second_scheduler)
2107
+ if any(value not in sampler_names() for value in samplers):
2108
  raise ValueError("Unsupported sampler or scheduler")
2109
+ if any(value not in scheduler_names() for value in schedulers):
 
2110
  raise ValueError("Unsupported sampler or scheduler")
2111
  if any(
2112
  detailer.sampler not in detailer_options["sampler_name"][0]
 
2899
  return {"status": True}
2900
 
2901
 
2902
+ def grouped_options(defaults, values, sources=None):
2903
+ defaults = set(defaults)
2904
+ sources = sources or {}
2905
+ groups = []
2906
+ standard = [
2907
+ {"value": value, "text": value}
2908
+ for value in values
2909
+ if value in defaults
2910
+ ]
2911
+ custom = []
2912
+ for value in values:
2913
+ if value in defaults:
2914
+ continue
2915
+ source = sources.get(value)
2916
+ text = value
2917
+ if value in state.get("custom_samplers", {}):
2918
+ text = value.partition(":")[2]
2919
+ source = "ComfyUI-ppm"
2920
+ custom.append({
2921
+ "value": value,
2922
+ "text": f"{text} [{source or 'Custom node'}]",
2923
+ })
2924
+ if standard:
2925
+ groups.append({"label": "Default", "options": standard})
2926
+ if custom:
2927
+ groups.append({"label": "Custom", "options": custom})
2928
+ return groups
2929
+
2930
+
2931
  def api_options(p=""):
2932
  if not valid_pass(p):
2933
  raise gr.Error("Invalid password")
2934
 
2935
  data = object_info()
2936
  detailer = state["face_detailer"].INPUT_TYPES()["required"]
2937
+ samplers = sampler_names()
2938
+ schedulers = scheduler_names()
2939
+ scheduler_sources = {
2940
+ **state["scheduler_sources"],
2941
+ ALIGN_SCHEDULER: "ComfyUI",
2942
+ }
2943
  return {
2944
  "models": data["CheckpointLoaderSimple"]["input"]["required"][
2945
  "ckpt_name"
2946
  ][0],
2947
  "loras": data["LoraLoader"]["input"]["required"]["lora_name"][0],
2948
+ "samplers": grouped_options(
2949
+ state["default_samplers"],
2950
+ samplers,
2951
+ state["sampler_sources"],
2952
+ ),
2953
+ "schedulers": grouped_options(
2954
+ state["default_schedulers"],
2955
+ schedulers,
2956
+ scheduler_sources,
2957
+ ),
2958
+ "detailer-samplers": grouped_options(
2959
+ state["default_samplers"],
2960
+ detailer["sampler_name"][0],
2961
+ state["sampler_sources"],
2962
+ ),
2963
+ "detailer-schedulers": grouped_options(
2964
+ state["default_schedulers"],
2965
+ detailer["scheduler"][0],
2966
+ state["scheduler_sources"],
2967
+ ),
2968
  "instant-style-scopes": list(STYLE_SCOPES),
2969
+ "upscale-methods": grouped_options(
2970
+ state["default_upscale_methods"],
2971
+ data["LatentUpscaleBy"]["input"]["required"][
2972
+ "upscale_method"
2973
+ ][0],
2974
+ ),
2975
  "upscale-models": data["UpscaleModelLoader"]["input"]["required"][
2976
  "model_name"
2977
  ][0],
 
3982
  init_comfy()
3983
  MODEL_NAMES = generation_models()
3984
  SAMPLE_OPTIONS = state["sample"].INPUT_TYPES()["required"]
3985
+ SAMPLER_NAMES = sampler_names()
3986
+ SCHEDULER_NAMES = scheduler_names()
3987
  DETAILER_OPTIONS = state["face_detailer"].INPUT_TYPES()["required"]
3988
  DETAILER_SAMPLER_NAMES = DETAILER_OPTIONS["sampler_name"][0]
3989
  DETAILER_SCHEDULER_NAMES = DETAILER_OPTIONS["scheduler"][0]
workflow_api.py CHANGED
@@ -765,6 +765,34 @@ def image_metadata(
765
  clip = [node_id, 1]
766
  return model, clip
767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
768
  def sample(
769
  model,
770
  seed,
@@ -777,37 +805,47 @@ def image_metadata(
777
  latent,
778
  denoise,
779
  ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
780
  if scheduler == ALIGN_SCHEDULER:
781
  sigmas = [add("AlignYourStepsScheduler", {
782
  "model_type": ALIGN_MODEL_TYPE,
783
  "steps": steps,
784
  "denoise": denoise,
785
  }), 0]
 
 
 
 
 
 
 
 
786
  sampler = [add("KSamplerSelect", {
787
  "sampler_name": sampler_name,
788
  }), 0]
789
- return [add("SamplerCustom", {
790
- "model": model,
791
- "add_noise": True,
792
- "noise_seed": seed,
793
- "cfg": cfg,
794
- "positive": positive,
795
- "negative": negative,
796
- "sampler": sampler,
797
- "sigmas": sigmas,
798
- "latent_image": latent,
799
- }), 0]
800
-
801
- return [add("KSampler", {
802
- "seed": seed,
803
- "steps": steps,
804
- "cfg": cfg,
805
- "sampler_name": sampler_name,
806
- "scheduler": scheduler,
807
- "denoise": denoise,
808
  "model": model,
 
 
 
809
  "positive": positive,
810
  "negative": negative,
 
 
811
  "latent_image": latent,
812
  }), 0]
813
 
 
765
  clip = [node_id, 1]
766
  return model, clip
767
 
768
+ def custom_sampler(sampler_name, model):
769
+ prefix, separator, name = sampler_name.partition(":")
770
+ if not separator:
771
+ return None
772
+ if prefix == "ppm-dyn":
773
+ return [add("DynSamplerSelect", {
774
+ "sampler_name": name,
775
+ "eta": 1,
776
+ "s_dy_pow": -1,
777
+ "s_extra_steps": False,
778
+ }), 0]
779
+ if prefix == "ppm-cfgpp":
780
+ return [add("CFGPPSamplerSelect", {
781
+ "sampler_name": name,
782
+ "eta": 1,
783
+ "s_gamma_start": 0,
784
+ "s_gamma_end": 1,
785
+ "s_extra_steps": False,
786
+ }), 0]
787
+ if prefix == "ppm":
788
+ return [add("PPMSamplerSelect", {
789
+ "sampler_name": name,
790
+ "model": model,
791
+ "cfg_pp": False,
792
+ "s_sigma_diff": 2,
793
+ }), 0]
794
+ return None
795
+
796
  def sample(
797
  model,
798
  seed,
 
805
  latent,
806
  denoise,
807
  ):
808
+ sampler = custom_sampler(sampler_name, model)
809
+ if scheduler != ALIGN_SCHEDULER and sampler is None:
810
+ return [add("KSampler", {
811
+ "seed": seed,
812
+ "steps": steps,
813
+ "cfg": cfg,
814
+ "sampler_name": sampler_name,
815
+ "scheduler": scheduler,
816
+ "denoise": denoise,
817
+ "model": model,
818
+ "positive": positive,
819
+ "negative": negative,
820
+ "latent_image": latent,
821
+ }), 0]
822
+
823
  if scheduler == ALIGN_SCHEDULER:
824
  sigmas = [add("AlignYourStepsScheduler", {
825
  "model_type": ALIGN_MODEL_TYPE,
826
  "steps": steps,
827
  "denoise": denoise,
828
  }), 0]
829
+ else:
830
+ sigmas = [add("BasicScheduler", {
831
+ "model": model,
832
+ "scheduler": scheduler,
833
+ "steps": steps,
834
+ "denoise": denoise,
835
+ }), 0]
836
+ if sampler is None:
837
  sampler = [add("KSamplerSelect", {
838
  "sampler_name": sampler_name,
839
  }), 0]
840
+ return [add("SamplerCustom", {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
841
  "model": model,
842
+ "add_noise": True,
843
+ "noise_seed": seed,
844
+ "cfg": cfg,
845
  "positive": positive,
846
  "negative": negative,
847
+ "sampler": sampler,
848
+ "sigmas": sigmas,
849
  "latent_image": latent,
850
  }), 0]
851