-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnnt_data.py
1832 lines (1597 loc) · 69.4 KB
/
nnt_data.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
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
import torch
import torch.nn as nn
import numpy as np
from PIL import Image
import ast
import os
import folder_paths
# Tensor data types
TENSOR_DTYPES = {
"float32": torch.float32,
"float64": torch.float64,
"int32": torch.int32,
"int64": torch.int64,
"uint8": torch.uint8,
"bool": torch.bool,
"auto": "auto" # Special case handling
}
# Tensor operations
TENSOR_OPERATIONS = [
"add_tensors",
"subtract_tensors",
"multiply_tensors_elementwise",
"matrix_multiply_tensors",
"transpose_tensor",
"inverse_tensor",
"add_scalar_to_tensor",
"multiply_tensor_by_scalar",
"custom_function",
"custom_function_with_grad",
"gradient",
"jacobian",
"hessian",
"gradient_norm"
]
# Data loading configurations
DATA_SOURCES = [
"txt",
"numpy",
"python_pickle",
"image_folder",
"image_text_pairs",
"text_text_pairs"
]
TORCHVISION_DATASETS = [
"CIFAR10",
"CIFAR100",
"MNIST",
"FashionMNIST",
"EMNIST",
"SVHN",
"STL10",
"ImageNet",
"LSUN",
"CelebA"
]
TOKENIZER_TYPES = [
"basic",
"wordpiece",
"bpe"
]
IMAGE_INTERPOLATION_MODES = [
"nearest",
"bilinear",
"bicubic"
]
NORMALIZE_RANGES = [
"0-1",
"-1-1",
"standardize"
]
# Format options for tensor to text conversion
TEXT_FORMAT_OPTIONS = [
"plain_text",
"formatted_text",
"summary"
]
# Configuration ranges
CONFIG_RANGES = {
"precision": {
"default": 4,
"min": 0,
"max": 10,
"step": 1
},
"max_elements": {
"default": 100,
"min": 1,
"max": 1000000,
"step": 1
},
"image_size": {
"default": 32,
"min": 16,
"max": 2048,
"step": 1
},
"vocab_size": {
"default": 10000,
"min": 1,
"max": 1000000,
"step": 1
},
"sequence_length": {
"default": 128,
"min": 1,
"max": 10000,
"step": 1
}
}
# Data Loading Node
# In nnt_data.py
class NntTorchvisionDataLoader:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"dataset_name": (TORCHVISION_DATASETS, {
"default": "MNIST"
}),
"split": (["train", "test"], {
"default": "train"
}),
"data_dir": ("STRING", {
"default": "",
"multiline": False,
"placeholder": "Leave empty for default path"
}),
"download": (["True", "False"], {
"default": "True"
}),
"normalize_data": (["True", "False"], {
"default": "True"
}),
"enable_augmentation": (["True", "False"], {
"default": "False"
}),
"samples_to_return": ("INT", {
"default": 32,
"min": 1,
"max": 50000,
"step": 1
}),
"start_index": ("INT", {
"default": 0,
"min": 0,
"max": 50000,
"step": 1
}),
"use_cache": (["True", "False"], {
"default": "True"
})
}
}
RETURN_TYPES = ("TENSOR", "TENSOR", "STRING", "INT")
RETURN_NAMES = ("images", "labels", "dataset_info", "num_classes")
FUNCTION = "load_dataset"
OUTPUT_NODE = True
CATEGORY = "NNT Neural Network Toolkit/Data Loading"
@staticmethod
def get_default_data_path():
"""Get default path for dataset storage"""
import os
import folder_paths
# Register path if not already registered
if not "torchvision_datasets" in folder_paths.folder_names_and_paths:
dataset_path = os.path.join(folder_paths.models_dir, "torchvision_datasets")
folder_paths.add_model_folder_path("torchvision_datasets", dataset_path)
return dataset_path
# If already registered, get the base path directly from models_dir
return os.path.join(folder_paths.models_dir, "torchvision_datasets")
def load_dataset(self, dataset_name, split, data_dir, download, normalize_data,
enable_augmentation, samples_to_return, start_index, use_cache):
try:
import torch
import torchvision
import torchvision.transforms as transforms
import os
# If data_dir is empty, use default path
if not data_dir:
data_dir = self.get_default_data_path()
# Create dataset specific directory
dataset_dir = os.path.join(data_dir, dataset_name.lower())
os.makedirs(dataset_dir, exist_ok=True)
# Define transforms
transform_list = [transforms.ToTensor()]
if normalize_data == "True":
transform_list.append(transforms.Normalize((0.5,), (0.5,)))
if enable_augmentation == "True":
transform_list.extend([
transforms.RandomHorizontalFlip(),
transforms.RandomRotation(10),
])
transform = transforms.Compose(transform_list)
# Get dataset class
dataset_class = getattr(torchvision.datasets, dataset_name)
# Load dataset
dataset = dataset_class(
root=dataset_dir,
train=(split == "train"),
download=(download == "True"),
transform=transform
)
# Select samples
end_index = min(start_index + samples_to_return, len(dataset))
images, labels = [], []
for idx in range(start_index, end_index):
img, label = dataset[idx]
images.append(img)
labels.append(label)
# Stack into tensors
images = torch.stack(images)
labels = torch.tensor(labels, dtype=torch.long)
# Create info message
info_msg = (
f"Dataset: {dataset_name}\n"
f"Split: {split}\n"
f"Samples: {len(images)} of {len(dataset)}\n"
f"Image shape: {list(images.shape)}\n"
f"Directory: {dataset_dir}\n"
f"Normalization: {normalize_data}\n"
f"Augmentation: {enable_augmentation}"
)
return (images, labels, info_msg, len(dataset.classes))
except Exception as e:
error_msg = f"Error loading dataset: {str(e)}"
return (torch.empty(0), torch.empty(0), error_msg, 0)
class NntFileLoader:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"data_source": (DATA_SOURCES, {
"default": "numpy"
}),
"data_dir": ("STRING", {
"default": cls.get_default_data_path(),
"multiline": False,
"placeholder": "Leave empty for default path"
}),
"file_pattern": ("STRING", {
"default": "*.npy",
"multiline": False,
}),
"data_type": (list(TENSOR_DTYPES.keys()), {
"default": "float32"
}),
# Data processing options
"normalize": (["True", "False"], {
"default": "True"
}),
"normalize_range": (NORMALIZE_RANGES, {
"default": "0-1"
}),
"batch_first": (["True", "False"], {
"default": "True"
}),
"shuffle": (["True", "False"], {
"default": "False"
}),
# Image specific options
"image_channels": ("INT", {
"default": 3,
"min": 1,
"max": 4,
"step": 1
}),
"image_size": ("INT", {
"default": 224,
"min": 16,
"max": 2048,
"step": 1
}),
"image_interpolation": (IMAGE_INTERPOLATION_MODES, {
"default": "bilinear"
}),
"use_cache": (["True", "False"], {
"default": "True"
})
},
"optional": {
"paired_data_dir": ("STRING", {
"default": "",
"multiline": False,
}),
"paired_file_pattern": ("STRING", {
"default": "",
"multiline": False,
}),
}
}
RETURN_TYPES = ("TENSOR", "TENSOR", "STRING", "INT")
RETURN_NAMES = ("data", "paired_data", "info_message", "batch_size")
FUNCTION = "load_data"
OUTPUT_NODE = True
CATEGORY = "NNT Neural Network Toolkit/Data Loading"
@staticmethod
def get_default_data_path():
"""Get default path for dataset storage"""
import os
import folder_paths
# Register path if not already registered
if not "nnt_datasets" in folder_paths.folder_names_and_paths:
dataset_path = os.path.join(folder_paths.models_dir, "nnt_datasets")
folder_paths.add_model_folder_path("nnt_datasets", dataset_path)
return dataset_path
# If already registered, get the base path directly from models_dir
return os.path.join(folder_paths.models_dir, "nnt_datasets")
def load_data(self, data_source, data_dir, file_pattern, data_type, normalize,
normalize_range, batch_first, shuffle, image_channels, image_size,
image_interpolation, use_cache, paired_data_dir="", paired_file_pattern=""):
try:
import torch
from torch.utils.data import Dataset, DataLoader, TensorDataset
import numpy as np
import os
import hashlib
dtype_map = {
'float32': torch.float32,
'float64': torch.float64,
'int32': torch.int32,
'int64': torch.int64,
'uint8': torch.uint8
}
torch_dtype = dtype_map[data_type]
# If data_dir is empty, use default path
if not data_dir:
data_dir = self.get_default_data_path()
# Generate cache key if caching is enabled
cache_key = None
if use_cache == "True":
cache_params = f"{data_source}_{data_dir}_{file_pattern}_{data_type}_{normalize}_{normalize_range}"
cache_key = hashlib.md5(cache_params.encode()).hexdigest()
# Check if data is already in cache
if cache_key in self._data_cache:
tensor, paired_tensor, info_message = self._data_cache[cache_key]
return tensor, paired_tensor, f"Loaded from cache: {info_message}", tensor.size(0)
# Initialize outputs
tensor = torch.empty(0)
paired_tensor = torch.empty(0)
info_message = ""
# Load data based on source
if data_source == "python_pickle":
tensor, paired_tensor, info_message = self._load_pickle_data(
data_dir, file_pattern, torch_dtype, normalize, normalize_range
)
elif data_source in ["txt", "numpy"]:
tensor, info_message = self._load_array_data(
data_source, data_dir, file_pattern, torch_dtype,
normalize, normalize_range, batch_first
)
paired_tensor = torch.empty(0)
elif data_source == "image_folder":
tensor, info_message = self._load_images(
data_dir, file_pattern, image_channels, image_size,
image_interpolation, normalize, normalize_range
)
paired_tensor = torch.empty(0)
elif data_source == "image_text_pairs":
if not paired_data_dir or not paired_file_pattern:
raise ValueError("Paired directory path and file pattern required for image-text pairs")
tensor, paired_tensor, info_message = self._load_image_text_pairs(
data_dir, paired_data_dir, file_pattern, paired_file_pattern,
image_channels, image_size
)
elif data_source == "text_text_pairs":
if not paired_data_dir or not paired_file_pattern:
raise ValueError("Paired directory path and file pattern required for text-text pairs")
tensor, paired_tensor, info_message = self._load_text_text_pairs(
data_dir, paired_data_dir, file_pattern, paired_file_pattern
)
# Create dataset and dataloader if shuffling is needed
if shuffle == "True":
# Create appropriate dataset based on whether we have paired data
if paired_tensor.nelement() > 0:
dataset = TensorDataset(tensor, paired_tensor)
else:
dataset = TensorDataset(tensor)
# Create DataLoader
dataloader = DataLoader(
dataset,
batch_size=len(dataset), # Load all data at once
shuffle=True
)
# Load the data using the DataLoader
batch = next(iter(dataloader))
if paired_tensor.nelement() > 0:
tensor, paired_tensor = batch
else:
[tensor] = batch
info_message += "\nData shuffled"
# Cache the results if requested
if use_cache == "True":
self._data_cache[cache_key] = (tensor, paired_tensor, info_message)
info_message += "\nData cached for future use"
batch_size = tensor.size(0) if tensor.dim() > 0 else 0
tensor = tensor.float().requires_grad_(True) # Make sure tensor has gradients enabled
if paired_tensor.nelement() > 0:
paired_tensor = paired_tensor.long() # Labels should be long type but don't need gradients
return tensor, paired_tensor, info_message, batch_size
except Exception as e:
error_msg = f"Error loading data: {str(e)}"
return torch.empty(0), torch.empty(0), error_msg, 0
# Include all the helper methods from the original loader
def _normalize_tensor(self, tensor, normalize_range):
"""Helper function to normalize a tensor to a specified range."""
if normalize_range == "0-1":
min_val = tensor.min()
max_val = tensor.max()
if max_val > min_val:
tensor = (tensor - min_val) / (max_val - min_val)
elif normalize_range == "-1-1":
min_val = tensor.min()
max_val = tensor.max()
if max_val > min_val:
tensor = 2.0 * (tensor - min_val) / (max_val - min_val) - 1.0
elif normalize_range == "standardize":
mean = tensor.mean()
std = tensor.std()
if std > 0:
tensor = (tensor - mean) / std
return tensor
def _load_pickle_data(self, folder_path, file_pattern, dtype, normalize, normalize_range):
import torch
import numpy as np
import os
import glob
import pickle
try:
path_pattern = os.path.join(folder_path, file_pattern)
files = glob.glob(path_pattern)
if not files:
raise ValueError(f"No files found matching pattern: {path_pattern}")
data_list = []
label_list = []
for file_path in files:
with open(file_path, 'rb') as fo:
data_dict = pickle.load(fo, encoding='bytes')
# Extract data and labels from the dictionary
data = data_dict.get(b'data')
if data is None:
raise ValueError(f"No data found in {file_path}")
labels = data_dict.get(b'labels') or data_dict.get(b'fine_labels')
if labels is None:
raise ValueError(f"No labels found in {file_path}")
data_list.append(data)
label_list.extend(labels)
# Concatenate data and labels
data_array = np.concatenate(data_list, axis=0)
labels_array = np.array(label_list)
# Convert to tensors
tensor = torch.tensor(data_array, dtype=dtype, requires_grad=True)
labels_tensor = torch.tensor(labels_array, dtype=torch.long)
# Normalize if requested
if normalize == "True":
tensor = self._normalize_tensor(tensor, normalize_range)
info_message = f"Loaded {len(files)} pickle files with {len(label_list)} samples"
return tensor, labels_tensor, info_message
except Exception as e:
raise RuntimeError(f"Error loading pickle data: {str(e)}")
def _load_array_data(self, data_source, folder_path, file_pattern, dtype,
normalize, normalize_range, batch_first):
import torch
import numpy as np
import os
import glob
try:
path_pattern = os.path.join(folder_path, file_pattern)
files = glob.glob(path_pattern)
if not files:
raise ValueError(f"No files found matching pattern: {path_pattern}")
data_list = []
for file_path in files:
if data_source == "txt":
data = np.loadtxt(file_path)
else: # numpy
data = np.load(file_path)
data_list.append(data)
# Stack all arrays
if len(data_list) == 1:
data_array = data_list[0]
else:
try:
data_array = np.stack(data_list, axis=0)
except ValueError:
# If arrays have different shapes, try vstack
data_array = np.vstack(data_list)
# Convert to tensor
tensor = torch.tensor(data_array, dtype=dtype)
# Normalize if requested
if normalize == "True":
tensor = self._normalize_tensor(tensor, normalize_range)
# Adjust batch dimension if needed
if not batch_first == "True" and tensor.dim() > 1:
tensor = tensor.permute(*range(1, tensor.dim()), 0)
info_message = f"Loaded {len(files)} {data_source} files"
return tensor, info_message
except Exception as e:
raise RuntimeError(f"Error loading array data: {str(e)}")
def _load_images(self, folder_path, file_pattern, channels, size,
interpolation, normalize, normalize_range):
import torch
import numpy as np
import os
import glob
from PIL import Image
try:
path_pattern = os.path.join(folder_path, file_pattern)
files = glob.glob(path_pattern)
if not files:
raise ValueError(f"No images found matching pattern: {path_pattern}")
interpolation_modes = {
"nearest": Image.NEAREST,
"bilinear": Image.BILINEAR,
"bicubic": Image.BICUBIC
}
interp_mode = interpolation_modes.get(interpolation, Image.BILINEAR)
data_list = []
for file_path in files:
try:
img = Image.open(file_path)
# Convert image mode based on channels
if channels == 1:
img = img.convert('L')
elif channels == 3:
img = img.convert('RGB')
elif channels == 4:
img = img.convert('RGBA')
else:
raise ValueError(f"Unsupported number of channels: {channels}")
# Resize image
img = img.resize((size, size), interp_mode)
# Convert to numpy array
img_array = np.array(img).astype(np.float32)
# Add channel dimension for grayscale
if channels == 1:
img_array = img_array[..., np.newaxis]
data_list.append(img_array)
except Exception as e:
raise RuntimeError(f"Error processing image {file_path}: {str(e)}")
# Stack all images
data_array = np.stack(data_list, axis=0)
# Normalize to [0, 1] initially
if data_array.max() > 1.0:
data_array = data_array / 255.0
# Convert to tensor and arrange dimensions to (N, C, H, W)
tensor = torch.from_numpy(data_array)
if channels == 1:
tensor = tensor.permute(0, 3, 1, 2) # (N, H, W, 1) -> (N, 1, H, W)
else:
tensor = tensor.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
# Apply additional normalization if requested
if normalize == "True":
tensor = self._normalize_tensor(tensor, normalize_range)
info_message = f"Loaded {len(files)} images with shape {tuple(tensor.shape)}"
return tensor, info_message
except Exception as e:
raise RuntimeError(f"Error loading images: {str(e)}")
def _load_image_text_pairs(self, image_folder, text_folder, image_pattern,
text_pattern, channels, size, vocab_size,
sequence_length, tokenizer):
import torch
import numpy as np
import os
import glob
from PIL import Image
from collections import Counter
try:
# Get matching files
image_files = glob.glob(os.path.join(image_folder, image_pattern))
text_files = glob.glob(os.path.join(text_folder, text_pattern))
image_basenames = {os.path.splitext(os.path.basename(f))[0]: f for f in image_files}
text_basenames = {os.path.splitext(os.path.basename(f))[0]: f for f in text_files}
common_basenames = sorted(set(image_basenames.keys()) & set(text_basenames.keys()))
if not common_basenames:
raise ValueError("No matching image-text pairs found")
# Build vocabulary first
word_counts = Counter()
for bn in common_basenames:
with open(text_basenames[bn], 'r', encoding='utf-8') as f:
text = f.read().strip()
if tokenizer == "basic":
tokens = text.split()
elif tokenizer == "wordpiece":
tokens = []
for word in text.split():
if len(word) > 1:
tokens.extend([word[0]] + [f"##{c}" for c in word[1:]])
else:
tokens.append(word)
elif tokenizer == "bpe":
tokens = [c for c in text] # Character-level as simplification
word_counts.update(tokens)
# Create vocabulary
vocab = {"<pad>": 0, "<unk>": 1}
for word, _ in word_counts.most_common(vocab_size - 2): # -2 for pad and unk
if word not in vocab:
vocab[word] = len(vocab)
# Process pairs
image_tensors = []
text_tensors = []
for bn in common_basenames:
# Process image
img = Image.open(image_basenames[bn])
img = img.convert('RGB' if channels == 3 else 'L')
img = img.resize((size, size))
img_array = np.array(img).astype(np.float32) / 255.0
if channels == 1:
img_array = img_array[..., np.newaxis]
# Process text
with open(text_basenames[bn], 'r', encoding='utf-8') as f:
text = f.read().strip()
if tokenizer == "basic":
tokens = text.split()
elif tokenizer == "wordpiece":
tokens = []
for word in text.split():
if len(word) > 1:
tokens.extend([word[0]] + [f"##{c}" for c in word[1:]])
else:
tokens.append(word)
elif tokenizer == "bpe":
tokens = [c for c in text]
# Convert tokens to indices
indices = [vocab.get(token, vocab["<unk>"]) for token in tokens[:sequence_length]]
indices = indices + [vocab["<pad>"]] * (sequence_length - len(indices))
image_tensors.append(torch.from_numpy(img_array))
text_tensors.append(torch.tensor(indices, dtype=torch.long))
# Stack all tensors
image_tensor = torch.stack(image_tensors).permute(0, 3, 1, 2)
text_tensor = torch.stack(text_tensors)
info_message = (f"Loaded {len(common_basenames)} image-text pairs\n"
f"Vocabulary size: {len(vocab)}")
return image_tensor, text_tensor, info_message
except Exception as e:
raise RuntimeError(f"Error loading image-text pairs: {str(e)}")
def _load_text_text_pairs(self, text_folder_1, text_folder_2,
pattern_1, pattern_2, vocab_size,
sequence_length, tokenizer):
import torch
import os
import glob
from collections import Counter
try:
# Get matching files
files_1 = glob.glob(os.path.join(text_folder_1, pattern_1))
files_2 = glob.glob(os.path.join(text_folder_2, pattern_2))
basenames_1 = {os.path.splitext(os.path.basename(f))[0]: f for f in files_1}
basenames_2 = {os.path.splitext(os.path.basename(f))[0]: f for f in files_2}
common_basenames = sorted(set(basenames_1.keys()) & set(basenames_2.keys()))
if not common_basenames:
raise ValueError("No matching text pairs found")
# Build shared vocabulary
word_counts = Counter()
for bn in common_basenames:
for file_path in [basenames_1[bn], basenames_2[bn]]:
with open(file_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
if tokenizer == "basic":
tokens = text.split()
elif tokenizer == "wordpiece":
tokens = []
for word in text.split():
if len(word) > 1:
tokens.extend([word[0]] + [f"##{c}" for c in word[1:]])
else:
tokens.append(word)
elif tokenizer == "bpe":
tokens = [c for c in text]
word_counts.update(tokens)
# Create vocabulary
vocab = {"<pad>": 0, "<unk>": 1}
for word, _ in word_counts.most_common(vocab_size - 2):
if word not in vocab:
vocab[word] = len(vocab)
# Process pairs
tensors_1 = []
tensors_2 = []
for bn in common_basenames:
for file_path, tensor_list in [(basenames_1[bn], tensors_1),
(basenames_2[bn], tensors_2)]:
with open(file_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
if tokenizer == "basic":
tokens = text.split()
elif tokenizer == "wordpiece":
tokens = []
for word in text.split():
if len(word) > 1:
tokens.extend([word[0]] + [f"##{c}" for c in word[1:]])
else:
tokens.append(word)
elif tokenizer == "bpe":
tokens = [c for c in text]
indices = [vocab.get(token, vocab["<unk>"]) for token in tokens[:sequence_length]]
indices = indices + [vocab["<pad>"]] * (sequence_length - len(indices))
tensor_list.append(torch.tensor(indices, dtype=torch.long))
# Stack all tensors
tensor_1 = torch.stack(tensors_1)
tensor_2 = torch.stack(tensors_2)
info_message = (f"Loaded {len(common_basenames)} text pairs\n"
f"Vocabulary size: {len(vocab)}")
return tensor_1, tensor_2, info_message
except Exception as e:
raise RuntimeError(f"Error loading text pairs: {str(e)}")
class NntTimeSeriesDataLoader:
"""
Node for loading common time series datasets from statsmodels and other sources,
with built-in preprocessing and analysis capabilities.
"""
import torch
import numpy as np
from statsmodels.datasets import get_rdataset
import pandas as pd
from scipy import stats
import os
DATASETS = [
"airline_passengers",
"sunspots",
"mortality_rates",
"livestock",
"electricity_consumption",
"gas_prices",
"temperature",
"unemployment",
"stock_returns",
"exchange_rates",
"co2_levels"
]
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"dataset": (cls.DATASETS, {
"default": "airline_passengers"
}),
"start_date": ("STRING", {
"default": "1949-01",
"multiline": False,
"placeholder": "YYYY-MM or YYYY-MM-DD"
}),
"end_date": ("STRING", {
"default": "1960-12",
"multiline": False,
"placeholder": "YYYY-MM or YYYY-MM-DD"
}),
"frequency": (["M", "D", "W", "Y", "Q", "H"], {
"default": "M"
}),
"preprocessing": (["None", "standardize", "normalize", "log", "difference", "box-cox"], {
"default": "None"
}),
"fill_missing": (["forward", "backward", "linear", "none"], {
"default": "forward"
}),
"return_type": (["single_series", "multi_series", "features_targets"], {
"default": "single_series"
}),
"sequence_length": ("INT", {
"default": 60,
"min": 1,
"max": 1000,
"step": 1
}),
"prediction_horizon": ("INT", {
"default": 12,
"min": 1,
"max": 100,
"step": 1
}),
},
"optional": {
"custom_filepath": ("STRING", {
"default": "",
"multiline": False,
"placeholder": "Path to custom CSV file"
}),
}
}
RETURN_TYPES = ("TENSOR", "TENSOR", "STRING", "DICT")
RETURN_NAMES = ("time_series_data", "features_targets", "dataset_info", "dataset_stats")
FUNCTION = "load_time_series"
OUTPUT_NODE = True
CATEGORY = "NNT Neural Network Toolkit/Data Loading"
@staticmethod
def get_default_data_path():
"""Get default path for dataset storage"""
import os
import folder_paths
if not "timeseries_datasets" in folder_paths.folder_names_and_paths:
dataset_path = os.path.join(folder_paths.models_dir, "timeseries_datasets")
folder_paths.add_model_folder_path("timeseries_datasets", dataset_path)
return dataset_path
return os.path.join(folder_paths.models_dir, "timeseries_datasets")
def load_time_series(self, dataset, start_date, end_date, frequency, preprocessing,
fill_missing, return_type, sequence_length, prediction_horizon,
cache_dir="", custom_filepath=""):
try:
import pandas as pd
# Handle data directory
if not cache_dir:
cache_dir = self.get_default_data_path()
# Create dataset specific directory
dataset_dir = os.path.join(cache_dir, dataset.lower())
os.makedirs(dataset_dir, exist_ok=True)
# Dictionary to store dataset information and statistics
dataset_stats = {
"original_shape": None,
"processed_shape": None,
"missing_values": 0,
"seasonality_test": None,
"stationarity_test": None,
"basic_stats": {},
"frequency": frequency,
"dataset_dir": dataset_dir
}
# Load dataset
if custom_filepath:
if not os.path.exists(custom_filepath):
raise FileNotFoundError(f"Custom file not found: {custom_filepath}")
df = pd.read_csv(custom_filepath, parse_dates=True, index_col=0)
else:
df = self._load_dataset(dataset)
# Save loaded dataset to cache directory
cache_file = os.path.join(dataset_dir, f"{dataset.lower()}_raw.csv")
df.to_csv(cache_file)
dataset_stats["cache_file"] = cache_file
# Store original shape
dataset_stats["original_shape"] = df.shape
dataset_stats["missing_values"] = df.isnull().sum().sum()
# Handle missing values
if fill_missing != "none":
df = self._handle_missing_values(df, fill_missing)
# Preprocess data
if preprocessing != "None":
df = self._preprocess_data(df, preprocessing)
# Save preprocessed data
preprocessed_file = os.path.join(dataset_dir, f"{dataset.lower()}_preprocessed.csv")
df.to_csv(preprocessed_file)
dataset_stats["preprocessed_file"] = preprocessed_file
# Perform statistical tests
dataset_stats["stationarity_test"] = self._test_stationarity(df)
dataset_stats["seasonality_test"] = self._test_seasonality(df)
# Calculate basic statistics
dataset_stats["basic_stats"] = {
"mean": float(df.mean()),
"std": float(df.std()),
"min": float(df.min()),
"max": float(df.max()),
"skewness": float(stats.skew(df.values)),
"kurtosis": float(stats.kurtosis(df.values))
}
# Prepare data based on return type
if return_type == "single_series":
data_tensor = torch.tensor(df.values, dtype=torch.float32)
features_tensor = torch.empty(0) # Empty tensor for unused return
# Save formatted data
np.save(os.path.join(dataset_dir, f"{dataset.lower()}_single_series.npy"),
data_tensor.numpy())
elif return_type == "multi_series":
# Create multiple series with different lags
series_list = []