-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcandidate_parser.py
More file actions
296 lines (242 loc) · 9.04 KB
/
Copy pathcandidate_parser.py
File metadata and controls
296 lines (242 loc) · 9.04 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
from __future__ import annotations
from dataclasses import dataclass
import re
import secrets
MAX_NESTING_DEPTH = 64
MAX_LEAF_OPTIONS = 4096
class CandidateSyntaxError(ValueError):
"""Base class for candidate-language errors."""
class IncompleteCandidateSyntaxError(CandidateSyntaxError):
"""The text may become valid when the user finishes editing it."""
class UnsupportedCandidateSyntaxError(CandidateSyntaxError):
"""The text is structurally complete but uses unsupported syntax."""
def normalize_prompt_fragment(text: str) -> str:
value = str(text or "")
value = re.sub(r"[\t\r\n]+", " ", value)
value = re.sub(r"\s*,\s*", ",", value)
parts = []
for part in value.split(","):
item = part.strip()
if item and item != "()":
parts.append(item)
return ", ".join(parts)
def split_candidate_parts(
options_text: str,
*,
validate_braces: bool = True,
) -> list[str]:
"""Split top-level candidates while preserving nested child groups."""
text = str(options_text or "").replace("\r\n", "\n").replace("\r", "\n")
parts: list[str] = []
current: list[str] = []
depth = 0
for char in text:
if char == "{":
depth += 1
current.append(char)
continue
if char == "}":
if depth == 0 and not validate_braces:
current.append(char)
continue
depth -= 1
if depth < 0:
raise IncompleteCandidateSyntaxError(
"Unmatched closing brace '}' in candidate text."
)
current.append(char)
continue
if depth == 0 and char in ("|", "\n"):
parts.append("".join(current))
current = []
continue
current.append(char)
if depth and validate_braces:
raise IncompleteCandidateSyntaxError(
"Unmatched opening brace '{' in candidate text."
)
parts.append("".join(current))
return [part.strip(" \t\r\n,") for part in parts if part.strip(" \t\r\n,")]
def _decode_leaf(value: str, *, forced: bool) -> str:
item = value[1:].strip() if forced else value
if forced and not item:
raise UnsupportedCandidateSyntaxError(
"A forced candidate must not be empty. Use '!()' to force an empty string."
)
if item == "()":
return ""
return item
@dataclass(frozen=True)
class FlatCandidatePool:
options: tuple[str, ...]
forced: bool = False
@property
def leaf_count(self) -> int:
return len(self.options)
def choose(self) -> str:
if not self.options:
return ""
return secrets.choice(self.options)
def build_flat_pool(options_text: str, *, allow_force: bool) -> FlatCandidatePool:
parts = split_candidate_parts(options_text, validate_braces=False)
active: list[str] = []
first_forced: str | None = None
for part in parts:
if part.startswith("#"):
continue
is_forced = allow_force and part.startswith("!")
value = _decode_leaf(part, forced=is_forced)
if is_forced:
if first_forced is None:
first_forced = value
continue
active.append(value)
if first_forced is not None:
return FlatCandidatePool((first_forced,), forced=True)
return FlatCandidatePool(tuple(active))
def _format_multiple_group_error(candidate: str, position: int) -> str:
pointer = " " * position + "^"
return (
"Unsupported syntax: A candidate may contain only one direct child group.\n\n"
f"{candidate}\n{pointer}\n\n"
"Multiple direct child groups are not supported because they create "
"a Cartesian product during candidate expansion. Use separate Prompt "
"Random Choice Ex nodes and combine their outputs with String Join."
)
def _find_direct_group(candidate: str) -> tuple[int, int] | None:
depth = 0
start = -1
first_group: tuple[int, int] | None = None
for index, char in enumerate(candidate):
if char == "{":
if depth == 0:
if first_group is not None:
raise UnsupportedCandidateSyntaxError(
_format_multiple_group_error(candidate, index)
)
start = index
depth += 1
elif char == "}":
depth -= 1
if depth < 0:
raise IncompleteCandidateSyntaxError(
"Unmatched closing brace '}' in candidate text."
)
if depth == 0:
first_group = (start, index)
if depth:
raise IncompleteCandidateSyntaxError(
"Unmatched opening brace '{' in candidate text."
)
return first_group
@dataclass(frozen=True)
class ExCandidate:
prefix: str
suffix: str
children: "ExCandidatePool | None" = None
@property
def leaf_count(self) -> int:
return self.children.leaf_count if self.children is not None else 1
def select_by_index(self, index: int) -> str:
if self.children is None:
return normalize_prompt_fragment(self.prefix + self.suffix)
child = self.children.select_by_index(index)
replacement = f", {child}" if child else ""
return normalize_prompt_fragment(self.prefix + replacement + self.suffix)
@dataclass(frozen=True)
class ExCandidatePool:
candidates: tuple[ExCandidate, ...]
forced: bool = False
@property
def leaf_count(self) -> int:
return sum(candidate.leaf_count for candidate in self.candidates)
def select_by_index(self, index: int) -> str:
if index < 0 or index >= self.leaf_count:
raise IndexError("leaf candidate index is out of range")
remaining = index
for candidate in self.candidates:
if remaining < candidate.leaf_count:
return candidate.select_by_index(remaining)
remaining -= candidate.leaf_count
raise IndexError("leaf candidate index is out of range")
def choose(self) -> str:
count = self.leaf_count
if count == 0:
return ""
return self.select_by_index(secrets.randbelow(count))
def _parse_ex_candidate(
raw_candidate: str,
*,
allow_force: bool,
depth: int,
) -> ExCandidate:
if depth > MAX_NESTING_DEPTH:
raise UnsupportedCandidateSyntaxError(
f"PromptRandomChoiceEx nesting exceeds {MAX_NESTING_DEPTH} levels."
)
forced = allow_force and raw_candidate.startswith("!")
candidate = raw_candidate[1:].strip() if forced else raw_candidate
if forced and not candidate:
raise UnsupportedCandidateSyntaxError(
"A forced candidate must not be empty. Use '!()' to force an empty string."
)
group = _find_direct_group(candidate)
if group is None:
leaf = _decode_leaf(candidate, forced=False)
return ExCandidate(prefix=leaf, suffix="")
start, end = group
prefix = candidate[:start]
suffix = candidate[end + 1 :]
child_text = candidate[start + 1 : end]
children = _parse_ex_pool(child_text, allow_force=allow_force, depth=depth + 1)
if not children.candidates:
children = ExCandidatePool((ExCandidate(prefix="", suffix=""),))
return ExCandidate(prefix=prefix, suffix=suffix, children=children)
def _parse_ex_pool(
options_text: str,
*,
allow_force: bool,
depth: int,
) -> ExCandidatePool:
parts = split_candidate_parts(options_text)
active_candidates: list[ExCandidate] = []
first_forced_candidate: ExCandidate | None = None
for part in parts:
if part.startswith("#"):
continue
is_forced = allow_force and part.startswith("!")
candidate = _parse_ex_candidate(
part,
allow_force=allow_force,
depth=depth,
)
if is_forced:
if first_forced_candidate is None:
first_forced_candidate = candidate
else:
active_candidates.append(candidate)
candidates = (
(first_forced_candidate,)
if first_forced_candidate is not None
else tuple(active_candidates)
)
pool = ExCandidatePool(candidates, forced=first_forced_candidate is not None)
if pool.leaf_count > MAX_LEAF_OPTIONS:
raise UnsupportedCandidateSyntaxError(
"PromptRandomChoiceEx contains too many leaf candidates "
f"({pool.leaf_count} > {MAX_LEAF_OPTIONS})."
)
return pool
def build_ex_pool(options_text: str, *, allow_force: bool) -> ExCandidatePool:
return _parse_ex_pool(options_text, allow_force=allow_force, depth=0)
def classify_runtime_text(options_text: str, *, is_ex: bool) -> tuple[str, str]:
try:
if is_ex:
build_ex_pool(options_text, allow_force=True)
else:
build_flat_pool(options_text, allow_force=True)
except IncompleteCandidateSyntaxError as exc:
return "incomplete", str(exc)
except UnsupportedCandidateSyntaxError as exc:
return "hard_error", str(exc)
return "valid", ""