forked from mcmonkeyprojects/SwarmUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkflowGeneratorSteps.cs
More file actions
2234 lines (2227 loc) · 122 KB
/
Copy pathWorkflowGeneratorSteps.cs
File metadata and controls
2234 lines (2227 loc) · 122 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using FreneticUtilities.FreneticExtensions;
using Newtonsoft.Json.Linq;
using SwarmUI.Core;
using SwarmUI.Media;
using SwarmUI.Text2Image;
using SwarmUI.Utils;
using static SwarmUI.Builtin_ComfyUIBackend.WorkflowGenerator;
namespace SwarmUI.Builtin_ComfyUIBackend;
public class WorkflowGeneratorSteps
{
/// <summary>Register a new step to the workflow generator.</summary>
public static void AddStep(Action<WorkflowGenerator> step, double priority)
{
WorkflowGenerator.AddStep(step, priority);
}
/// <summary>Register a new step to the workflow generator.</summary>
public static void AddModelGenStep(Action<WorkflowGenerator> step, double priority)
{
WorkflowGenerator.AddModelGenStep(step, priority);
}
/* ========= RESERVED NODES ID MAP =========
* 4: Initial Model Loader
* 5: VAE Encode Init or Empty Latent
* 6: Positive Prompt
* 7: Negative Prompt
* 8: Final VAEDecode
* 9: Final Image Save
* 10: Main KSampler
* 11: Alternate Main VAE Loader
* 15: Image Load
* 20: Refiner Model Loader
* 21: Refiner VAE Loader
* 23: Refiner KSampler
* 24: Refiner VAEDecoder
* 25: Refiner VAEEncode
* 26: Refiner ImageScale
* 27: Refiner UpscaleModelLoader
* 28: Refiner ImageUpscaleWithModel
* 29: Refiner ImageSave
* 30: Video Image Pre-Save
*
* 100+: Dynamic
* 1500+: LoRA Loaders (Stable-Dynamic)
* 50,000+: Intermediate Image Saves (Stable-Dynamic)
*/
public static void Register()
{
#region Model Loader
AddStep(g =>
{
g.FinalLoadedModel = g.UserInput.Get(T2IParamTypes.Model);
if (g.FinalLoadedModel is null)
{
throw new SwarmUserErrorException($"No model input given. Did your UI load properly?");
}
g.FinalLoadedModelList = [g.FinalLoadedModel];
(g.FinalLoadedModel, g.CurrentModel, g.CurrentTextEnc, g.CurrentVae) = g.CreateModelLoader(g.FinalLoadedModel, "Base", "4", sectionId: T2IParamInput.SectionID_BaseOnly);
}, -15);
AddModelGenStep(g =>
{
if (g.IsRefinerStage && g.UserInput.TryGet(T2IParamTypes.RefinerVAE, out T2IModel rvae))
{
g.LoadingVAE = g.CreateVAELoader(rvae.ToString(g.ModelFolderFormat), g.HasNode("21") ? null : "21");
}
else if (!g.NoVAEOverride && g.UserInput.TryGet(T2IParamTypes.VAE, out T2IModel vae))
{
if (g.FinalLoadedModel.ModelClass?.ID == "stable-diffusion-v3-medium" && vae.ModelClass?.CompatClass?.ID != "stable-diffusion-v3")
{
Logs.Warning($"Model {g.FinalLoadedModel.Title} is an SD3 model, but you have VAE {vae.Title} selected. If that VAE is not an SD3 specific VAE, this is likely a mistake. Errors may follow. If this breaks, disable the custom VAE.");
}
g.LoadingVAE = g.CreateVAELoader(vae.ToString(g.ModelFolderFormat), g.HasNode("11") ? null : "11");
}
else if (!g.NoVAEOverride && g.UserInput.Get(T2IParamTypes.AutomaticVAE, false))
{
string clazz = g.FinalLoadedModel.ModelClass?.CompatClass?.ID;
string vaeName = null;
if (clazz == "stable-diffusion-xl-v1")
{
vaeName = g.UserInput.SourceSession?.User?.Settings.VAEs.DefaultSDXLVAE;
}
else if (clazz == "stable-diffusion-v1")
{
vaeName = g.UserInput.SourceSession?.User?.Settings.VAEs.DefaultSDv1VAE;
}
if (!string.IsNullOrWhiteSpace(vaeName) && vaeName.ToLowerFast() != "none")
{
string match = T2IParamTypes.GetBestModelInList(vaeName, Program.T2IModelSets["VAE"].ListModelNamesFor(g.UserInput.SourceSession));
if (match is not null)
{
T2IModel vaeModel = Program.T2IModelSets["VAE"].Models[match];
g.LoadingVAE = g.CreateVAELoader(vaeModel.ToString(g.ModelFolderFormat), g.HasNode("11") ? null : "11");
}
}
}
}, -14);
AddModelGenStep(g =>
{
(g.LoadingModel, g.LoadingClip) = g.LoadLorasForConfinement(-1, g.LoadingModel, g.LoadingClip);
(g.LoadingModel, g.LoadingClip) = g.LoadLorasForConfinement(0, g.LoadingModel, g.LoadingClip);
if (g.IsRefinerStage)
{
(g.LoadingModel, g.LoadingClip) = g.LoadLorasForConfinement(1, g.LoadingModel, g.LoadingClip);
}
else if (g.IsImageToVideoSwap)
{
(g.LoadingModel, g.LoadingClip) = g.LoadLorasForConfinement(T2IParamInput.SectionID_VideoSwap, g.LoadingModel, g.LoadingClip);
}
else if (g.IsImageToVideo)
{
(g.LoadingModel, g.LoadingClip) = g.LoadLorasForConfinement(T2IParamInput.SectionID_Video, g.LoadingModel, g.LoadingClip);
}
else // Base
{
(g.LoadingModel, g.LoadingClip) = g.LoadLorasForConfinement(T2IParamInput.SectionID_BaseOnly, g.LoadingModel, g.LoadingClip);
}
}, -10);
AddModelGenStep(g =>
{
if (g.UserInput.TryGet(ComfyUIBackendExtension.SetClipDevice, out string device) && g.Features.Contains("set_clip_device"))
{
string clipDeviceNode = g.CreateNode("OverrideCLIPDevice", new JObject()
{
["clip"] = g.LoadingClip,
["device"] = device
});
g.LoadingClip = [clipDeviceNode, 0];
}
}, -9);
AddModelGenStep(g =>
{
string applyTo = g.UserInput.Get(T2IParamTypes.FreeUApplyTo, null);
if (g.Features.Contains("freeu") && applyTo is not null)
{
if (applyTo == "Both" || applyTo == g.LoadingModelType)
{
string version = g.UserInput.Get(T2IParamTypes.FreeUVersion, "1");
string freeU = g.CreateNode(version == "2" ? "FreeU_V2" : "FreeU", new JObject()
{
["model"] = g.LoadingModel,
["b1"] = g.UserInput.Get(T2IParamTypes.FreeUBlock1),
["b2"] = g.UserInput.Get(T2IParamTypes.FreeUBlock2),
["s1"] = g.UserInput.Get(T2IParamTypes.FreeUSkip1),
["s2"] = g.UserInput.Get(T2IParamTypes.FreeUSkip2)
});
g.LoadingModel = [freeU, 0];
}
}
}, -8);
AddModelGenStep(g =>
{
if (g.UserInput.TryGet(ComfyUIBackendExtension.SelfAttentionGuidanceScale, out double sagScale))
{
string patched = g.CreateNode("SelfAttentionGuidance", new JObject()
{
["model"] = g.LoadingModel,
["scale"] = sagScale,
["blur_sigma"] = g.UserInput.Get(ComfyUIBackendExtension.SelfAttentionGuidanceSigmaBlur, 2.0)
});
g.LoadingModel = [patched, 0];
}
if (g.UserInput.TryGet(ComfyUIBackendExtension.PerturbedAttentionGuidanceScale, out double pagScale))
{
string patched = g.CreateNode("PerturbedAttentionGuidance", new JObject()
{
["model"] = g.LoadingModel,
["scale"] = pagScale
});
g.LoadingModel = [patched, 0];
}
if (g.UserInput.TryGet(ComfyUIBackendExtension.RescaleCFGMultiplier, out double rescaleCfg))
{
string patched = g.CreateNode("RescaleCFG", new JObject()
{
["model"] = g.LoadingModel,
["multiplier"] = rescaleCfg
});
g.LoadingModel = [patched, 0];
}
if (g.UserInput.TryGet(ComfyUIBackendExtension.RenormCFG, out double renormCfg))
{
string patched = g.CreateNode("RenormCFG", new JObject()
{
["model"] = g.LoadingModel,
["cfg_trunc"] = 100, // This value is the weirdly named timestep where the renorm applies - less than this apply, above don't. 100 is default, not sure if it needs a customization param?
["renorm_cfg"] = renormCfg
});
g.LoadingModel = [patched, 0];
}
if (g.UserInput.Get(ComfyUIBackendExtension.UseCfgZeroStar, false))
{
string patched = g.CreateNode("CFGZeroStar", new JObject()
{
["model"] = g.LoadingModel
});
g.LoadingModel = [patched, 0];
}
if (g.UserInput.Get(ComfyUIBackendExtension.UseTCFG, false))
{
string patched = g.CreateNode("TCFG", new JObject()
{
["model"] = g.LoadingModel
});
g.LoadingModel = [patched, 0];
}
if (g.UserInput.TryGet(ComfyUIBackendExtension.NormalizedAttentionGuidanceScale, out double nagScale) && nagScale > 0)
{
string patched = g.CreateNode("NAGuidance", new JObject()
{
["model"] = g.LoadingModel,
["nag_scale"] = nagScale,
["nag_alpha"] = g.UserInput.Get(ComfyUIBackendExtension.NormalizedAttentionGuidanceAlpha, 0.5),
["nag_tau"] = g.UserInput.Get(ComfyUIBackendExtension.NormalizedAttentionGuidanceTau, 1.5),
});
g.LoadingModel = [patched, 0];
}
}, -7);
AddModelGenStep(g =>
{
if (g.UserInput.TryGet(T2IParamTypes.ClipStopAtLayer, out int layer))
{
string clipSkip = g.CreateNode("CLIPSetLastLayer", new JObject()
{
["clip"] = g.LoadingClip,
["stop_at_clip_layer"] = layer
});
g.LoadingClip = [clipSkip, 0];
}
}, -6);
AddModelGenStep(g =>
{
if (g.UserInput.TryGet(T2IParamTypes.SeamlessTileable, out string tileable) && tileable != "false")
{
string mode = "Both";
if (tileable == "X-Only") { mode = "X"; }
else if (tileable == "Y-Only") { mode = "Y"; }
string tiling = g.CreateNode("SwarmModelTiling", new JObject()
{
["model"] = g.LoadingModel,
["tile_axis"] = mode
});
g.LoadingModel = [tiling, 0];
string tilingVae = g.CreateNode("SwarmTileableVAE", new JObject()
{
["vae"] = g.LoadingVAE,
["tile_axis"] = mode
});
g.LoadingVAE = [tilingVae, 0];
}
}, -5);
AddModelGenStep(g =>
{
if (g.UserInput.TryGet(ComfyUIBackendExtension.TeaCacheMode, out string teaCacheMode) && teaCacheMode != "disabled")
{
double teaCacheThreshold = g.UserInput.Get(ComfyUIBackendExtension.TeaCacheThreshold, 0.25);
double teaCacheStart = g.UserInput.Get(ComfyUIBackendExtension.TeaCacheStart, 0);
if (teaCacheMode == "base gen only" && g.LoadingModelType != "Base")
{
// wrong step, skip
}
else if (g.FinalLoadedModel?.Metadata?.SpecialFormat == "nunchaku" || g.FinalLoadedModel?.Metadata?.SpecialFormat == "nunchaku-fp4")
{
Logs.Warning($"Ignore TeaCache Mode parameter because the current model is Nunchaku which does not support TeaCache. Use 'Nunchaku Cache Threshold' for a similar effect to TeaCache.");
}
else if (g.IsFlux())
{
if (teaCacheMode != "video only")
{
string teaCacheNode = g.CreateNode(g.Features.Contains("teacache_oldvers") ? "TeaCacheForImgGen" : "TeaCache", new JObject()
{
["model"] = g.LoadingModel,
["model_type"] = "flux",
["rel_l1_thresh"] = teaCacheThreshold,
["max_skip_steps"] = 3,
["start_percent"] = teaCacheStart,
["end_percent"] = 1,
["cache_device"] = "cuda"
});
g.LoadingModel = [teaCacheNode, 0];
}
}
else if (g.IsHunyuanVideo() || g.IsLTXV() || g.IsWanVideo() || g.IsHiDream())
{
string type = "";
if (g.IsHunyuanVideo())
{
type = "hunyuan_video";
}
else if (g.IsLTXV())
{
type = "ltxv";
}
else if (g.IsHiDream())
{
type = "hidream_i1_dev";
}
else
{
string arch = g.CurrentModelClass()?.ID;
if (arch == "wan-2_1-text2video-1_3b" || arch == "wan-2_1-image2video-1_3b")
{
type = "wan2.1_t2v_1.3B";
}
else if (arch == "wan-2_1-text2video-14b")
{
type = "wan2.1_t2v_14B";
}
else if (arch == "wan-2_1-image2video-14b" || arch == "wan-2_1-flf2v-14b")
{
if (g.FinalLoadedModel.Name.Contains("720p") || g.FinalLoadedModel.StandardWidth == 960 || arch == "wan-2_1-flf2v-14b")
{
type = "wan2.1_i2v_720p_14B";
}
else
{
type = "wan2.1_i2v_480p_14B";
}
}
}
string teaCacheNode = g.CreateNode(g.Features.Contains("teacache_oldvers") ? "TeaCacheForVidGen" : "TeaCache", new JObject()
{
["model"] = g.LoadingModel,
["model_type"] = type,
["rel_l1_thresh"] = teaCacheThreshold,
["max_skip_steps"] = 3,
["start_percent"] = teaCacheStart,
["end_percent"] = 1,
["cache_device"] = "cuda"
});
g.LoadingModel = [teaCacheNode, 0];
}
else
{
Logs.Debug($"Ignore TeaCache Mode parameter because the current model is '{g.CurrentModelClass()?.Name ?? "(none)"}' which does not support TeaCache.");
}
}
if (g.UserInput.TryGet(ComfyUIBackendExtension.EasyCacheMode, out string easyCacheMode) && easyCacheMode != "disabled")
{
if (teaCacheMode == "base gen only" && g.LoadingModelType != "Base")
{
// wrong step, skip
}
else if (g.IsVideoModel() || teaCacheMode != "video only")
{
string teaCacheNode = g.CreateNode("EasyCache", new JObject()
{
["model"] = g.LoadingModel,
["reuse_threshold"] = g.UserInput.Get(ComfyUIBackendExtension.EasyCacheThreshold, 0),
["start_percent"] = g.UserInput.Get(ComfyUIBackendExtension.EasyCacheStart, 0),
["end_percent"] = g.UserInput.Get(ComfyUIBackendExtension.EasyCacheEnd, 1),
["verbose"] = false
});
g.LoadingModel = [teaCacheNode, 0];
}
}
}, -4);
AddModelGenStep(g =>
{
if (g.Features.Contains("aitemplate") && g.UserInput.Get(ComfyUIBackendExtension.AITemplateParam))
{
string aitLoad = g.CreateNode("AITemplateLoader", new JObject()
{
["model"] = g.LoadingModel,
["keep_loaded"] = "disable"
});
g.LoadingModel = [aitLoad, 0];
}
if (g.UserInput.TryGet(T2IParamTypes.TorchCompile, out string compileMode) && compileMode != "Disabled")
{
string torchCompile = g.CreateNode("TorchCompileModel", new JObject()
{
["model"] = g.LoadingModel,
["backend"] = compileMode
});
g.LoadingModel = [torchCompile, 0];
}
}, -3);
#endregion
#region Base Image
AddStep(g =>
{
// TODO: if g.IsAudioModel(), InitAudio?
if (!g.IsAudioModel() && g.UserInput.TryGet(T2IParamTypes.InitImage, out Image img))
{
string maskImageNode = null;
if (g.UserInput.TryGet(T2IParamTypes.MaskImage, out Image mask))
{
WGNodeData maskNode = g.LoadImage(mask, "${maskimage}", true);
maskImageNode = g.CreateNode("ImageToMask", new JObject()
{
["image"] = maskNode.Path,
["channel"] = "red"
});
g.EnableDifferential();
if (g.UserInput.TryGet(T2IParamTypes.MaskGrow, out int growAmount))
{
maskImageNode = g.CreateNode("SwarmMaskGrow", new JObject()
{
["mask"] = NodePath(maskImageNode, 0),
["grow"] = growAmount,
});
}
if (g.UserInput.TryGet(T2IParamTypes.MaskBlur, out int blurAmount))
{
maskImageNode = g.CreateNode("SwarmMaskBlur", new JObject()
{
["mask"] = NodePath(maskImageNode, 0),
["blur_radius"] = blurAmount,
["sigma"] = 1.0
});
}
g.FinalMask = [maskImageNode, 0];
}
g.BasicInputImage = g.LoadImage(img, "${initimage}", true, "15");
g.CurrentMedia = g.BasicInputImage;
JArray currentMask = g.FinalMask;
if (g.UserInput.TryGet(T2IParamTypes.InitImageNoise, out double initNoise))
{
JObject noiseInput = new()
{
["image"] = g.BasicInputImage.Path,
["amount"] = initNoise,
["seed"] = g.UserInput.Get(T2IParamTypes.Seed, 0) + 327
};
if (currentMask is not null)
{
// cut the edges of a blurred mask back to make recompositing cleaner
string thresholded = g.CreateNode("SwarmMaskThreshold", new JObject()
{
["mask"] = currentMask,
["min"] = 0.5,
["max"] = 1.0
});
noiseInput["mask"] = NodePath(thresholded, 0);
}
string noised = g.CreateNode("SwarmImageNoise", noiseInput);
g.BasicInputImage = g.BasicInputImage.WithPath([noised, 0]);
}
if (currentMask is not null)
{
if (g.UserInput.TryGet(T2IParamTypes.MaskShrinkGrow, out int shrinkGrow))
{
g.MaskShrunkInfo = g.CreateImageMaskCrop(g.FinalMask, g.BasicInputImage.Path, shrinkGrow, g.CurrentVae.Path, g.FinalLoadedModel);
currentMask = [g.MaskShrunkInfo.CroppedMask, 0];
// TODO: proper width/height wrangling
g.CurrentMedia = g.CurrentMedia.WithPath([g.MaskShrunkInfo.MaskedLatent, 0], WGNodeData.DT_LATENT_IMAGE);
}
else
{
JArray masked = g.DoMaskedVAEEncode(g.CurrentVae.Path, g.BasicInputImage.Path, currentMask, "5");
g.CurrentMedia = g.CurrentMedia.WithPath(masked, WGNodeData.DT_LATENT_IMAGE);
}
}
else
{
g.CurrentMedia = g.BasicInputImage.EncodeToLatent(g.CurrentVae, "5");
}
if (g.UserInput.TryGet(T2IParamTypes.UnsamplerPrompt, out string unprompt))
{
int steps = g.UserInput.Get(T2IParamTypes.Steps);
int startStep = 0;
if (g.UserInput.TryGet(T2IParamTypes.InitImageCreativity, out double creativity))
{
startStep = (int)Math.Round(steps * (1 - creativity));
}
JArray posCond = g.CreateConditioning(unprompt, g.CurrentTextEnc.Path, g.FinalLoadedModel, true);
JArray negCond = g.CreateConditioning(g.UserInput.Get(T2IParamTypes.NegativePrompt, ""), g.CurrentTextEnc.Path, g.FinalLoadedModel, false);
g.CurrentMedia = g.CurrentMedia.AsLatentImage(g.CurrentVae);
string unsampler = g.CreateNode("SwarmUnsampler", new JObject()
{
["model"] = g.CurrentModel.Path,
["steps"] = steps,
["sampler_name"] = g.UserInput.Get(ComfyUIBackendExtension.SamplerParam, "euler"),
["scheduler"] = g.UserInput.Get(ComfyUIBackendExtension.SchedulerParam, "normal"),
["positive"] = posCond,
["negative"] = negCond,
["latent_image"] = g.CurrentMedia.Path,
["start_at_step"] = startStep,
["previews"] = g.UserInput.Get(T2IParamTypes.NoPreviews) ? "none" : "default"
});
g.CurrentMedia = g.CurrentMedia.WithPath([unsampler, 0]);
g.MainSamplerAddNoise = false;
}
if (g.UserInput.TryGet(T2IParamTypes.BatchSize, out int batchSize) && batchSize > 1)
{
g.CurrentMedia = g.CurrentMedia.AsLatentImage(g.CurrentVae);
string batchNode = g.CreateNode("RepeatLatentBatch", new JObject()
{
["samples"] = g.CurrentMedia.Path,
["amount"] = batchSize
});
g.CurrentMedia = g.CurrentMedia.WithPath([batchNode, 0]);
}
else
{
batchSize = 1;
}
if (g.UserInput.TryGet(T2IParamTypes.InitImageResetToNorm, out double resetFactor))
{
g.CurrentMedia = g.CurrentMedia.AsLatentImage(g.CurrentVae);
string emptyImg = g.CreateEmptyImage(g.UserInput.GetImageWidth(), g.UserInput.GetImageHeight(), batchSize);
if (g.Features.Contains("comfy_latent_blend_masked") && currentMask is not null)
{
string blended = g.CreateNode("SwarmLatentBlendMasked", new JObject()
{
["samples0"] = g.CurrentMedia.Path,
["samples1"] = NodePath(emptyImg, 0),
["mask"] = currentMask,
["blend_factor"] = resetFactor
});
g.CurrentMedia = g.CurrentMedia.WithPath([blended, 0]);
}
else
{
string emptyMultiplied = g.CreateNode("LatentMultiply", new JObject()
{
["samples"] = NodePath(emptyImg, 0),
["multiplier"] = resetFactor
});
string originalMultiplied = g.CreateNode("LatentMultiply", new JObject()
{
["samples"] = g.CurrentMedia.Path,
["multiplier"] = 1 - resetFactor
});
string added = g.CreateNode("LatentAdd", new JObject()
{
["samples1"] = NodePath(emptyMultiplied, 0),
["samples2"] = NodePath(originalMultiplied, 0)
});
g.CurrentMedia = g.CurrentMedia.WithPath([added, 0]);
}
}
if (g.IsLTXV2())
{
if (g.CurrentMedia.DataType == WGNodeData.DT_VIDEO)
{
string frameCountNode = g.CreateNode("SwarmCountFrames", new JObject()
{
["image"] = g.CurrentMedia.AsRawImage(g.CurrentVae).Path
});
string emptyAudio = g.CreateNode("LTXVEmptyLatentAudio", new JObject()
{
["batch_size"] = batchSize,
["frames_number"] = NodePath(frameCountNode, 0),
["frame_rate"] = g.CurrentMedia.FPS ?? g.UserInput.Get(T2IParamTypes.VideoFPS, 24),
["audio_vae"] = g.CurrentAudioVae.Path
});
g.CurrentMedia = g.CurrentMedia.Duplicate();
g.CurrentMedia.Frames = null;
g.CurrentMedia.AttachedAudio = new([emptyAudio, 0], g, WGNodeData.DT_LATENT_AUDIO, g.CurrentCompat());
}
}
}
else
{
g.CurrentMedia = g.EmptyImage(g.UserInput.GetImageWidth(), g.UserInput.GetImageHeight(), g.UserInput.Get(T2IParamTypes.BatchSize, 1), "5");
}
if (g.UserInput.TryGet(T2IParamTypes.VideoAudioInput, out AudioFile audioData))
{
string audioNode = g.CreateAudioLoadNode(audioData, "${videoaudioinput}");
g.CurrentMedia.AttachedAudio = new WGNodeData([audioNode, 0], g, WGNodeData.DT_AUDIO, g.CurrentCompat());
}
}, -9);
#endregion
#region Positive Prompt
AddStep(g =>
{
g.FinalPrompt = g.CreateConditioning(g.UserInput.Get(T2IParamTypes.Prompt), g.CurrentTextEnc.Path, g.UserInput.Get(T2IParamTypes.Model), true, "6");
}, -8);
#endregion
#region ReVision/UnCLIP/IPAdapter
AddStep(g =>
{
if (g.UserInput.TryGet(T2IParamTypes.PromptImages, out List<Image> images) && images.Any())
{
if (g.UserInput.TryGet(ComfyUIBackendExtension.UseStyleModel, out string styleModelName))
{
string clipVis = g.RequireVisionModel("sigclip_vision_patch14_384.safetensors", "https://huggingface.co/Comfy-Org/sigclip_vision_384/resolve/main/sigclip_vision_patch14_384.safetensors", "1fee501deabac72f0ed17610307d7131e3e9d1e838d0363aa3c2b97a6e03fb33", T2IParamTypes.ClipVisionModel);
string styleModelClipLoader = g.CreateNode("CLIPVisionLoader", new JObject()
{
["clip_name"] = clipVis
});
string styleModelLoader = g.CreateNode("StyleModelLoader", new JObject()
{
["style_model_name"] = styleModelName
});
for (int i = 0; i < images.Count; i++)
{
WGNodeData imageLoader = g.LoadImage(images[i], "${promptimages." + i + "}", false);
string encoded = g.CreateNode("CLIPVisionEncode", new JObject()
{
["clip_vision"] = NodePath(styleModelClipLoader, 0),
["image"] = imageLoader.Path,
["crop"] = "none"
});
string styled = g.CreateNode("StyleModelApply", new JObject()
{
["conditioning"] = g.FinalPrompt,
["clip_vision_output"] = NodePath(encoded, 0),
["style_model"] = NodePath(styleModelLoader, 0),
["strength_type"] = "multiply",
["strength"] = g.UserInput.Get(ComfyUIBackendExtension.StyleModelMultiplyStrength, 1)
});
if (g.UserInput.TryGet(ComfyUIBackendExtension.StyleModelMergeStrength, out double mergeStrength) && mergeStrength < 1)
{
styled = g.CreateNode("ConditioningAverage", new JObject()
{
["conditioning_to"] = NodePath(styled, 0),
["conditioning_from"] = g.FinalPrompt,
["conditioning_to_strength"] = mergeStrength
});
}
if (g.UserInput.TryGet(ComfyUIBackendExtension.StyleModelApplyStart, out double applyAt) && applyAt > 0)
{
string cond1 = g.CreateNode("ConditioningSetTimestepRange", new JObject()
{
["conditioning"] = g.FinalPrompt,
["start"] = 0,
["end"] = applyAt
});
string cond2 = g.CreateNode("ConditioningSetTimestepRange", new JObject()
{
["conditioning"] = NodePath(styled, 0),
["start"] = applyAt,
["end"] = 1
});
string combined = g.CreateNode("ConditioningCombine", new JObject()
{
["conditioning_1"] = NodePath(cond1, 0),
["conditioning_2"] = NodePath(cond2, 0),
});
g.FinalPrompt = [combined, 0];
}
else
{
g.FinalPrompt = [styled, 0];
}
}
}
string visionLoaderId = null;
string getVisionLoader()
{
if (visionLoaderId is not null)
{
return visionLoaderId;
}
string visModelName = "clip_vision_g.safetensors";
visModelName = g.RequireVisionModel(visModelName, "https://huggingface.co/stabilityai/control-lora/resolve/main/revision/clip_vision_g.safetensors", "9908329b3ead722a693ea400fab1d7c9ec91d6736fd194a94d20d793457f9c2e", T2IParamTypes.ClipVisionModel);
visionLoaderId = g.CreateNode("CLIPVisionLoader", new JObject()
{
["clip_name"] = visModelName
});
return visionLoaderId;
}
double revisionStrength = g.UserInput.Get(T2IParamTypes.ReVisionStrength, 0);
if (revisionStrength > 0)
{
bool autoZero = g.UserInput.Get(T2IParamTypes.RevisionZeroPrompt, false);
if ((g.UserInput.TryGet(T2IParamTypes.Prompt, out string promptText) && string.IsNullOrWhiteSpace(promptText)) || autoZero)
{
string zeroed = g.CreateNode("ConditioningZeroOut", new JObject()
{
["conditioning"] = g.FinalPrompt
});
g.FinalPrompt = [zeroed, 0];
}
if ((g.UserInput.TryGet(T2IParamTypes.NegativePrompt, out string negPromptText) && string.IsNullOrWhiteSpace(negPromptText)) || autoZero)
{
string zeroed = g.CreateNode("ConditioningZeroOut", new JObject()
{
["conditioning"] = g.FinalNegativePrompt
});
g.FinalNegativePrompt = [zeroed, 0];
}
if (!g.UserInput.TryGet(T2IParamTypes.Model, out T2IModel model) || model.ModelClass is null ||
(model.ModelClass.CompatClass?.ID != "stable-diffusion-xl-v1"/* && model.ModelClass.CompatClass?.ID != "stable-diffusion-v3-medium"*/))
{
throw new SwarmUserErrorException($"Model type must be SDXL for ReVision (currently is {model?.ModelClass?.Name ?? "Unknown"}). Set ReVision Strength to 0 if you just want IP-Adapter.");
}
for (int i = 0; i < images.Count; i++)
{
WGNodeData imageLoader = g.LoadImage(images[i], "${promptimages." + i + "}", false);
string encoded = g.CreateNode("CLIPVisionEncode", new JObject()
{
["clip_vision"] = NodePath($"{getVisionLoader()}", 0),
["image"] = imageLoader.Path,
["crop"] = "none"
});
string unclipped = g.CreateNode("unCLIPConditioning", new JObject()
{
["conditioning"] = g.FinalPrompt,
["clip_vision_output"] = NodePath(encoded, 0),
["strength"] = revisionStrength,
["noise_augmentation"] = 0
});
g.FinalPrompt = [unclipped, 0];
}
}
if (g.UserInput.Get(T2IParamTypes.UseReferenceOnly, false))
{
WGNodeData firstImgNode = g.LoadImage(images[0], "${promptimages.0}", true);
WGNodeData lastEncoded = firstImgNode.AsLatentImage(g.CurrentVae);
for (int i = 1; i < images.Count; i++)
{
WGNodeData newImgNode = g.LoadImage(images[i], "${promptimages." + i + "}", true);
WGNodeData newEncoded = newImgNode.AsLatentImage(g.CurrentVae);
string newBatched = g.CreateNode("LatentBatch", new JObject()
{
["samples1"] = lastEncoded.Path,
["samples2"] = newEncoded.Path
});
lastEncoded = lastEncoded.WithPath([newBatched, 0]);
}
g.CurrentMedia = g.CurrentMedia.AsLatentImage(g.CurrentVae);
string referencedModel = g.CreateNode("SwarmReferenceOnly", new JObject()
{
["model"] = g.CurrentModel.Path,
["reference"] = lastEncoded.Path,
["latent"] = g.CurrentMedia.Path
});
g.CurrentModel = g.CurrentModel.WithPath([referencedModel, 0]);
g.CurrentMedia = g.CurrentMedia.WithPath([referencedModel, 1]);
g.DefaultPreviews = "second";
}
if (g.UserInput.TryGet(ComfyUIBackendExtension.UseIPAdapterForRevision, out string ipAdapter) && ipAdapter != "None")
{
string getIPAvisionLoader()
{
string ipAdapterVisionLoader = getVisionLoader();
if (!g.Features.Contains("cubiqipadapterunified"))
{
if ((ipAdapter.Contains("sd15") && !ipAdapter.Contains("vit-G")) || ipAdapter.Contains("vit-h"))
{
string targetName = "clip_vision_h.safetensors";
targetName = g.RequireVisionModel(targetName, "https://huggingface.co/h94/IP-Adapter/resolve/main/models/image_encoder/model.safetensors", "6ca9667da1ca9e0b0f75e46bb030f7e011f44f86cbfb8d5a36590fcd7507b030", T2IParamTypes.ClipVisionModel);
ipAdapterVisionLoader = g.CreateNode("CLIPVisionLoader", new JObject()
{
["clip_name"] = targetName
});
}
}
return ipAdapterVisionLoader;
}
if (g.Features.Contains("cubiqipadapterunified"))
{
g.RequireVisionModel("CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors", "https://huggingface.co/h94/IP-Adapter/resolve/main/models/image_encoder/model.safetensors", "6ca9667da1ca9e0b0f75e46bb030f7e011f44f86cbfb8d5a36590fcd7507b030");
g.RequireVisionModel("CLIP-ViT-bigG-14-laion2B-39B-b160k.safetensors", "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/image_encoder/model.safetensors", "657723e09f46a7c3957df651601029f66b1748afb12b419816330f16ed45d64d");
}
WGNodeData lastImage = g.LoadImage(images[0], "${promptimages.0}", false);
for (int i = 1; i < images.Count; i++)
{
WGNodeData newImg = g.LoadImage(images[i], "${promptimages." + i + "}", false);
string batched = g.CreateNode("ImageBatch", new JObject()
{
["image1"] = lastImage.Path,
["image2"] = newImg.Path
});
lastImage = lastImage.WithPath([batched, 0]);
}
if (g.Features.Contains("cubiqipadapterunified"))
{
string presetLow = ipAdapter.ToLowerFast();
bool isXl = g.CurrentCompatClass() == "stable-diffusion-xl-v1";
void requireIPAdapterModel(string name, string url, string hash)
{
if (IPAdapterModelsValid.ContainsKey(name))
{
return;
}
string filePath = Utilities.CombinePathWithAbsolute(Program.ServerSettings.Paths.ActualModelRoot, $"ipadapter/{name}");
g.DownloadModel(name, filePath, url, hash);
IPAdapterModelsValid.TryAdd(name, name);
}
void requireLora(string name, string url, string hash)
{
if (IPAdapterModelsValid.ContainsKey($"LORA-{name}"))
{
return;
}
string filePath = Utilities.CombinePathWithAbsolute(Program.ServerSettings.Paths.ActualModelRoot, Program.ServerSettings.Paths.SDLoraFolder.Split(';')[0], $"ipadapter/{name}");
g.DownloadModel(name, filePath, url, hash);
IPAdapterModelsValid.TryAdd($"LORA-{name}", name);
}
// IPAdapter model links @ https://github.com/cubiq/ComfyUI_IPAdapter_plus?tab=readme-ov-file#installation
// required model for any given type @ https://github.com/cubiq/ComfyUI_IPAdapter_plus/blob/main/utils.py#L29
if (presetLow.StartsWith("file:"))
{
// no autodownload
}
else if (presetLow.StartsWith("light"))
{
if (isXl) { throw new SwarmUserErrorException("IP-Adapter light model is not supported for SDXL"); }
else { requireIPAdapterModel("sd15_light_v11.bin", "https://huggingface.co/h94/IP-Adapter/resolve/main/models/ip-adapter_sd15_light_v11.bin", "350b63a57847c163e2e984b01090f85ffe60eaae20f32b2b2c9e1ccc7ddd972b"); }
}
else if (presetLow.StartsWith("standard"))
{
if (isXl) { requireIPAdapterModel("ip-adapter_sdxl_vit-h.safetensors", "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/ip-adapter_sdxl_vit-h.safetensors", "ebf05d918348aec7abb02a5e9ecef77e0aaea6914a5c4ea13f50d45eb1681831"); }
else { requireIPAdapterModel("ip-adapter_sd15.safetensors", "https://huggingface.co/h94/IP-Adapter/resolve/main/models/ip-adapter_sd15.safetensors", "289b45f16d043d0bf542e45831f971dcdaabe18b656f11e86d9dfba7e9ee3369"); }
}
else if (presetLow.StartsWith("vit-g"))
{
if (isXl) { requireIPAdapterModel("ip-adapter_sdxl.safetensors", "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/ip-adapter_sdxl.safetensors", "ba1002529e783604c5f326d49f0122025392d1d20ac8d573b3eeb3e6dea4ebb6"); }
else { requireIPAdapterModel("ip-adapter_sd15_vit-G.safetensors", "https://huggingface.co/h94/IP-Adapter/resolve/main/models/ip-adapter_sd15_vit-G.safetensors", "a26f736af07bb341a83dfea23713531d0575760e8ed947c68cb31a4c62d9c90b"); }
}
else if (presetLow.StartsWith("plus ("))
{
if (isXl) { requireIPAdapterModel("ip-adapter-plus_sdxl_vit-h.safetensors", "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/ip-adapter-plus_sdxl_vit-h.safetensors", "3f5062b8400c94b7159665b21ba5c62acdcd7682262743d7f2aefedef00e6581"); }
else { requireIPAdapterModel("ip-adapter-plus_sd15.safetensors", "https://huggingface.co/h94/IP-Adapter/resolve/main/models/ip-adapter-plus_sd15.safetensors", "a1c250be40455cc61a43da1201ec3f1edaea71214865fb47f57927e06cbe4996"); }
}
else if (presetLow.StartsWith("plus face"))
{
if (isXl) { requireIPAdapterModel("ip-adapter-plus-face_sdxl_vit-h.safetensors", "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/ip-adapter-plus-face_sdxl_vit-h.safetensors", "677ad8860204f7d0bfba12d29e6c31ded9beefdf3e4bbd102518357d31a292c1"); }
else { requireIPAdapterModel("ip-adapter-plus-face_sd15.safetensors", "https://huggingface.co/h94/IP-Adapter/resolve/main/models/ip-adapter-plus-face_sd15.safetensors", "1c9edc21af6f737dc1d6e0e734190e976cfacf802d6b024b77aa3be922f7569b"); }
}
else if (presetLow.StartsWith("full"))
{
if (isXl) { throw new SwarmUserErrorException("IP-Adapter full face model is not supported for SDXL"); }
else { requireIPAdapterModel("full_face_sd15.safetensors", "https://huggingface.co/h94/IP-Adapter/resolve/main/models/ip-adapter-full-face_sd15.safetensors", "f4a17fb643bf876235a45a0e87a49da2855be6584b28ca04c62a97ab5ff1c6f3"); }
}
else if (presetLow == "faceid")
{
if (isXl)
{
requireIPAdapterModel("ip-adapter-faceid_sdxl.bin", "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid_sdxl.bin", "f455fed24e207c878ec1e0466b34a969d37bab857c5faa4e8d259a0b4ff63d7e");
requireLora("ip-adapter-faceid_sdxl_lora.safetensors", "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid_sdxl_lora.safetensors", "4fcf93d6e8dc8dd18f5f9e51c8306f369486ed0aa0780ade9961308aff7f0d64");
}
else
{
requireIPAdapterModel("ip-adapter-faceid_sd15.bin", "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid_sd15.bin", "201344e22e6f55849cf07ca7a6e53d8c3b001327c66cb9710d69fd5da48a8da7");
requireLora("ip-adapter-faceid_sd15_lora.safetensors", "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid_sd15_lora.safetensors", "70699f0dbfadd47de1f81d263cf4c86bd4b7271d841304af9b340b3a7f38e86a");
}
}
else if (presetLow.StartsWith("faceid plus -"))
{
if (isXl) { throw new SwarmUserErrorException("IP-Adapter FaceID plus model is not supported for SDXL"); }
else
{
requireIPAdapterModel("ip-adapter-faceid-plus_sd15.bin", "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid-plus_sd15.bin", "252fb53e0d018489d9e7f9b9e2001a52ff700e491894011ada7cfb471e0fadf2");
requireLora("ip-adapter-faceid-plus_sd15_lora.safetensors", "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid-plus_sd15_lora.safetensors", "3f00341d11e5e7b5aadf63cbdead09ef82eb28669156161cf1bfc2105d4ff1cd");
}
}
else if (presetLow.StartsWith("faceid plus v2"))
{
if (isXl)
{
requireIPAdapterModel("ip-adapter-faceid-plusv2_sdxl.bin", "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid-plusv2_sdxl.bin", "c6945d82b543700cc3ccbb98d363b837e9c596281607857c74b713a876daf5fb");
requireLora("ip-adapter-faceid-plusv2_sdxl_lora.safetensors", "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid-plusv2_sdxl_lora.safetensors", "f24b4bb2dad6638a09c00f151cde84991baf374409385bcbab53c1871a30cb7b");
}
else
{
requireIPAdapterModel("ip-adapter-faceid-plusv2_sd15.bin", "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid-plusv2_sd15.bin", "26d0d86a1d60d6cc811d3b8862178b461e1eeb651e6fe2b72ba17aa95411e313");
requireLora("ip-adapter-faceid-plusv2_sd15_lora.safetensors", "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid-plusv2_sd15_lora.safetensors", "8abff87a15a049f3e0186c2e82c1c8e77783baf2cfb63f34c412656052eb57b0");
}
}
else if (presetLow.StartsWith("faceid portrait unnorm"))
{
if (isXl) { requireIPAdapterModel("ip-adapter-faceid-portrait_sdxl_unnorm.bin", "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid-portrait_sdxl_unnorm.bin", "220bb86e205393a3d0411631cb473caddbf35fd371be2905ca9008818170db55"); }
else { throw new SwarmUserErrorException("IP-Adapter FaceID Portrait UnNorm model is only supported for SDXL"); }
}
else if (presetLow.StartsWith("faceid portrait"))
{
if (isXl) { requireIPAdapterModel("ip-adapter-faceid-portrait_sdxl.bin", "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid-portrait_sdxl.bin", "5631ce7824cdafd2db37c5e85b985730a95ff59c5b4fc80c2b79b0bee5711512"); }
else { requireIPAdapterModel("ip-adapter-faceid-portrait-v11_sd15.bin", "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid-portrait-v11_sd15.bin", "a48cb4f89ed18e02c6000f65aa9efec452e87eaed4a1bc9fcf4a460c8d0e3bc6"); }
}
string ipAdapterLoader;
if (presetLow.StartsWith("file:"))
{
ipAdapterLoader = g.CreateNode("IPAdapterModelLoader", new JObject()
{
["ipadapter_file"] = ipAdapter["file:".Length..]
});
}
else if (presetLow.StartsWith("faceid"))
{
ipAdapterLoader = g.CreateNode("IPAdapterUnifiedLoaderFaceID", new JObject()
{
["model"] = g.CurrentModel.Path,
["preset"] = ipAdapter,
["lora_strength"] = 0.6,
["provider"] = "CPU"
});
}
else
{
ipAdapterLoader = g.CreateNode("IPAdapterUnifiedLoader", new JObject()
{
["model"] = g.CurrentModel.Path,
["preset"] = ipAdapter
});
}
double ipAdapterStart = g.UserInput.Get(ComfyUIBackendExtension.IPAdapterStart, 0.0);
double ipAdapterEnd = g.UserInput.Get(ComfyUIBackendExtension.IPAdapterEnd, 1.0);
if (ipAdapterStart >= ipAdapterEnd)
{
throw new SwarmUserErrorException($"IP-Adapter Start must be less than IP-Adapter End.");
}
if (presetLow.StartsWith("file:"))
{
string weightType = g.UserInput.Get(ComfyUIBackendExtension.IPAdapterWeightType, "linear");
if (weightType == "standard") { weightType = "linear"; }
else if (weightType == "prompt is more important") { weightType = "ease out"; }
string ipAdapterNode = g.CreateNode("IPAdapterAdvanced", new JObject()
{
["model"] = g.CurrentModel.Path,
["ipadapter"] = NodePath(ipAdapterLoader, 0),
["image"] = lastImage.Path,
["weight"] = g.UserInput.Get(ComfyUIBackendExtension.IPAdapterWeight, 1),
["start_at"] = ipAdapterStart,
["end_at"] = ipAdapterEnd,
["weight_type"] = weightType,
["combine_embeds"] = "concat",
["embeds_scaling"] = "V only",
["clip_vision"] = NodePath(getVisionLoader(), 0)
});
g.CurrentModel = g.CurrentModel.WithPath([ipAdapterNode, 0]);
}
else
{
string ipAdapterNode = g.CreateNode("IPAdapter", new JObject()
{
["model"] = NodePath(ipAdapterLoader, 0),
["ipadapter"] = NodePath(ipAdapterLoader, 1),
["image"] = lastImage.Path,
["weight"] = g.UserInput.Get(ComfyUIBackendExtension.IPAdapterWeight, 1),
["start_at"] = ipAdapterStart,
["end_at"] = ipAdapterEnd,
["weight_type"] = g.UserInput.Get(ComfyUIBackendExtension.IPAdapterWeightType, "standard")
});
g.CurrentModel = g.CurrentModel.WithPath([ipAdapterNode, 0]);
}
}
else if (g.Features.Contains("cubiqipadapter"))
{
string ipAdapterLoader = g.CreateNode("IPAdapterModelLoader", new JObject()
{
["ipadapter_file"] = ipAdapter
});
string ipAdapterNode = g.CreateNode("IPAdapterApply", new JObject()
{
["ipadapter"] = NodePath(ipAdapterLoader, 0),
["model"] = g.CurrentModel.Path,
["image"] = lastImage.Path,
["clip_vision"] = NodePath(getIPAvisionLoader(), 0),
["weight"] = g.UserInput.Get(ComfyUIBackendExtension.IPAdapterWeight, 1),
["noise"] = 0,
["weight_type"] = "original"
});
g.CurrentModel = g.CurrentModel.WithPath([ipAdapterNode, 0]);
}
else
{
string ipAdapterNode = g.CreateNode("IPAdapter", new JObject()
{
["model"] = g.CurrentModel.Path,
["image"] = lastImage.Path,
["clip_vision"] = NodePath(getIPAvisionLoader(), 0),
["weight"] = g.UserInput.Get(ComfyUIBackendExtension.IPAdapterWeight, 1),
["model_name"] = ipAdapter,
["dtype"] = "fp16" // TODO: ...???
});
g.CurrentModel = g.CurrentModel.WithPath([ipAdapterNode, 0]);
}
}
}
}, -7);
#endregion
#region Negative Prompt
AddStep(g =>
{
g.FinalNegativePrompt = g.CreateConditioning(g.UserInput.Get(T2IParamTypes.NegativePrompt, ""), g.CurrentTextEnc.Path, g.UserInput.Get(T2IParamTypes.Model), false, "7");
}, -7);
#endregion
#region ControlNet
AddStep(g =>
{
WGNodeData firstImageNode = null;
for (int i = 0; i < 3; i++)
{
T2IParamTypes.ControlNetParamHolder controlnetParams = T2IParamTypes.Controlnets[i];
if (g.UserInput.TryGet(controlnetParams.Strength, out double controlStrength))
{
string imageInput = "${" + controlnetParams.Image.Type.ID + "}";
WGNodeData imageNodeActual = null;
if (g.UserInput.TryGet(controlnetParams.Image, out Image img))
{
imageNodeActual = g.LoadImage(img, imageInput, true);
}
else
{
if (i == 0 ? g.BasicInputImage is null : firstImageNode is null)
{
Logs.Verbose($"Following error relates to parameters: {g.UserInput.ToJSON().ToDenseDebugString()}");
throw new SwarmUserErrorException("Must specify either a ControlNet Image, or Init image. Or turn off ControlNet if not wanted.");
}