forked from mcmonkeyprojects/SwarmUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkflowGenerator.cs
More file actions
2783 lines (2684 loc) · 120 KB
/
WorkflowGenerator.cs
File metadata and controls
2783 lines (2684 loc) · 120 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 System.Text;
using System.Collections.Generic;
using System.IO;
using SwarmUI.Core;
using SwarmUI.Media;
using SwarmUI.Text2Image;
using SwarmUI.Utils;
using Newtonsoft.Json.Linq;
using FreneticUtilities.FreneticExtensions;
using FreneticUtilities.FreneticToolkit;
namespace SwarmUI.Builtin_ComfyUIBackend;
/// <summary>Helper class for generating ComfyUI workflows from input parameters.</summary>
public partial class WorkflowGenerator
{
/// <summary>Represents a step in the workflow generation process.</summary>
/// <param name="Action">The action to take.</param>
/// <param name="Priority">The priority to apply it at.
/// These are such from lowest to highest.
/// "-10" is the priority of the first core pre-init,
/// "0" is before final outputs,
/// "10" is final output.</param>
public record class WorkflowGenStep(Action<WorkflowGenerator> Action, double Priority);
/// <summary>Callable steps for modifying workflows as they go.</summary>
public static List<WorkflowGenStep> Steps = [];
/// <summary>Callable steps for configuring model generation.</summary>
public static List<WorkflowGenStep> ModelGenSteps = [];
/// <summary>Can be set to globally block custom nodes, if needed.</summary>
public static volatile bool RestrictCustomNodes = false;
/// <summary>Supported Features of the comfy backend.</summary>
public HashSet<string> Features = [];
/// <summary>Helper tracker for CLIP Models that are loaded (to skip a datadrive read from being reused every time).</summary>
public static ConcurrentDictionary<string, string> ClipModelsValid = [];
/// <summary>Helper tracker for Vision Models that are loaded (to skip a datadrive read from being reused every time).</summary>
public static ConcurrentDictionary<string, string> VisionModelsValid = [];
/// <summary>Helper tracker for IP Adapter Models that are loaded (to skip a datadrive read from being reused every time).</summary>
public static ConcurrentDictionary<string, string> IPAdapterModelsValid = [];
/// <summary>Register a new step to the workflow generator.</summary>
public static void AddStep(Action<WorkflowGenerator> step, double priority)
{
Steps.Add(new(step, priority));
Steps = [.. Steps.OrderBy(s => s.Priority)];
}
/// <summary>Register a new step to the workflow generator.</summary>
public static void AddModelGenStep(Action<WorkflowGenerator> step, double priority)
{
ModelGenSteps.Add(new(step, priority));
ModelGenSteps = [.. ModelGenSteps.OrderBy(s => s.Priority)];
}
static WorkflowGenerator()
{
WorkflowGeneratorSteps.Register();
}
/// <summary>Lock for when ensuring the backend has valid models.</summary>
public static MultiLockSet<string> ModelDownloaderLocks = new(32);
/// <summary>Helper to create a NodePath: [nodeId, outputIndex].</summary>
public static JArray NodePath(string node, int index)
{
return [node, index];
}
/// <summary>The raw user input data.</summary>
public T2IParamInput UserInput;
/// <summary>The output workflow object.</summary>
public JObject Workflow;
/// <summary>Current node data trackers for core data that passes throughout the workflow.</summary>
public WGNodeData CurrentModel, CurrentTextEnc, CurrentVae, CurrentAudioVae, CurrentMedia, BasicInputImage;
/// <summary>Lastmost node ID for key input trackers.</summary>
public JArray
FinalMask = null,
FinalPrompt = ["6", 0],
FinalNegativePrompt = ["7", 0],
FinalTrimLatent = null,
LoadingModel = null, LoadingClip = null, LoadingVAE = null;
[Obsolete("Use BasicInputImage instead.")]
public JArray FinalInputImage
{
get => BasicInputImage?.Path ?? ["5", 0];
set => BasicInputImage = new WGNodeData(value, this, WGNodeData.DT_IMAGE, CurrentCompat());
}
[Obsolete("Use CurrentModel instead.")]
public JArray FinalModel
{
get => CurrentModel?.Path ?? ["4", 0];
set => CurrentModel = new WGNodeData(value, this, WGNodeData.DT_MODEL, CurrentCompat());
}
[Obsolete("Use CurrentTextEnc instead.")]
public JArray FinalClip
{
get => CurrentTextEnc?.Path ?? ["4", 1];
set => CurrentTextEnc = new WGNodeData(value, this, WGNodeData.DT_TEXTENC, CurrentCompat());
}
[Obsolete("Use CurrentVae instead.")]
public JArray FinalVae
{
get => CurrentVae?.Path ?? ["4", 2];
set => CurrentVae = new WGNodeData(value, this, WGNodeData.DT_VAE, CurrentCompat());
}
[Obsolete("Use CurrentMedia instead.")]
public JArray FinalLatentImage
{
get => CurrentMedia is null ? ["5", 0] : CurrentMedia.AsLatentImage(CurrentVae).Path;
set => CurrentMedia = new WGNodeData(value, this, WGNodeData.DT_LATENT_IMAGE, CurrentCompat());
}
[Obsolete("Use CurrentMedia instead.")]
public JArray FinalSamples
{
get => CurrentMedia is null ? ["10", 0] : CurrentMedia.AsLatentImage(CurrentVae).Path;
set => CurrentMedia = new WGNodeData(value, this, WGNodeData.DT_LATENT_IMAGE, CurrentCompat());
}
[Obsolete("Use CurrentMedia instead.")]
public JArray FinalImageOut
{
get => CurrentMedia?.AsRawImage(CurrentVae)?.Path;
set => CurrentMedia = new WGNodeData(value, this, WGNodeData.DT_IMAGE, CurrentCompat());
}
/// <summary>If true, something has required the workflow stop now.</summary>
public bool SkipFurtherSteps = false;
/// <summary>What model currently matches <see cref="CurrentModel"/>.</summary>
public T2IModel FinalLoadedModel;
/// <summary>What models currently match <see cref="CurrentModel"/> (including eg loras).</summary>
public List<T2IModel> FinalLoadedModelList = [];
/// <summary>Mapping of any extra nodes to keep track of, Name->ID, eg "MyNode" -> "15".</summary>
public Dictionary<string, string> NodeHelpers = [];
/// <summary>Last used ID, tracked to safely add new nodes with sequential IDs. Note that this starts at 100, as below 100 is reserved for constant node IDs.</summary>
public int LastID = 100;
/// <summary>Model folder separator format, if known.</summary>
public string ModelFolderFormat;
/// <summary>Type id ('Base', 'Refiner') of the current loading model.</summary>
public string LoadingModelType;
/// <summary>If true, user-selected VAE may be wrong, so ignore it.</summary>
public bool NoVAEOverride = false;
/// <summary>If true, the generator is currently working on the refiner stage.</summary>
public bool IsRefinerStage = false;
/// <summary>If true, the generator is currently working on Image2Video.</summary>
public bool IsImageToVideo = false;
/// <summary>If true, the generator is currently working on Image2Video-SwapModel.</summary>
public bool IsImageToVideoSwap = false;
/// <summary>If true, the main sampler should add noise. If false, it shouldn't.</summary>
public bool MainSamplerAddNoise = true;
/// <summary>If true, Differential Diffusion node has been attached to the current model.</summary>
public bool IsDifferentialDiffusion = false;
/// <summary>Outputs of <see cref="CreateImageMaskCrop(JArray, JArray, int, JArray, T2IModel, double, double)"/> if used for the main image.</summary>
public ImageMaskCropData MaskShrunkInfo = new(null, null, null, null);
/// <summary>Gets the current loaded model class.</summary>
public T2IModelClass CurrentModelClass()
{
FinalLoadedModel ??= UserInput.Get(T2IParamTypes.Model, null);
return FinalLoadedModel?.ModelClass;
}
/// <summary>Gets the current loaded model compat class.</summary>
public T2IModelCompatClass CurrentCompat()
{
return CurrentModelClass()?.CompatClass;
}
/// <summary>Gets the current loaded model compat class ID.</summary>
public string CurrentCompatClass()
{
return CurrentModelClass()?.CompatClass?.ID;
}
/// <summary>Gets a dynamic ID within a semi-stable registration set.</summary>
public string GetStableDynamicID(int index, int offset)
{
for (int i = 0; i < 99999; i++)
{
int id = 1000 + index + offset + i;
string result = $"{id}";
if (!HasNode(result))
{
return result;
}
}
throw new Exception("Failed to find a stable dynamic ID.");
}
/// <summary>Creates a new node with the given class type and configuration action, and optional manual ID.</summary>
public string CreateNode(string classType, Action<string, JObject> configure, string id = null)
{
id ??= $"{LastID++}";
JObject obj = new() { ["class_type"] = classType };
configure(id, obj);
Workflow[id] = obj;
return id;
}
/// <summary>Creates a new node with the given class type and input data, and optional manual ID.</summary>
public string CreateNode(string classType, JObject input, string id = null, bool idMandatory = true)
{
string lookup = $"__generic_node__{classType}___{input}";
if ((id is null || !idMandatory) && NodeHelpers.TryGetValue(lookup, out string existingNode))
{
return existingNode;
}
string result = CreateNode(classType, (_, n) => n["inputs"] = input, id);
NodeHelpers[lookup] = result;
return result;
}
/// <summary>Helper to download a core model file required by the workflow.</summary>
public void DownloadModel(string name, string filePath, string url, string hash)
{
if (File.Exists(filePath))
{
return;
}
lock (ModelDownloaderLocks.GetLock(name))
{
if (File.Exists(filePath)) // Double-check in case another thread downloaded it
{
return;
}
Logs.Info($"Downloading {name} to {filePath}...");
double nextPerc = 0.05;
string tmpPath = $"{filePath}.tmp";
try
{
if (File.Exists(tmpPath))
{
File.Delete(tmpPath);
}
Utilities.DownloadFile(url, tmpPath, (bytes, total, perSec) =>
{
double perc = bytes / (double)total;
if (perc >= nextPerc)
{
Logs.Info($"{name} download at {perc * 100:0.0}%...");
// TODO: Send a signal back so a progress bar can be displayed on a UI
nextPerc = Math.Round(perc / 0.05) * 0.05 + 0.05;
}
}, verifyHash: hash).Wait();
File.Move(tmpPath, filePath);
}
catch (Exception ex)
{
Logs.Error($"Failed to download {name} from {url}: {ex.Message}");
File.Delete(tmpPath);
throw new SwarmReadableErrorException("Required model download failed.");
}
Logs.Info($"Downloading complete, continuing.");
}
}
/// <summary>Loads and applies LoRAs in the user parameters for the given LoRA confinement ID, as a Set CLIP Hooks node.</summary>
public JArray CreateHookLorasForConfinement(int confinement, JArray clip)
{
if (!UserInput.TryGet(T2IParamTypes.Loras, out List<string> loras))
{
return clip;
}
List<string> weights = UserInput.Get(T2IParamTypes.LoraWeights);
List<string> tencWeights = UserInput.Get(T2IParamTypes.LoraTencWeights);
List<string> confinements = UserInput.Get(T2IParamTypes.LoraSectionConfinement);
if (confinement > 0 && (confinements is null || confinements.Count == 0))
{
return clip;
}
T2IModelHandler loraHandler = Program.T2IModelSets["LoRA"];
JArray last = null;
for (int i = 0; i < loras.Count; i++)
{
int confinementId = -1;
if (confinements is not null && confinements.Count > i)
{
confinementId = int.Parse(confinements[i]);
}
if (confinementId != confinement)
{
continue;
}
if (!loraHandler.Models.TryGetValue(loras[i] + ".safetensors", out T2IModel lora))
{
if (!loraHandler.Models.TryGetValue(loras[i], out lora))
{
throw new SwarmUserErrorException($"LoRA Model '{loras[i]}' not found in the model set.");
}
}
FinalLoadedModelList.Add(lora);
if (Program.ServerSettings.Metadata.ImageMetadataIncludeModelHash)
{
lora.GetOrGenerateTensorHashSha256(); // Ensure hash is preloaded early
}
float weight = weights is null || i >= weights.Count ? 1 : float.Parse(weights[i]);
float tencWeight = tencWeights is null || i >= tencWeights.Count ? weight : float.Parse(tencWeights[i]);
string newId = CreateNode("CreateHookLora", new JObject()
{
["prev_hooks"] = last,
["lora_name"] = lora.ToString(ModelFolderFormat),
["strength_model"] = weight,
["strength_clip"] = tencWeight
}, GetStableDynamicID(2500, i), false);
last = [newId, 0];
}
if (last is null)
{
return clip;
}
string newHooks = CreateNode("SetClipHooks", new JObject()
{
["hooks"] = last,
["clip"] = clip,
["apply_to_conds"] = true,
["schedule_clip"] = false
}, GetStableDynamicID(2500, loras.Count), false);
return [newHooks, 0];
}
/// <summary>Loads and applies LoRAs in the user parameters for the given LoRA confinement ID.</summary>
public (JArray, JArray) LoadLorasForConfinement(int confinement, JArray model, JArray clip)
{
if (!UserInput.TryGet(T2IParamTypes.Loras, out List<string> loras))
{
return (model, clip);
}
List<string> weights = UserInput.Get(T2IParamTypes.LoraWeights);
List<string> tencWeights = UserInput.Get(T2IParamTypes.LoraTencWeights);
List<string> confinements = UserInput.Get(T2IParamTypes.LoraSectionConfinement);
if (confinement > 0 && (confinements is null || confinements.Count == 0))
{
return (model, clip);
}
T2IModelHandler loraHandler = Program.T2IModelSets["LoRA"];
for (int i = 0; i < loras.Count; i++)
{
int confinementId = -1;
if (confinements is not null && confinements.Count > i)
{
confinementId = int.Parse(confinements[i]);
}
if (confinementId != confinement)
{
continue;
}
if (!loraHandler.Models.TryGetValue(loras[i] + ".safetensors", out T2IModel lora))
{
if (!loraHandler.Models.TryGetValue(loras[i], out lora))
{
throw new SwarmUserErrorException($"LoRA Model '{loras[i]}' not found in the model set.");
}
}
FinalLoadedModelList.Add(lora);
if (Program.ServerSettings.Metadata.ImageMetadataIncludeModelHash)
{
lora.GetOrGenerateTensorHashSha256(); // Ensure hash is preloaded early
}
float weight = weights is null || i >= weights.Count ? 1 : float.Parse(weights[i]);
float tencWeight = tencWeights is null || i >= tencWeights.Count ? weight : float.Parse(tencWeights[i]);
string id = GetStableDynamicID(2000, i);
string specialFormat = FinalLoadedModel?.Metadata?.SpecialFormat;
if (IsFlux() && (specialFormat == "nunchaku" || specialFormat == "nunchaku-fp4"))
{
// This is dirty to use this alt node, but it seems required for Nunchaku.
string newId = CreateNode("NunchakuFluxLoraLoader", new JObject()
{
["model"] = model,
["lora_name"] = lora.ToString(ModelFolderFormat),
["lora_strength"] = weight
}, id, false);
model = [newId, 0];
}
else if (CurrentCompat()?.LorasTargetTextEnc == false || tencWeight == 0)
{
string newId = CreateNode("LoraLoaderModelOnly", new JObject()
{
["model"] = model,
["lora_name"] = lora.ToString(ModelFolderFormat),
["strength_model"] = weight,
}, id, false);
model = [newId, 0];
}
else
{
string newId = CreateNode("LoraLoader", new JObject()
{
["model"] = model,
["clip"] = clip,
["lora_name"] = lora.ToString(ModelFolderFormat),
["strength_model"] = weight,
["strength_clip"] = tencWeight
}, id, false);
model = [newId, 0];
clip = [newId, 1];
}
}
return (model, clip);
}
public string CreateAudioLoadNode(AudioFile audio, string param, string nodeId = null)
{
// TODO: Fallback for base LoadAudio node?
return CreateNode("SwarmLoadAudioB64", new JObject()
{
["audio_base64"] = audio.AsBase64
}, nodeId);
}
/// <summary>Creates a new node to load an image.</summary>
[Obsolete("Use LoadImage instead.")]
public string CreateLoadImageNode(ImageFile img, string param, bool resize, string nodeId = null, int? width = null, int? height = null)
{
return LoadImage(img, param, resize, nodeId, width, height).Path[0].ToString();
}
/// <summary>Creates a new node to load an image.</summary>
public WGNodeData LoadImage(ImageFile img, string param, bool resize, string nodeId = null, int? width = null, int? height = null)
{
string result;
if (Features.Contains("comfy_loadimage_b64") && !RestrictCustomNodes)
{
if (img.Type.MetaType == MediaMetaType.Image)
{
int imgWidth = width ?? UserInput.GetImageWidth();
int imgHeight = height ?? UserInput.GetImageHeight();
result = CreateNode("SwarmLoadImageB64", new JObject()
{
["image_base64"] = (resize ? img.Resize(imgWidth, imgHeight) : img).AsBase64
}, nodeId);
return new([result, 0], this, WGNodeData.DT_IMAGE, CurrentCompat()) { Width = imgWidth, Height = imgHeight };
}
else
{
WGNodeData attachedAudio = null;
if (img.Type.MetaType == MediaMetaType.Video)
{
result = CreateNode("SwarmLoadVideoB64", new JObject()
{
["video_base64"] = img.AsBase64
}, resize ? null : nodeId);
string splitNode = CreateNode("GetVideoComponents", new JObject()
{
["video"] = NodePath(result, 0)
});
NodeHelpers["video_components_split"] = splitNode;
result = splitNode;
attachedAudio = new([splitNode, 1], this, WGNodeData.DT_AUDIO, CurrentCompat());
}
else
{
result = CreateNode("SwarmLoadImageB64", new JObject()
{
["image_base64"] = img.AsBase64
}, resize ? null : nodeId);
}
int? imgWidth = null;
int? imgHeight = null;
if (resize)
{
imgWidth = UserInput.GetImageWidth();
imgHeight = UserInput.GetImageHeight();
result = CreateNode("ImageScale", new JObject()
{
["image"] = NodePath(result, 0),
["width"] = imgWidth,
["height"] = imgHeight,
["upscale_method"] = "lanczos",
["crop"] = "disabled"
}, nodeId);
}
return new([result, 0], this, WGNodeData.DT_VIDEO, CurrentCompat()) { AttachedAudio = attachedAudio, Width = imgWidth, Height = imgHeight };
}
}
else
{
result = CreateNode("LoadImage", new JObject()
{
["image"] = param
}, nodeId);
return new([result, 0], this, WGNodeData.DT_IMAGE, CurrentCompat());
}
}
/// <summary>For <see cref="CreateImageMaskCrop(JArray, JArray, int, JArray, T2IModel, double, double)"/>.</summary>
public record class ImageMaskCropData(string BoundsNode, string CroppedMask, string MaskedLatent, string ScaledImage);
/// <summary>Creates an automatic image mask-crop before sampling, to be followed by <see cref="RecompositeCropped(string, string, JArray, JArray)"/> after sampling.</summary>
/// <param name="mask">The mask node input.</param>
/// <param name="image">The image node input.</param>
/// <param name="growBy">Number of pixels to grow the boundary by.</param>
/// <param name="vae">The relevant VAE.</param>
/// <param name="model">The model in use, for determining resolution.</param>
/// <param name="threshold">Optional minimum value threshold.</param>
/// <param name="thresholdMax">Optional maximum value of the threshold.</param>
/// <returns>(boundsNode, croppedMask, maskedLatent, scaledImage).</returns>
public ImageMaskCropData CreateImageMaskCrop(JArray mask, JArray image, int growBy, JArray vae, T2IModel model, double threshold = 0.01, double thresholdMax = 1)
{
if (threshold > 0)
{
string thresholded = CreateNode("SwarmMaskThreshold", new JObject()
{
["mask"] = mask,
["min"] = threshold,
["max"] = thresholdMax
});
mask = [thresholded, 0];
}
string targetRes = UserInput.Get(T2IParamTypes.SegmentTargetResolution, "0x0");
(string targetWidth, string targetHeight) = targetRes.BeforeAndAfter('x');
int targetX = int.Parse(targetWidth);
int targetY = int.Parse(targetHeight);
bool isCustomRes = targetX > 0 && targetY > 0;
string boundsNode = CreateNode("SwarmMaskBounds", new JObject()
{
["mask"] = mask,
["grow"] = growBy,
["aspect_x"] = isCustomRes ? targetX : 0,
["aspect_y"] = isCustomRes ? targetY : 0
});
string croppedImage = CreateNode("SwarmImageCrop", new JObject()
{
["image"] = image,
["x"] = NodePath(boundsNode, 0),
["y"] = NodePath(boundsNode, 1),
["width"] = NodePath(boundsNode, 2),
["height"] = NodePath(boundsNode, 3)
});
string croppedMask = CreateNode("CropMask", new JObject()
{
["mask"] = mask,
["x"] = NodePath(boundsNode, 0),
["y"] = NodePath(boundsNode, 1),
["width"] = NodePath(boundsNode, 2),
["height"] = NodePath(boundsNode, 3)
});
string scaledImage = CreateNode("SwarmImageScaleForMP", new JObject()
{
["image"] = NodePath(croppedImage, 0),
["width"] = isCustomRes ? targetX : model?.StandardWidth <= 0 ? UserInput.GetImageWidth() : model.StandardWidth,
["height"] = isCustomRes ? targetY : model?.StandardHeight <= 0 ? UserInput.GetImageHeight() : model.StandardHeight,
["can_shrink"] = true
});
JArray encoded = DoMaskedVAEEncode(vae, [scaledImage, 0], [croppedMask, 0], null);
return new(boundsNode, croppedMask, $"{encoded[0]}", scaledImage);
}
/// <summary>Returns a masked image composite with mask thresholding.</summary>
public JArray CompositeMask(JArray baseImage, JArray newImage, JArray mask)
{
if (!UserInput.Get(T2IParamTypes.MaskCompositeUnthresholded, false))
{
string thresholded = CreateNode("ThresholdMask", new JObject()
{
["mask"] = mask,
["value"] = 0.001
});
mask = [thresholded, 0];
}
string nodeClass = "ImageCompositeMasked";
if (Features.Contains("variation_seed") && !RestrictCustomNodes)
{
nodeClass = "SwarmImageCompositeMaskedColorCorrecting";
}
string composited = CreateNode(nodeClass, new JObject()
{
["destination"] = baseImage,
["source"] = newImage,
["mask"] = mask,
["x"] = 0,
["y"] = 0,
["resize_source"] = false,
["correction_method"] = UserInput.Get(T2IParamTypes.ColorCorrectionBehavior, "None")
});
return [composited, 0];
}
/// <summary>Recomposites a masked image edit, after <see cref="CreateImageMaskCrop(JArray, JArray, int)"/> was used.</summary>
public JArray RecompositeCropped(string boundsNode, JArray croppedMask, JArray firstImage, JArray newImage)
{
string scaledBack = CreateNode("ImageScale", new JObject()
{
["image"] = newImage,
["width"] = NodePath(boundsNode, 2),
["height"] = NodePath(boundsNode, 3),
["upscale_method"] = "lanczos",
["crop"] = "disabled"
});
if (!UserInput.Get(T2IParamTypes.MaskCompositeUnthresholded, false))
{
string thresholded = CreateNode("ThresholdMask", new JObject()
{
["mask"] = croppedMask,
["value"] = 0.001
});
croppedMask = [thresholded, 0];
}
string nodeClass = "ImageCompositeMasked";
if (Features.Contains("variation_seed") && !RestrictCustomNodes)
{
nodeClass = "SwarmImageCompositeMaskedColorCorrecting";
}
string composited = CreateNode(nodeClass, new JObject()
{
["destination"] = firstImage,
["source"] = NodePath(scaledBack, 0),
["mask"] = croppedMask,
["x"] = NodePath(boundsNode, 0),
["y"] = NodePath(boundsNode, 1),
["resize_source"] = false,
["correction_method"] = UserInput.Get(T2IParamTypes.ColorCorrectionBehavior, "None")
});
return [composited, 0];
}
/// <summary>Call to run the generation process and get the result.</summary>
public JObject Generate()
{
Workflow = [];
foreach (WorkflowGenStep step in Steps)
{
step.Action(this);
if (SkipFurtherSteps)
{
break;
}
}
return Workflow;
}
/// <summary>Returns true if the given node ID has already been used.</summary>
public bool HasNode(string id)
{
return Workflow.ContainsKey(id);
}
public int T2VFPSOverride = -1;
public static List<Func<WorkflowGenerator, int, int>> AltT2VFPSDefaulters = [];
public int Text2VideoFPS()
{
if (T2VFPSOverride > 0)
{
return T2VFPSOverride;
}
int fpsDefault = 24;
if (IsWanVideo())
{
// TODO: Detect CausVid (24 fps LoRA) and/or Wan 2.2 (also 24fps) somehow, to be able to set the base to 16 and leave the rest at 24.
//fpsDefault = 16;
}
foreach (Func<WorkflowGenerator, int, int> fpsOverride in AltT2VFPSDefaulters)
{
fpsDefault = fpsOverride(this, fpsDefault);
}
return UserInput.Get(T2IParamTypes.VideoFPS, fpsDefault);
}
[Obsolete("Use WGNodeData.SaveOutput")]
public string CreateAudioSaveNode(JArray audio, string id = null) => new WGNodeData(audio, this, WGNodeData.DT_AUDIO, CurrentCompat()).SaveOutput(null, null, id: id);
/// <summary>Creates a node to save an image output.</summary>
[Obsolete("Use WGNodeData.SaveOutput")]
public string CreateImageSaveNode(JArray image, string id = null)
{
if (IsVideoModel())
{
return CreateAnimationSaveNode(image, Text2VideoFPS(), UserInput.Get(T2IParamTypes.VideoFormat, "h264-mp4"), id);
}
return new WGNodeData(image, this, WGNodeData.DT_IMAGE, CurrentCompat()).SaveOutput(null, null, id: id);
}
/// <summary>Creates a node to save an animation output.</summary>
[Obsolete("Use WGNodeData.SaveOutput")]
public string CreateAnimationSaveNode(JArray anim, int fps, string format, string id = null)
{
return new WGNodeData(anim, this, WGNodeData.DT_VIDEO, CurrentCompat()) { FPS = fps }.SaveOutput(null, null, id: id);
}
/// <summary>Creates a VAELoader node and returns its node ID. Avoids duplication.</summary>
public JArray CreateVAELoader(string vae, string id = null)
{
string vaeFixed = vae.Replace('\\', '/').Replace("/", ModelFolderFormat ?? $"{Path.DirectorySeparatorChar}");
if (NodeHelpers.TryGetValue($"vaeloader-{vaeFixed}", out string helper))
{
return [helper, 0];
}
string vaeLoader;
if (IsSana())
{
vaeLoader = CreateNode("ExtraVAELoader", new JObject()
{
["vae_name"] = vaeFixed,
["vae_type"] = "dcae-f32c32-sana-1.0",
["dtype"] = "FP16"
}, id);
}
else
{
vaeLoader = CreateNode("VAELoader", new JObject()
{
["vae_name"] = vaeFixed
}, id);
}
NodeHelpers[$"vaeloader-{vaeFixed}"] = vaeLoader;
return [vaeLoader, 0];
}
/// <summary>Creates a VAEDecode node and returns its node ID.</summary>
[Obsolete("Use WGNodeData.DecodeLatents instead")]
public string CreateVAEDecode(JArray vae, JArray latent, string id = null)
{
return new WGNodeData(latent, this, WGNodeData.DT_LATENT_IMAGE, CurrentCompat()).DecodeLatents(new WGNodeData(vae, this, WGNodeData.DT_VAE, CurrentCompat()), false, id: id).Path[0].ToString();
}
/// <summary>Default sampler type.</summary>
public string DefaultSampler = "euler";
/// <summary>Default sampler scheduler type.</summary>
public string DefaultScheduler = "normal";
/// <summary>Default previews type.</summary>
public string DefaultPreviews = "default";
public List<JArray> LoadPromptImagesForMainRef(List<Image> images)
{
List<JArray> result = [];
for (int i = 0; i < images.Count; i++)
{
JArray imgNode = GetPromptImage(true, false, i);
result.Add(imgNode);
}
return result;
}
public (JArray, JArray, JArray, JArray) BuildInputImageHandling(List<JArray> images, JArray pos, JArray neg, JArray latent)
{
JArray imgNeg = null;
if (IsKontext() || IsOmniGen() || IsQwenImage() || IsAnyFlux2())
{
if (IsOmniGen() || IsQwenImageEditPlus())
{
imgNeg = neg;
}
void makeRefLatent(JArray image)
{
string vaeEncode = CreateVAEEncode(CurrentVae.Path, image);
string refLatentNode = CreateNode("ReferenceLatent", new JObject()
{
["conditioning"] = pos,
["latent"] = NodePath(vaeEncode, 0)
});
pos = [refLatentNode, 0];
if (imgNeg is not null)
{
string refLatentNodeNeg = CreateNode("ReferenceLatent", new JObject()
{
["conditioning"] = imgNeg,
["latent"] = NodePath(vaeEncode, 0)
});
imgNeg = [refLatentNodeNeg, 0];
}
}
JArray img = images[0];
makeRefLatent(img);
for (int i = 1; i < images.Count; i++)
{
JArray img2 = images[i];
makeRefLatent(img2);
}
if (img is not null)
{
if (IsQwenImageEditPlus())
{
neg = imgNeg;
}
}
}
else if (IsHiDreamO1())
{
List<JArray> refImages = [];
int count = Math.Min(images.Count, 10);
for (int i = 0; i < count; i++)
{
refImages.Add(GetPromptImage(true, false, i));
}
JObject refInputs = new()
{
["positive"] = pos,
["negative"] = neg
};
for (int i = 0; i < refImages.Count; i++)
{
refInputs[$"images.image_{i + 1}"] = refImages[i];
}
string refNode = CreateNode("HiDreamO1ReferenceImages", refInputs);
pos = [refNode, 0];
neg = [refNode, 1];
}
else if (IsWanVideo()) // TODO: Somehow check if this is actually a phantom model?
{
JArray img = images[0];
for (int i = 1; i < images.Count; i++)
{
JArray img2 = images[i];
string batched = CreateNode("ImageBatch", new JObject()
{
["image1"] = img,
["image2"] = img2
});
img = [batched, 0];
}
double width = UserInput.GetImageWidth();
double height = UserInput.GetImageHeight();
if (IsRefinerStage)
{
double scale = UserInput.Get(T2IParamTypes.RefinerUpscale, 1);
int iwidth = (int)Math.Round(width * scale);
int iheight = (int)Math.Round(height * scale);
width = (iwidth / 16) * 16;
height = (iheight / 16) * 16;
}
// TODO: This node asking for latent info is wacky. Maybe have a reader node that grabs it from the current actual latent, so it's more plug-n-play-ish
string phantomNode = CreateNode("WanPhantomSubjectToVideo", new JObject()
{
["positive"] = pos,
["negative"] = neg,
["vae"] = CurrentVae.Path,
["images"] = img,
["width"] = (int)width,
["height"] = (int)height,
["length"] = UserInput.Get(T2IParamTypes.Text2VideoFrames, 81),
["batch_size"] = 1
});
string negCombine = CreateNode("ConditioningCombine", new JObject()
{
["conditioning_1"] = NodePath(phantomNode, 1),
["conditioning_2"] = NodePath(phantomNode, 2)
});
pos = [phantomNode, 0];
neg = [negCombine, 0];
//latent = [phantomNode, 3]; // This latent is actually pretty stupid, it's just inline generating an empty latent for some reason? Ignore it.
}
else
{
// TODO: Should this warn? Or at least contextually track if 0 models across all stages of the workflow ever use the input image(s)
}
return (pos, neg, latent, imgNeg);
}
/// <summary>Creates a KSampler and returns its node ID.</summary>
public string CreateKSampler(JArray model, JArray pos, JArray neg, JArray latent, double cfg, int steps, int startStep, int endStep, long seed, bool returnWithLeftoverNoise, bool addNoise, double sigmin = -1, double sigmax = -1, string previews = null, string defsampler = null, string defscheduler = null, string id = null, bool rawSampler = false, bool doTiled = false, bool isFirstSampler = false, bool hadSpecialCond = false, string explicitSampler = null, string explicitScheduler = null, int sectionId = 0)
{
if (IsVideoModel())
{
previews ??= UserInput.Get(ComfyUIBackendExtension.VideoPreviewType, "animate");
}
if (IsLTXV() || IsLTXV2())
{
if (!hadSpecialCond)
{
string ltxvcond = CreateNode("LTXVConditioning", new JObject()
{
["positive"] = pos,
["negative"] = neg,
["frame_rate"] = UserInput.Get(T2IParamTypes.VideoFPS, 24)
});
pos = [ltxvcond, 0];
neg = [ltxvcond, 1];
}
if (IsLTXV())
{
defscheduler ??= "ltxv";
}
}
else if (IsNvidiaCosmos1())
{
if (!hadSpecialCond)
{
string ltxvcond = CreateNode("LTXVConditioning", new JObject() // (Despite the name, this is just setting the framerate)
{
["positive"] = pos,
["negative"] = neg,
["frame_rate"] = UserInput.Get(T2IParamTypes.VideoFPS, 24)
});
pos = [ltxvcond, 0];
neg = [ltxvcond, 1];
}
defsampler ??= "res_multistep";
defscheduler ??= "karras";
}
else if (IsAnima())
{
defsampler ??= "er_sde";
defscheduler ??= "simple";
}
else if (IsHunyuanImageRefiner())
{
if (!hadSpecialCond)
{
string refinerCond = CreateNode("HunyuanRefinerLatent", new JObject()
{
["positive"] = pos,
["negative"] = neg,
["latent"] = latent,
["noise_augmentation"] = 0.1 // TODO: User input?
});
pos = [refinerCond, 0];
neg = [refinerCond, 1];
latent = [refinerCond, 2];
}
defscheduler ??= "simple";
}
else if (IsHunyuanVideo15SR())
{
if (!hadSpecialCond)
{
string srCond = CreateNode("HunyuanVideo15SuperResolution", new JObject()
{
["positive"] = pos,
["negative"] = neg,
["vae"] = CurrentVae.Path,
["latent"] = latent,
["noise_augmentation"] = 0.7 // TODO: User input?
});
pos = [srCond, 0];
neg = [srCond, 1];
latent = [srCond, 2];
}
}
// TODO: Registry of model default preferences instead of this
else if (IsFlux() || IsWanVideo() || IsWanVideo22() || IsOmniGen() || IsQwenImage() || IsZImage() || IsZetaChroma() || IsErnie() || IsHiDreamO1())
{
defscheduler ??= "simple";
}
else if (IsChroma() || IsChromaRadiance())
{
defscheduler ??= "beta";
}
else if (IsAnyFlux2())
{
defscheduler ??= "flux2";
}
bool willCascadeFix = false;
WGNodeData cascadeModel = null;
if (!rawSampler && IsCascade() && FinalLoadedModel.Name.Contains("stage_c") && Program.MainSDModels.Models.TryGetValue(FinalLoadedModel.Name.Replace("stage_c", "stage_b"), out T2IModel bModel))
{
(_, cascadeModel, _, CurrentVae) = CreateModelLoader(bModel, LoadingModelType, null, true, sectionId: sectionId);
willCascadeFix = true;
defsampler ??= "euler_ancestral";
defscheduler ??= "simple";
if (!isFirstSampler)
{
willCascadeFix = false;
model = cascadeModel.Path;
}
}
string classId = FinalLoadedModel?.ModelClass?.ID ?? "";
static bool isSpecial(T2IModel model)
{
string modelId = model?.ModelClass?.ID ?? "";
return modelId.EndsWith("/lora-depth") || modelId.EndsWith("/lora-canny");
}
if (classId == "Flux.1-dev/inpaint") // TODO: Correct for split function to use `images`
{
// Not sure why, but InpaintModelConditioning is required here.
JArray img = BasicInputImage?.Path;
JArray mask = FinalMask;
if (MaskShrunkInfo is not null && MaskShrunkInfo.ScaledImage is not null)
{
img = [MaskShrunkInfo.ScaledImage, 0];