-
Notifications
You must be signed in to change notification settings - Fork 2
/
nilornodes.py
815 lines (657 loc) ยท 27.2 KB
/
nilornodes.py
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
import os
import io
import math
import random
from scipy.interpolate import interp1d
from numpy import linspace
import numpy as np
from huggingface_hub import HfApi
from datetime import datetime
from PIL import Image
from PIL.PngImagePlugin import PngInfo
import OpenEXR
import Imath
import folder_paths
import torch
BIGMIN = -(2**53-1)
BIGMAX = (2**53-1)
category = "Nilor Nodes ๐บ"
subcategories = {
"generators": "/Generators",
"utilities": "/Utilities",
"io": "/IO",
}
class AnyType(str):
"""A special class that is always equal in not equal comparisons. Credit to pythongosssss"""
def __eq__(self, _) -> bool:
return True
def __ne__(self, __value: object) -> bool:
return False
any = AnyType("*")
class NilorInterpolatedFloatList: # Generate interpolated float values based on a number of sections
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
# Dictionary that defines input types for each field
return {
"required": {
"number_of_floats": ("INT", {"forceInput": False}),
"number_of_sections": ("INT", {"forceInput": False}),
"section_number": ("INT", {"forceInput": False}),
"interpolation_type": (["slinear","quadratic", "cubic"], {}), # Type of interpolation to use
},
}
# Define return types and names for outputs of the node
RETURN_TYPES = ("FLOAT",)
RETURN_NAMES = ("floats",)
FUNCTION = "generate_float_list"
CATEGORY = category + subcategories["generators"]
@staticmethod
def interpolate_values(start, end, num_points, interp_type):
# Linear interpolation between start and end over num_points
x = linspace(0, num_points - 1, num_points)
y = linspace(start, end, num_points)
f = interp1d(x, y, kind=interp_type)
return f(x)
def generate_float_list(self, number_of_floats, number_of_sections, section_number, interpolation_type):
# Initializes the array with zeros
my_floats = [0.0] * number_of_floats
# Calculate the length of each portion based on total frames and number of images
portion_length = int((number_of_floats - 1) / (number_of_sections - 1))
# Handling the first image (special case for the first segment)
if section_number == 1:
portion_values = self.interpolate_values(1, 0, portion_length, interpolation_type)
my_floats[0:portion_length] = portion_values
# Handling the last image (special case for the last segment)
elif section_number == number_of_sections:
portion_values = self.interpolate_values(0, 1, portion_length, interpolation_type)
start_index = int((number_of_sections - 2) * portion_length)
my_floats[start_index:] = portion_values
# Handling middle images (general case for dual segments)
else:
portion_values = np.concatenate(
[
self.interpolate_values(0, 1, portion_length, interpolation_type),
self.interpolate_values(1, 0, portion_length, interpolation_type),
]
)
start_index = int((section_number - 2) * portion_length)
end_index = start_index + (2 * portion_length)
my_floats[start_index:end_index] = portion_values
# Returns the modified list of float values
return (my_floats,)
class NilorOneMinusFloatList:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
# Dictionary that defines input types for each field
return {
"required": {
"list_of_floats": ("FLOAT", {"input_is_list": True}),
},
}
# Define return types and names for outputs of the node
RETURN_TYPES = ("FLOAT",)
RETURN_NAMES = ("floats",)
FUNCTION = "one_minus_float_list"
CATEGORY = category + subcategories["generators"]
def one_minus_float_list(self, list_of_floats):
return ([1 - x for x in list_of_floats],)
class NilorRemapFloatList:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
# Dictionary that defines input types for each field
return {
"required": {
"list_of_floats": ("FLOAT", {"input_is_list": True}),
"min_input": ("FLOAT", {"default": 0.0}),
"max_input": ("FLOAT", {"default": 1.0}),
"min_output": ("FLOAT", {"default": 0.0}),
"max_output": ("FLOAT", {"default": 1.0}),
},
}
# Define return types and names for outputs of the node
RETURN_TYPES = ("FLOAT",)
RETURN_NAMES = ("remapped_floats",)
FUNCTION = "remap_float_list"
CATEGORY = category + subcategories["generators"]
def remap_float_list(self, list_of_floats, min_input, max_input, min_output, max_output):
# Avoid division by zero
if max_input - min_input == 0:
raise ValueError("max_input and min_input cannot be the same value.")
scale = (max_output - min_output) / (max_input - min_input)
return ([min_output + (x - min_input) * scale for x in list_of_floats],)
class NilorRemapFloatListAutoInput:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"list_of_floats": ("FLOAT", {"input_is_list": True}),
"min_output": ("FLOAT", {"default": 0.0}),
"max_output": ("FLOAT", {"default": 1.0}),
},
}
# Define return types and names for outputs of the node
RETURN_TYPES = ("FLOAT",)
RETURN_NAMES = ("remapped_list",)
FUNCTION = "remap_float_list_auto_input"
CATEGORY = category + subcategories["generators"]
def remap_float_list_auto_input(self, list_of_floats, min_output, max_output):
min_input = min(list_of_floats)
max_input = max(list_of_floats)
scale = (max_output - min_output) / (max_input - min_input)
return ([min_output + (x - min_input) * scale for x in list_of_floats],)
class NilorInverseMapFloatList:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"list_of_floats": ("FLOAT", {"input_is_list": True}),
},
}
RETURN_TYPES = ("FLOAT",)
RETURN_NAMES = ("floats",)
FUNCTION = "inverse_map_float_list"
CATEGORY = category + subcategories["generators"]
def inverse_map_float_list(self, list_of_floats):
if not list_of_floats:
raise ValueError("The input list_of_floats cannot be empty.")
min_input = min(list_of_floats)
max_input = max(list_of_floats)
return ([min_input + max_input - x for x in list_of_floats],)
class NilorIntToListOfBools:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
# Dictionary that defines input types for each field
return {
"required": {
"number_of_images": ("INT", {"forceInput": False}),
},
}
# Define return types and names for outputs of the node
RETURN_TYPES = ("BOOLEAN",)
RETURN_NAMES = ("booleans",)
FUNCTION = "boolify"
CATEGORY = category + subcategories["generators"]
OUTPUT_IS_LIST = (True,)
def boolify(self, number_of_images, max_images=10):
# Initializes the array with zeros
my_bools = [False] * max_images
for i in range(max_images):
# Set the boolean value to True if the index is less than the number of images
my_bools[i] = i < number_of_images
return (my_bools,)
class NilorListOfInts:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"min": ("INT", {"forceInput": False, "default": 0}),
"max": ("INT", {"forceInput": False, "default": 9}),
"shuffle": ("BOOLEAN", {"default": False}), # Toggle to randomize order
},
}
RETURN_TYPES = ("INT",)
RETURN_NAMES = ("ints",)
FUNCTION = "int_list"
CATEGORY = category + subcategories["generators"]
OUTPUT_IS_LIST = (True,) # Indicates that the output should be processed as a list of individual elements
def int_list(self, min=1, max=10, shuffle=False):
# Generate the list
ints_list = list(range(min, max + 1))
if shuffle:
random.shuffle(ints_list)
return (ints_list,)
class NilorCountImagesInDirectory:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
# Dictionary that defines input types for each field
return {
"required": {
"directory": ("STRING", {"default": "X://path/to/images"}),
},
}
# Define return types and names for outputs of the node
RETURN_TYPES = ("INT",)
RETURN_NAMES = ("int",)
FUNCTION = "count_images_in_directory"
CATEGORY = category + subcategories["utilities"]
INPUT_IS_LIST = False
def count_images_in_directory(self, directory):
if not os.path.isdir(directory):
raise FileNotFoundError(f"Directory '{directory} cannot be found.")
list_dir = []
list_dir = os.listdir(directory)
count = 0
for file in list_dir:
if file.endswith(".png") or file.endswith(".jpeg") or file.endswith(".jpg"):
count += 1
return [count]
class NilorSelectIndexFromList:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"list_of_any": (any, {"forceInput": False}), # Marking as lazy if processing could be deferred
"index": ("INT", {"default": 0}),
},
}
RETURN_TYPES = (any,)
RETURN_NAMES = ("any",)
FUNCTION = "any_by_index"
CATEGORY = category + subcategories["utilities"]
INPUT_IS_LIST = True # Treats input list as a whole, rather than processing each item separately
OUTPUT_IS_LIST = (False,) # Output is a single element, not a list
def any_by_index(self, list_of_any, index=0):
# The input is a tensor so we need to unpack one level
if isinstance(list_of_any, list) and len(list_of_any) == 1:
actual_list = list_of_any[0]
else:
actual_list = list_of_any
# Handle index access safely
if isinstance(index, list):
index = index[0]
# Ensure the index is within bounds
if index < 0 or index >= len(actual_list):
raise ValueError("Index is outside the bounds of the array.")
# Returns the value at the given index
return (actual_list[index],)
class NilorSaveEXRArbitrary:
def __init__(self):
self.output_dir = folder_paths.get_output_directory()
self.type = "output"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"channels": (any,), # This should match the 'any' type list from List of Any
"filename_prefix": ("STRING", {"default": "output"}),
},
"hidden": {
"prompt": "PROMPT",
"extra_pnginfo": "EXTRA_PNGINFO",
},
}
RETURN_TYPES = ()
FUNCTION = "save_exr_arbitrary" # The execution function
CATEGORY = category + subcategories["io"]
# INPUT_IS_LIST = True
OUTPUT_NODE = True
def save_exr_arbitrary(self, channels=None, filename_prefix="output", prompt=None, extra_pnginfo=None):
print("Running save_exr_arbitrary")
# print(f"channels: {channels}")
# print(f"filename_prefix: {filename_prefix}")
actual_channels = channels
# actual_channels = channels[0] # Unpack the channels list
# filename_prefix = filename_prefix[0] # Unpack the filename_prefix list
# check if actual_channels is subscriptable
try:
actual_channels[0]
except TypeError:
print("actual_channels is not subscriptable")
return
# File path handling
useabs = os.path.isabs(filename_prefix)
if not useabs:
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, actual_channels[0].shape[-1], actual_channels[0].shape[-2])
# Determine if the input contains a batch
is_batch = len(actual_channels[0].shape) == 3 # If batch, shape is [batch_size, height, width]
if is_batch:
batch_size = actual_channels[0].shape[0]
else:
batch_size = 1
for i in range(batch_size):
# Extract each image's channels
if is_batch:
image_channels = [tensor[i] for tensor in actual_channels] # For batch, select i-th image
else:
image_channels = actual_channels # For single image, use channels as is
# Validate each tensor
height, width = image_channels[0].shape[-2:]
for tensor in image_channels:
if tensor.shape[-2:] != (height, width):
raise ValueError("All input tensors must have the same dimensions")
# Channel naming
default_names = ["R", "G", "B", "A"] + [f"Channel{j}" for j in range(4, len(image_channels))]
# Prepare data for EXR writing
exr_data = {}
for j, tensor in enumerate(image_channels):
exr_data[default_names[j]] = tensor.cpu().numpy()
# Handle file naming and saving
if useabs:
writepath = filename_prefix
else:
file = f"{filename}_{counter:05}_.exr"
writepath = os.path.join(full_output_folder, file)
counter += 1
# Write EXR file
self.write_exr(writepath, exr_data)
return filename_prefix
def write_exr(self, writepath, exr_data):
try:
# Determine the height and width from one of the provided channels
height, width = list(exr_data.values())[0].shape[:2]
# Create the EXR file header with dynamic channel names
header = OpenEXR.Header(width, height)
header['channels'] = {name: Imath.Channel(Imath.PixelType(Imath.PixelType.FLOAT)) for name in exr_data.keys()}
# Create the EXR file
exr_file = OpenEXR.OutputFile(writepath, header)
# Prepare the data for each channel
channel_data = {name: data.astype(np.float32).tobytes() for name, data in exr_data.items()}
# Write the channel data to the EXR file
exr_file.writePixels(channel_data)
exr_file.close()
print(f"EXR file saved successfully to {writepath}")
except Exception as e:
print(f"Failed to write EXR file: {e}")
class NilorSaveVideoToHFDataset:
def __init__(self) -> None:
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"filename_prefix": ("STRING", {"default": "nilor_save"}),
"filenames": ("VHS_FILENAMES",),
"hf_auth_token": ("STRING", {"default": "auth_token"}),
"repository_id": ("STRING", {"default": "nilor_dataset"}),
}
}
RETURN_TYPES = ()
FUNCTION = "save_video_to_hf_dataset"
OUTPUT_NODE = True
CATEGORY = category + subcategories["io"]
def save_video_to_hf_dataset(
self, filenames, hf_auth_token, repository_id, filename_prefix="nilor_save"
):
files = filenames[1]
results = list()
for path in files:
ext = path.split(".")[-1]
name = f"{filename_prefix}.{ext}"
api = HfApi(token=hf_auth_token)
api.upload_file(
path_or_fileobj=path,
path_in_repo=name,
repo_id=repository_id,
repo_type="dataset",
)
results.append(name)
return {"ui": {"string_field": results}}
class NilorSaveImageToHFDataset:
def __init__(self) -> None:
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"repository_id": ("STRING", {"default": "nilor_dataset"}),
"hf_auth_token": ("STRING", {"default": "auth_token"}),
"filename_prefix": ("STRING", {"default": "nilor_image"}),
},
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
}
RETURN_TYPES = ()
FUNCTION = "save_image_to_hf_dataset"
OUTPUT_NODE = True
CATEGORY = category + subcategories["io"]
def save_image_to_hf_dataset(
self,
image,
repository_id,
hf_auth_token,
filename_prefix="nilor_image",
prompt=None,
extra_pnginfo=None,
):
# Save the image to the dataset
metadata = PngInfo()
metadata.add_text("workflow", "testing, this should be png data")
results = list()
for i, tensor in enumerate(image):
data = 255.0 * tensor.cpu().numpy()
img = Image.fromarray(np.clip(data, 0, 255).astype(np.uint8))
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format="PNG", pnginfo=metadata)
img_byte_arr = img_byte_arr.getvalue()
now = datetime.now()
date_string = now.strftime("%Y-%m-%d-%H-%M-%S")
image_name = f"{filename_prefix}_{i}_{date_string}.png"
api = HfApi(token=hf_auth_token)
api.upload_file(
path_or_fileobj=img_byte_arr,
path_in_repo=image_name,
repo_id=repository_id,
repo_type="dataset",
)
results.append(image_name)
return {"ui": {"string_field": results}}
class NilorShuffleImageBatch:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"images": ("IMAGE",),
"seed": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1})
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("images",)
FUNCTION = "shuffle_image_batch"
CATEGORY = category + subcategories["utilities"]
def _check_image_dimensions(self, images):
if images.shape[0] == 0:
raise ValueError("Input images tensor is empty.")
# All images in the batch should have the same dimensions
if len(images.shape) != 4:
raise ValueError(f"Expected 4D tensor (batch, channels, height, width), got shape {images.shape}")
def shuffle_image_batch(self, images: torch.Tensor, seed):
self._check_image_dimensions(images)
# Get the number of images in the batch
num_images = images.shape[0]
# Generate indices and shuffle them
torch.manual_seed(seed)
indices = torch.randperm(num_images)
# Shuffle the images using the indices
shuffled_images = images[indices]
return (shuffled_images,)
class NilorRepeatTrimImageBatch:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"images": ("IMAGE",),
"count": ("INT", {"default": 1, "min": 1, "max": BIGMAX, "step": 1})
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("images",)
FUNCTION = "repeat_trim_image_batch"
CATEGORY = category + subcategories["utilities"]
def _check_image_dimensions(self, images):
if images.shape[0] == 0:
raise ValueError("Input images tensor is empty.")
# All images in the batch should have the same dimensions
if len(images.shape) != 4:
raise ValueError(f"Expected 4D tensor (batch, channels, height, width), got shape {images.shape}")
def repeat_trim_image_batch(self, images: torch.Tensor, count):
self._check_image_dimensions(images)
batch_count = images.size(0)
amount = math.ceil(count / batch_count)
appended_tensors = images.repeat(amount, 1, 1, 1),
batched_tensors = torch.cat(appended_tensors, dim=0)
trimmed_tensors = batched_tensors[:count]
return (trimmed_tensors,)
class NilorRepeatShuffleTrimImageBatch:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"images": ("IMAGE",),
"seed": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1}),
"count": ("INT", {"default": 1, "min": 1, "max": BIGMAX, "step": 1})
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("images",)
FUNCTION = "repeat_shuffle_trim_image_batch"
CATEGORY = category + subcategories["utilities"]
def _check_image_dimensions(self, images):
if images.shape[0] == 0:
raise ValueError("Input images tensor is empty.")
# All images in the batch should have the same dimensions
if len(images.shape) != 4:
raise ValueError(f"Expected 4D tensor (batch, channels, height, width), got shape {images.shape}")
def repeat_shuffle_trim_image_batch(self, images: torch.Tensor, seed, count):
self._check_image_dimensions(images)
torch.manual_seed(seed)
batch_count = images.size(0)
amount = math.ceil(count / batch_count)
appended_tensors = []
while len(appended_tensors) < count:
indices = torch.randperm(batch_count)
appended_tensors.append(images[indices])
batched_tensors = torch.cat(appended_tensors, dim=0)
trimmed_tensors = batched_tensors[:count]
return (trimmed_tensors,)
class NilorOutputFilenameString:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"client": ("STRING", {"default": "nilor"}),
"project": ("STRING", {"default": "research"}),
"section": ("STRING", {"default": "test-1"}),
"name": ("STRING", {"default": "out-1"}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
"extra_pnginfo": "EXTRA_PNGINFO",
},
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("string",)
FUNCTION = "notify"
CATEGORY = category + subcategories["utilities"]
OUTPUT_NODE = True
IS_CHANGED = True
def get_time(self, format: str):
now = datetime.now()
return now.strftime(format)
def notify(self, client, project, section, name, unique_id=None, extra_pnginfo=None):
time = self.get_time("%y%m%d-%H%M%S")
client = client or "nilor"
project = project or "research"
section = section or "test-1"
name = name or "out-1"
text = f"{client}_{project}/{section}/{time}_{section}/{time}_{client}_{project}_{section}_{name}"
if unique_id is not None and extra_pnginfo is not None:
if not isinstance(extra_pnginfo, list):
print("Error: extra_pnginfo is not a list")
elif (
not isinstance(extra_pnginfo[0], dict)
or "workflow" not in extra_pnginfo[0]
):
print("Error: extra_pnginfo[0] is not a dict or missing 'workflow' key")
else:
workflow = extra_pnginfo[0]["workflow"]
node = next(
(x for x in workflow["nodes"] if str(x["id"]) == str(unique_id[0])),
None,
)
if node:
node["widgets_values"] = [text]
#TODO: make this node's text string preview widget work
return {"ui": {"text": text}, "result": (text,)}
class NilorNFractionsOfInt:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"numerator": ("INT", {"default": 10}),
"denominator": ("INT", {"default": 2}),
"type": (["starts","ends", "centres", "start + end"], {}),
},
}
RETURN_TYPES = ("INT",)
RETURN_NAMES = ("fractions",)
FUNCTION = "n_fractions_of_int"
CATEGORY = category + subcategories["utilities"]
OUTPUT_IS_LIST = (True,)
def n_fractions_of_int(self, numerator, denominator, type):
# the number of fractions to generate is the denominator
if type == "starts":
return ([i * numerator // denominator for i in range(denominator)],)
elif type == "ends":
return ([(i + 1) * numerator // denominator for i in range(denominator)],)
elif type == "centres":
return ([(i * numerator + numerator // 2) // denominator for i in range(denominator)],)
elif type == "start + end":
return ([i * numerator // (denominator - 1) for i in range(denominator)],)
else:
raise ValueError(f"Unknown type: {type}")
# Mapping class names to objects for potential export
NODE_CLASS_MAPPINGS = {
"Nilor Interpolated Float List": NilorInterpolatedFloatList,
"Nilor One Minus Float List": NilorOneMinusFloatList,
"Nilor Remap Float List": NilorRemapFloatList,
"Nilor Inverse Map Float List": NilorInverseMapFloatList,
"Nilor Int To List Of Bools": NilorIntToListOfBools,
"Nilor List of Ints": NilorListOfInts,
"Nilor Count Images In Directory": NilorCountImagesInDirectory,
"Nilor Save Image To HF Dataset": NilorSaveImageToHFDataset,
"Nilor Save Video To HF Dataset": NilorSaveVideoToHFDataset,
"Nilor Select Index From List": NilorSelectIndexFromList,
"Nilor Save EXR Arbitrary": NilorSaveEXRArbitrary,
"Nilor Shuffle Image Batch": NilorShuffleImageBatch,
"Nilor Repeat & Trim Image Batch": NilorRepeatTrimImageBatch,
"Nilor Repeat, Shuffle, & Trim Image Batch": NilorRepeatShuffleTrimImageBatch,
"Nilor Output Filename String": NilorOutputFilenameString,
"Nilor n Fractions of Int": NilorNFractionsOfInt
}
# Mapping nodes to human-readable names
NODE_DISPLAY_NAME_MAPPINGS = {
"Nilor Interpolated Float List": "๐บ Interpolated Float List",
"Nilor One Minus Float List": "๐บ One Minus Float List",
"Nilor Remap Float List": "๐บ Nilor Remap Float List",
"Nilor Inverse Map Float List": "๐บ Nilor Inverse Map Float List",
"Nilor Int To List Of Bools": "๐บ Int To List Of Bools",
"Nilor List of Ints": "๐บ List of Ints",
"Nilor Count Images In Directory": "๐บ Count Images In Directory",
"Nilor Save Image To HF Dataset": "๐บ Save Image To HF Dataset",
"Nilor Save Video To HF Dataset": "๐บ Save Video To HF Dataset",
"Nilor Select Index From List": "๐บ Select Index From List",
"Nilor Save EXR Arbitrary": "๐บ Save EXR Arbitrary",
"Nilor Shuffle Image Batch": "๐บ Nilor Shuffle Image Batch",
"Nilor Repeat & Trim Image Batch": "๐บ Nilor Repeat & Trim Image Batch",
"Nilor Repeat, Shuffle, & Trim Image Batch": "๐บ Nilor Repeat, Shuffle, & Trim Image Batch",
"Nilor Output Filename String": "๐บ Nilor Output Filename String",
"Nilor n Fractions of Int": "๐บ Nilor n Fractions of Int"
}