-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
490 lines (411 loc) · 18.2 KB
/
__init__.py
File metadata and controls
490 lines (411 loc) · 18.2 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
import os
import random
import re
from pathlib import Path
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
# ============================================================
# Prompt Selector Node
# ============================================================
class PromptSelectorNode:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"text_1": ("STRING", {"default": "", "multiline": True}),
"use_text_1": ("BOOLEAN", {"default": False}),
"text_2": ("STRING", {"default": "", "multiline": True}),
"use_text_2": ("BOOLEAN", {"default": False}),
"text_3": ("STRING", {"default": "", "multiline": True}),
"use_text_3": ("BOOLEAN", {"default": False}),
"text_4": ("STRING", {"default": "", "multiline": True}),
"use_text_4": ("BOOLEAN", {"default": False}),
"text_5": ("STRING", {"default": "", "multiline": True}),
"use_text_5": ("BOOLEAN", {"default": False}),
"mode": (["Manual", "Random", "Random Selected"], {"default": "Manual"}),
"min_count": ("INT", {"default": 1, "min": 1, "max": 5}),
"max_count": ("INT", {"default": 1, "min": 1, "max": 5}),
"seed": ("INT", {"default": 0, "min": 0, "max": 2**31 - 1}),
"separator": _sep_dropdown(),
}
}
RETURN_TYPES = ("STRING", "STRING")
RETURN_NAMES = ("result", "names")
FUNCTION = "build"
CATEGORY = "RandomList/PromptTools"
IS_CHANGED = staticmethod(lambda *a, **k: True)
def build(self, text_1, use_text_1, text_2, use_text_2,
text_3, use_text_3, text_4, use_text_4,
text_5, use_text_5, mode, min_count, max_count,
seed, separator):
sep = _sep_map(separator)
rng = random.Random(seed)
texts = [
("Text 1", text_1.strip(), use_text_1),
("Text 2", text_2.strip(), use_text_2),
("Text 3", text_3.strip(), use_text_3),
("Text 4", text_4.strip(), use_text_4),
("Text 5", text_5.strip(), use_text_5),
]
valid = [(n, v, u) for n, v, u in texts if v]
selected, names = [], []
if not valid:
return ("", "")
if mode == "Manual":
selected = [v for n, v, u in valid if u]
names = [n for n, v, u in valid if u]
elif mode == "Random":
n_pick = rng.randint(min(min_count, len(valid)), min(max_count, len(valid)))
picks = rng.sample(valid, n_pick)
picks.sort(key=lambda x: [y[0] for y in valid].index(x[0]))
selected = [v for n, v, u in picks]
names = [n for n, v, u in picks]
elif mode == "Random Selected":
selected_pool = [(n, v, u) for n, v, u in valid if u]
if selected_pool:
n_pick = rng.randint(min(min_count, len(selected_pool)), min(max_count, len(selected_pool)))
picks = rng.sample(selected_pool, n_pick)
picks.sort(key=lambda x: [y[0] for y in selected_pool].index(x[0]))
selected = [v for n, v, u in picks]
names = [n for n, v, u in picks]
return (sep.join(selected), sep.join(names))
# -------------------------
# RandomListPicker Node
# -------------------------
class RandomListPicker:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"list_string": ("STRING", {"multiline": True, "default": "Hund, Katze, Apfel, Birne"}),
"min_count": ("INT", {"default": 1, "min": 0, "max": 1000}),
"max_count": ("INT", {"default": 1, "min": 0, "max": 1000}),
"index": ("INT", {"default": -1, "min": -1, "max": 1000}),
"input_separator": ([
"comma (,)", "semicolon (;)", "pipe (|)", "newline",
"point (.)", "point newline (.\n)", "BREAK", "empty"
], {"default": "comma (,)"}),
"output_separator": ([
"comma (,)", "semicolon (;)", "pipe (|)", "space ( )",
"newline", "point (.)", "point newline (.\n)", "BREAK", "empty"
], {"default": "comma (,)"}),
"empty_slots": ("INT", {"default": 0, "min": 0, "max": 100}),
"seed": ("INT", {"default": 0, "min": 0, "max": 1125899906842624}),
}
}
RETURN_TYPES = ("STRING", "STRING")
RETURN_NAMES = ("picked_items", "picked_indices")
FUNCTION = "pick_items"
CATEGORY = "RandomList/PromptTools"
@classmethod
def IS_CHANGED(cls, *args, **kwargs):
return True
def pick_items(self, list_string, min_count, max_count, index,
input_separator, output_separator, empty_slots, seed):
sep_map = {
"comma (,)": ",", "semicolon (;)": ";", "pipe (|)": "|",
"space ( )": " ", "newline": "\n", "point (.)": ".",
"point newline (.\n)": ".\n", "BREAK": "\nBREAK\n", "empty": ""
}
in_sep = sep_map.get(input_separator, ",")
out_sep = sep_map.get(output_separator, ",")
items = [item.strip() for item in list_string.split(in_sep) if item.strip()]
if empty_slots > 0:
items.extend([""] * empty_slots)
if not items:
return ("", "")
if index >= 0:
return (items[index], str(index)) if index < len(items) else ("", "")
rng = random.Random(seed)
min_count = max(0, min_count)
max_count = max(min_count, max_count)
actual_count = rng.randint(min_count, min(max_count, len(items)))
selected_items = rng.sample(items, actual_count)
selected_indices = [str(items.index(val)) for val in selected_items]
result_items = out_sep.join([p for p in selected_items if p])
result_indices = ",".join(selected_indices)
return (result_items, result_indices)
# -------------------------
# PromptCombiner Node Small
# -------------------------
class PromptCombinerSmall:
@classmethod
def INPUT_TYPES(cls):
inputs = {}
for i in range(1, 6):
inputs[f"text_{i}"] = ("STRING", {"multiline": True, "default": ""})
inputs[f"sep_{i}"] = ([
"comma", "space", "semicolon", "pipe", "newline",
"point", "point newline", "BREAK", "empty"
], {"default": "comma"})
return {"required": inputs}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("result",)
FUNCTION = "combine"
CATEGORY = "RandomList/PromptTools"
def combine(self, **kwargs):
separator_map = {
"comma": ", ", "space": " ", "semicolon": "; ", "pipe": " | ",
"newline": "\n", "point": ".", "point newline": ".\n", "BREAK": "\nBREAK\n", "empty": ""
}
parts = []
for i in range(1, 6):
text = kwargs.get(f"text_{i}", "").strip()
sep_name = kwargs.get(f"sep_{i}", "comma")
if text:
parts.append(text)
if text and i == 5:
# Abschluss-Separator nach dem letzten Feld
parts.append(separator_map.get(sep_name, ","))
elif text:
parts.append(separator_map.get(sep_name, ","))
return ("".join(parts),)
# -------------------------
# PromptCombiner Node Large
# -------------------------
class PromptCombiner:
@classmethod
def INPUT_TYPES(cls):
inputs = {}
for i in range(1, 11):
inputs[f"text_{i}"] = ("STRING", {"multiline": True, "default": ""})
inputs[f"sep_{i}"] = ([
"comma", "space", "semicolon", "pipe", "newline",
"point", "point newline", "BREAK", "empty"
], {"default": "comma"})
return {"required": inputs}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("result",)
FUNCTION = "combine"
CATEGORY = "RandomList/PromptTools"
def combine(self, **kwargs):
separator_map = {
"comma": ", ", "space": " ", "semicolon": "; ", "pipe": " | ",
"newline": "\n", "point": ".", "point newline": ".\n", "BREAK": "\nBREAK\n", "empty": ""
}
parts = []
for i in range(1, 11):
text = kwargs.get(f"text_{i}", "").strip()
sep_name = kwargs.get(f"sep_{i}", "comma")
if text:
parts.append(text)
if text and i == 10:
# Abschluss-Separator nach dem letzten Feld
parts.append(separator_map.get(sep_name, ","))
elif text:
parts.append(separator_map.get(sep_name, ","))
return ("".join(parts),)
# -------------------------
# Dynamic Tag-Nodes from tags/*.txt
# -------------------------
def _safe_identifier(name: str) -> str:
s = re.sub(r"\W+", "_", name, flags=re.UNICODE).strip("_")
if not s:
s = "Tag"
if re.match(r"^\d", s):
s = "_" + s
return s
def _sep_dropdown():
return ([
"comma", "space", "semicolon", "pipe", "newline",
"point", "point newline", "BREAK" "empty"
], {"default": "comma"})
def _sep_map(key: str) -> str:
m = {
"comma": ", ",
"space": " ",
"semicolon": "; ",
"pipe": " | ",
"newline": "\n",
"point": ".",
"point newline": ".\n",
"BREAK": "\nBREAK\n",
"empty": ""
}
return m.get(key, ", ")
TAGS_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tags")
def _create_tag_node_from_file(path: str):
try:
base = os.path.splitext(os.path.basename(path))[0]
with open(path, "r", encoding="utf-8") as f:
lines = [ln.rstrip("\n") for ln in f]
kv = []
for raw in lines:
line = raw.strip()
if not line:
continue
if "=" in line:
k, v = line.split("=", 1)
k = k.strip()
v = v.strip()
if not k:
continue
kv.append((k, v if v else k))
else:
kv.append((line, line)) # No explicit name
if not kv:
return
class_base = _safe_identifier(base)
class_name = f"{class_base}CheckboxJoiner"
# ---- INPUT TYPES ----
def INPUT_TYPES(cls):
inputs = {}
for (label, _) in kv:
key = label if label else "Value_" + str(len(inputs) + 1)
inputs[key] = ("BOOLEAN", {"default": False})
inputs["mode"] = (["Manual", "Random", "Random Selected"], {"default": "Manual"})
inputs["min_count"] = ("INT", {"default": 1, "min": 1, "max": len(kv), "step": 1})
inputs["max_count"] = ("INT", {"default": 1, "min": 1, "max": len(kv), "step": 1})
inputs["seed"] = ("INT", {"default": 0, "min": 0, "max": 2**31 - 1})
inputs["separator"] = _sep_dropdown()
return {"required": inputs}
# ---- FUNCTIONAL LOGIC ----
def build_string(self, **kwargs):
sep_key = kwargs.get("separator", "comma")
sep = _sep_map(sep_key)
mode = kwargs.get("mode", "Manual")
min_count = kwargs.get("min_count", 1)
max_count = kwargs.get("max_count", 1)
seed = kwargs.get("seed", 0)
rnd = random.Random(seed)
# Label → Value
labels_with_names = [(label if label else "", value) for (label, value) in kv]
all_labels = [label if label else f"Value_{i+1}" for i, (label, _) in enumerate(kv)]
# Which checkboxes are activ?
manual_selected = [
(label, value) for (label, value), key in zip(kv, all_labels)
if kwargs.get(key, False)
]
rnd_selected = set()
if mode == "Random":
# Pick from all tags (except manuell)
pool = [(label, value) for (label, value) in kv if (label, value) not in manual_selected]
count = rnd.randint(min_count, max_count)
missing = max(0, count - len(manual_selected))
rnd_selected = set(rnd.sample(pool, min(len(pool), missing)))
elif mode == "Random Selected":
# Pick from selected
if manual_selected:
count = rnd.randint(min_count, max_count)
rnd_selected = set(rnd.sample(manual_selected, min(len(manual_selected), count)))
# Combined final selection
if mode == "Manual":
final_pairs = manual_selected
elif mode == "Random Selected":
final_pairs = list(rnd_selected)
else:
final_pairs = list(set(manual_selected) | rnd_selected)
# Keep sequence
selected_ordered = [
(label, value) for (label, value) in kv if (label, value) in final_pairs
]
# Create separate Name- and Value-Strings
names = [label for (label, _) in selected_ordered if label]
values = [value for (_, value) in selected_ordered]
name_result = sep.join(names)
value_result = sep.join(values)
return (value_result, name_result)
# ---- Generate class ----
TagNode = type(class_name, (), {
"INPUT_TYPES": classmethod(INPUT_TYPES),
"RETURN_TYPES": ("STRING", "STRING"),
"RETURN_NAMES": ("result", "name"),
"FUNCTION": "build_string",
"CATEGORY": "RandomList/Tags",
"IS_CHANGED": staticmethod(lambda *a, **k: True),
"build_string": build_string,
})
NODE_CLASS_MAPPINGS[class_name] = TagNode
NODE_DISPLAY_NAME_MAPPINGS[class_name] = f"{base} Checkbox Joiner"
except Exception as e:
print(f"Error creating TagNode from {path}: {e}")
return
# Scan tags folder
if os.path.isdir(TAGS_FOLDER):
for fn in sorted(os.listdir(TAGS_FOLDER)):
if fn.lower().endswith(".txt"):
_create_tag_node_from_file(os.path.join(TAGS_FOLDER, fn))
# -----------------------------------------
# Tag File Writer Node
# -----------------------------------------
class TagFileWriter:
"""
Writes key/value pairs into a selectable file in /tags-folder.
- If name is empty → write only prompt as row.
- If name is set → write "Name = Prompt".
- Existing rows with same name will be replaced.
"""
@classmethod
def INPUT_TYPES(cls):
tags_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tags")
if not os.path.exists(tags_folder):
os.makedirs(tags_folder)
files = [f for f in os.listdir(tags_folder) if f.lower().endswith(".txt")]
if not files:
files = ["<no .txt files found>"]
return {
"required": {
"target_file": (files, {"default": files[0]}),
"name": ("STRING", {"default": "", "multiline": False}),
"prompt": ("STRING", {"default": "", "multiline": True}),
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("status",)
FUNCTION = "write_to_file"
CATEGORY = "RandomList/PromptTools"
def write_to_file(self, target_file, name, prompt):
tags_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tags")
file_path = os.path.join(tags_folder, target_file)
# Validation
if not os.path.exists(file_path):
return (f"❌ File {target_file} not found.",)
if not prompt.strip() and not name.strip():
return ("⚠️ No name nor Prompt given – saving failed.",)
name = name.strip()
prompt = prompt.strip()
new_line = f"{name} = {prompt}" if name else prompt
replaced = False
try:
# Read file
if os.path.exists(file_path):
with open(file_path, "r", encoding="utf-8") as f:
lines = [ln.rstrip("\n") for ln in f]
# If name given: Replace existing row
if name:
for i, line in enumerate(lines):
if "=" in line:
k, _ = line.split("=", 1)
if k.strip().lower() == name.lower():
lines[i] = new_line
replaced = True
break
# If nothing replaced, append new row
if not replaced:
lines.append(new_line)
else:
lines = [new_line]
# Write file
with open(file_path, "w", encoding="utf-8") as f:
for ln in lines:
f.write(ln + "\n")
if replaced:
return (f"✅ Entry '{name}' in {target_file} replaced.",)
else:
return (f"✅ Entry '{name or prompt}' in {target_file} added.",)
except Exception as e:
return (f"❌ Error writing file: {str(e)}",)
# -------------------------
# Node Registry (static)
# -------------------------
NODE_CLASS_MAPPINGS["PromptSelectorNode"] = PromptSelectorNode
NODE_DISPLAY_NAME_MAPPINGS["PromptSelectorNode"] = "Prompt Selector"
NODE_CLASS_MAPPINGS["RandomListPicker"] = RandomListPicker
NODE_DISPLAY_NAME_MAPPINGS["RandomListPicker"] = "Random List Picker"
NODE_CLASS_MAPPINGS["PromptCombiner"] = PromptCombiner
NODE_DISPLAY_NAME_MAPPINGS["PromptCombiner"] = "Prompt Combiner"
NODE_CLASS_MAPPINGS["PromptCombinerSmall"] = PromptCombinerSmall
NODE_DISPLAY_NAME_MAPPINGS["PromptCombinerSmall"] = "Prompt Combiner Small"
NODE_CLASS_MAPPINGS["TagFileWriter"] = TagFileWriter
NODE_DISPLAY_NAME_MAPPINGS["TagFileWriter"] = "Tag File Writer"
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]