Repository navigation
Expand file tree
/
Copy pathnodes.py
More file actions
356 lines (305 loc) · 10.2 KB
/
Copy pathnodes.py
File metadata and controls
356 lines (305 loc) · 10.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
from __future__ import annotations
import re
import secrets
import time
try:
from .candidate_parser import (
UnsupportedCandidateSyntaxError,
build_ex_pool,
build_flat_pool,
)
from .runtime_state import RUNTIME_CANDIDATE_STATE_STORE
except ImportError:
from candidate_parser import (
UnsupportedCandidateSyntaxError,
build_ex_pool,
build_flat_pool,
)
from runtime_state import RUNTIME_CANDIDATE_STATE_STORE
DEFAULT_OPTIONS_TEXT = """town,
girl's room,
park,
lake,
flower garden,
castle, fortress,
forest,
grasslands,
sea,
snowy landscape,
mountain,
flower field,
starry sky,
coffee shop,"""
DEFAULT_OPTIONS_TEXT_EX = """town
zoo{animals{birds|penguins}|aquarium,{fish|jellyfish}}
coffee shop{cake|coffee cup}
amusement park{ferris wheel|carousel|balloons}
(){
white day
wedding ceremony
birthday party
}"""
MAX_SAFE_SEED = 2**53 - 1
CATEGORY = "Prompt Random Choice"
WINDOWS_RESERVED_NAMES = {
"CON",
"PRN",
"AUX",
"NUL",
*(f"COM{index}" for index in range(1, 10)),
*(f"LPT{index}" for index in range(1, 10)),
}
def _safe_text(value: str) -> str:
text = str(value or "")
if not text:
return "empty"
text = text.replace("\\", "/").replace("/", "_")
text = re.sub(r'[<>:"|?*\x00-\x1f]', "_", text)
text = re.sub(r"[\s,]+", "_", text)
text = text.replace("(", "_").replace(")", "_")
text = text.replace("{", "_").replace("}", "_")
text = re.sub(r"_+", "_", text)
text = text.strip().strip("._-")
if not text:
return "empty"
if text.upper() in WINDOWS_RESERVED_NAMES:
text = f"_{text}"
return text[:200].rstrip(" .") or "empty"
def _options_input(default: str) -> tuple[str, dict]:
return (
"STRING",
{"multiline": True, "default": default, "dynamicPrompts": False},
)
def _change_every_input() -> tuple[str, dict]:
return (
"INT",
{"default": 1, "min": 1, "max": 999999, "step": 1},
)
def _state_key_input() -> tuple[str, dict]:
return (
"STRING",
{"default": "", "multiline": False, "dynamicPrompts": False},
)
class _RandomChoiceStateMixin:
def __init__(self):
self._current_choice: str | None = None
self._repeat_index = 0
self._last_source_key: str | None = None
self._last_change_every: int | None = None
self._selected_revision = 0
@classmethod
def IS_CHANGED(cls, **kwargs):
return time.time_ns()
def _reset_selection(self):
self._current_choice = None
self._repeat_index = 0
self._selected_revision = 0
def _select_new_choice(self, pool, selected_revision: int):
self._current_choice = pool.choose()
self._repeat_index = 1
self._selected_revision = selected_revision
def _run_choice(
self,
pool,
change_every,
*,
source_key: str,
reset_on_source_change: bool,
latest_revision: int = 0,
):
change_every = max(1, int(change_every))
source_changed = self._last_source_key != source_key
interval_changed = (
self._last_change_every is not None
and self._last_change_every != change_every
)
needs_selection = self._current_choice is None or interval_changed
if reset_on_source_change and source_changed:
needs_selection = True
if not needs_selection:
if self._repeat_index < change_every:
self._repeat_index += 1
else:
needs_selection = True
self._last_source_key = source_key
self._last_change_every = change_every
if needs_selection:
if pool.leaf_count == 0:
self._reset_selection()
return "", "empty", "(empty)", 0, change_every, 0
self._select_new_choice(pool, latest_revision)
selected_text = str(self._current_choice or "")
return (
selected_text,
_safe_text(selected_text),
selected_text if selected_text else "(empty)",
self._repeat_index,
change_every,
self._selected_revision,
)
@staticmethod
def _format_result(choice_result, *, latest_revision=0, runtime_status=""):
(
selected_text,
selected_text_safe,
selected_text_title,
repeat_index,
change_every,
selected_revision,
) = choice_result
return {
"ui": {
"selected_text_title": [selected_text_title],
"repeat_index": [repeat_index],
"change_every": [change_every],
"latest_revision": [latest_revision],
"selected_revision": [selected_revision],
"runtime_status": [runtime_status],
},
"result": (selected_text, selected_text_safe),
}
class PromptRandomChoice(_RandomChoiceStateMixin):
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"options_text": _options_input(DEFAULT_OPTIONS_TEXT),
"change_every": _change_every_input(),
}
}
RETURN_TYPES = ("STRING", "STRING")
RETURN_NAMES = ("selected_text", "selected_text_safe")
FUNCTION = "pick"
CATEGORY = CATEGORY
def pick(self, options_text, change_every):
source = str(options_text or "")
result = self._run_choice(
build_flat_pool(source, allow_force=False),
change_every,
source_key=source,
reset_on_source_change=True,
)
return self._format_result(result)
class PromptRandomChoiceEx(_RandomChoiceStateMixin):
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"options_text": _options_input(DEFAULT_OPTIONS_TEXT_EX),
"change_every": _change_every_input(),
}
}
RETURN_TYPES = ("STRING", "STRING")
RETURN_NAMES = ("selected_text", "selected_text_safe")
FUNCTION = "pick"
CATEGORY = CATEGORY
def pick(self, options_text, change_every):
source = str(options_text or "")
result = self._run_choice(
build_ex_pool(source, allow_force=False),
change_every,
source_key=source,
reset_on_source_change=True,
)
return self._format_result(result)
class _RuntimeRandomChoiceMixin(_RandomChoiceStateMixin):
IS_EX = False
STATE_KEY_PREFIX = "prc-runtime"
@classmethod
def IS_CHANGED(cls, **kwargs):
return float("NaN")
@classmethod
def INPUT_TYPES(cls):
default = DEFAULT_OPTIONS_TEXT_EX if cls.IS_EX else DEFAULT_OPTIONS_TEXT
return {
"required": {
"options_text": _options_input(default),
"change_every": _change_every_input(),
"state_key": _state_key_input(),
},
"hidden": {"unique_id": "UNIQUE_ID"},
}
def _resolve_state_key(self, state_key, unique_id) -> str:
key = state_key.strip() if isinstance(state_key, str) else ""
kind = "ex" if self.IS_EX else "flat"
return key or f"{self.STATE_KEY_PREFIX}-{kind}-{unique_id}"
def _runtime_source(self, options_text, state_key, unique_id):
key = self._resolve_state_key(state_key, unique_id)
state = RUNTIME_CANDIDATE_STATE_STORE.get(key)
if state is None:
return str(options_text or ""), 0, "fallback"
expected_kind = "ex" if self.IS_EX else "flat"
if state.node_kind != expected_kind:
raise ValueError("Runtime state belongs to another node kind.")
if state.input_status == "hard_error":
raise UnsupportedCandidateSyntaxError(state.error)
if state.accepted_text is not None:
return state.accepted_text, state.revision, state.input_status
return str(options_text or ""), 0, state.input_status
def pick(self, options_text, change_every, state_key="", unique_id=None):
source, latest_revision, runtime_status = self._runtime_source(
options_text, state_key, unique_id
)
pool = (
build_ex_pool(source, allow_force=True)
if self.IS_EX
else build_flat_pool(source, allow_force=True)
)
result = self._run_choice(
pool,
change_every,
source_key=source,
reset_on_source_change=False,
latest_revision=latest_revision,
)
return self._format_result(
result,
latest_revision=latest_revision,
runtime_status=runtime_status,
)
class RuntimePromptRandomChoice(_RuntimeRandomChoiceMixin):
IS_EX = False
RETURN_TYPES = ("STRING", "STRING")
RETURN_NAMES = ("selected_text", "selected_text_safe")
FUNCTION = "pick"
CATEGORY = CATEGORY
class RuntimePromptRandomChoiceEx(_RuntimeRandomChoiceMixin):
IS_EX = True
RETURN_TYPES = ("STRING", "STRING")
RETURN_NAMES = ("selected_text", "selected_text_safe")
FUNCTION = "pick"
CATEGORY = CATEGORY
class SafeRandomSeed:
@classmethod
def INPUT_TYPES(cls):
return {"required": {}}
RETURN_TYPES = ("INT",)
RETURN_NAMES = ("seed",)
FUNCTION = "generate"
CATEGORY = CATEGORY
@classmethod
def IS_CHANGED(cls, **kwargs):
return secrets.token_hex(16)
def generate(self):
seed = secrets.randbelow(MAX_SAFE_SEED + 1)
return {
"ui": {
"seed_title": [f"Seed: {seed}"],
"seed_value": [str(seed)],
},
"result": (seed,),
}
NODE_CLASS_MAPPINGS = {
"PromptRandomChoice": PromptRandomChoice,
"PromptRandomChoiceEx": PromptRandomChoiceEx,
"RuntimePromptRandomChoice": RuntimePromptRandomChoice,
"RuntimePromptRandomChoiceEx": RuntimePromptRandomChoiceEx,
"SafeRandomSeed": SafeRandomSeed,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"PromptRandomChoice": "Prompt Random Choice",
"PromptRandomChoiceEx": "Prompt Random Choice Ex",
"RuntimePromptRandomChoice": "Runtime Prompt Random Choice",
"RuntimePromptRandomChoiceEx": "Runtime Prompt Random Choice Ex",
"SafeRandomSeed": "Safe Random Seed",
}