forked from mewo2/deserts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgrammar.py
462 lines (366 loc) · 10.9 KB
/
grammar.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
# -*- coding: utf-8 -*-
from functools import wraps
import json
from collections import defaultdict
import random
import copy
import math
import loremipsum
from parsecom import *
def retrying(f, max_tries=100):
@wraps(f)
def wrapper(*args, **kwargs):
for _ in range(max_tries):
try:
return f(*args, **kwargs)
except AssertionError:
continue
assert False
return wrapper
def caching(f):
cache = {}
@wraps(f)
def wrapper(*args):
try:
return cache[args]
except KeyError:
res = f(*args)
cache[args] = res
return res
return wrapper
def capital(word):
return word[0].upper() + word[1:]
def distinct(*args):
return len(args) == len(set(args))
class Generator(object):
def __add__(self, other):
return ConcatGen(self, other)
def pretty(self, wrap=80):
r = repr(self).strip()
if len(r) < wrap:
return [r]
return [f"***{self.__class__.__name__}***"]
class ConcatGen(Generator):
def __init__(self, *gs):
self.gs = [g for g in gs]
def __call__(self, director, **kwargs):
return "".join(g(director, **kwargs) for g in self.gs)
def __repr__(self):
return "".join(repr(g) for g in self.gs)
def pretty(self, wrap=80):
lines = []
line = ""
remaining = wrap
for g in self.gs:
gls = g.pretty(remaining)
if line and line[-1] not in "~^ " and gls[0] and gls[0][0] not in ",. ":
line = line + " "
remaining -= 1
gls = g.pretty(remaining)
line = line + gls[0]
for gl in gls[1:]:
assert len(gl) <= remaining
lines.append(line)
line = " " * (wrap - remaining) + gl
remaining = wrap - len(line)
if remaining < 20:
lines.append(line)
line = ""
remaining = wrap
if line:
assert len(line) <= wrap
lines.append(line)
return lines
def concatgen(*gs):
gens = []
for g in gs:
if isemptygen(g):
continue
if gens and isinstance(gens[-1], LiteralGen) and isinstance(g, LiteralGen):
newg = LiteralGen(gens[-1].value + g.value)
gens[-1] = newg
if len(gs) == 1:
return gs[0]
return ConcatGen(*gs)
class LiteralGen(Generator):
def __init__(self, value):
self.value = value
def __call__(self, director, **kwargs):
director.literals.add(self.value.strip())
return self.value
def __repr__(self):
return self.value
def isemptygen(g):
return isinstance(g, LiteralGen) and not g.value
class MaybeGen(Generator):
def __init__(self, gen):
self.gen = gen
def __call__(self, director, **kwargs):
if random.random() < 0.5 ** 0.5:
return self.gen(director, **kwargs)
return ""
def __repr__(self):
return f"[{self.gen|repr}]"
class ChoiceGen(Generator):
def __init__(self, *gs):
self.gs = gs
def __call__(self, director, **kwargs):
gs = director.shuffle(self.gs)
for g in gs:
try:
ret = g(director, **kwargs)
except AssertionError:
continue
if not ret.strip():
continue
director.mark_used(g)
for g2 in gs:
if g != g2:
director.mark_unused(g2)
return ret
assert False
def __repr__(self):
return "<" + "|".join(repr(g) for g in self.gs) + ">"
def pretty(self, wrap=80):
r = repr(self)
if len(r) <= wrap:
return [r]
char = "<"
lines = []
for g in self.gs:
glines = g.pretty(wrap=wrap - 1)
for gl in glines:
assert len(gl) < wrap, gl
lines.append(char + gl)
char = " "
char = "|"
if len(lines[-1]) < wrap:
lines[-1] = lines[-1] + ">"
else:
lines.append(">")
return lines
class LookupGen(Generator):
def __init__(self, name):
self.name = name
def __call__(self, director, **kwargs):
if self.name in director.kwargs:
value = director.kwargs[self.name]
if isinstance(value, bool):
value = "true" if value else ""
return value
value = director.lexicon[self.name](director, **kwargs)
director.counts[self.name] += 1
return value
def __repr__(self):
return "@" + self.name
class FunctionGen(Generator):
def __init__(self, name, *args):
self.name = name
self.args = args
def __call__(self, director, **kwargs):
current, director.current = director.current, self
ret = director.functions[self.name](*self.args, **kwargs)
director.current = current
return ret
def __repr__(self):
return r"\%s{%s}" % (self.name, "|".join(repr(a) for a in self.args))
def combine(*gens):
g = gens[0]
gens = gens[1:]
if len(gens) == 0:
return g
while len(gens) > 1:
g, gens = g + gens[0], gens[1:]
g = g + gens[0]
return g
def cleanup(txt):
txt = re.sub("\s+", " ", txt) # remove multiple spaces
txt = re.sub(r" ([\.,;:!\?])", r"\1", txt) # remove space before punctuation
txt = re.sub(
r"a\(n\)\s*(\W+)([aeiouáéíóúäëïöü])",
r"an \1\2",
txt,
flags=re.UNICODE | re.IGNORECASE,
)
txt = re.sub(r"a\(n\)", r"a", txt)
def cap(m):
pre = m.group(1) or ""
return pre + m.group(2).upper()
txt = re.sub(r"\^(\W*)(.)", cap, txt, flags=re.UNICODE) # capitalize after ^
txt = txt.strip()
txt = re.sub("\s+", " ", txt) # remove multiple spaces again
return txt
class Director(object):
stdlib = []
def __init__(self, *args):
lexicon = defaultdict(list)
for k, v in args:
lexicon[k].append(v)
self.lexicon = {}
for k, v in lexicon.items():
if len(v) > 1:
print(f"Got {len(v)} definitions for {k}")
self.lexicon[k] = ChoiceGen(*v)
else:
self.lexicon[k] = v[0]
self.functions = {}
for f, args in self.stdlib:
self.function(*args)(f)
self.current = None
self.ages = defaultdict(float)
self.counts = defaultdict(int)
self.literals = set()
@retrying
def __call__(self, name, **kwargs):
self.data = defaultdict(lambda: None)
self.kwargs = kwargs
txt = self.lexicon[name](self)
del self.kwargs
return "\n".join(cleanup(para) for para in txt.split("~"))
def function(self, name, *types):
def wrapper(f):
@wraps(f)
def wrapped(*args, **kwargs):
def thunk(x):
return lambda: x(self, **kwargs)
args = list(args)
the_types = list(types)
new_args = []
while args:
try:
t = the_types.pop(0)
except:
t = None
a = args.pop(0)
if t is None:
na = thunk(a)
else:
na = t(a(self, **kwargs))
new_args.append(na)
ret = f(self, *new_args, **kwargs)
return ret
self.functions[name] = wrapped
return wrapped
return wrapper
def shuffle(self, items):
items = list(items)
items = sorted(items, key=lambda x: self.ages[x] + random.random())
return items
def mark_used(self, item):
self.ages[item] += 0.5
def mark_unused(self, item):
self.ages[item] *= 0.5
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def stdlib(*args):
def wrapper(f):
Director.stdlib.append((f, args))
return wrapper
def wrapped(txt, width=80):
lines = [""]
words = txt.split()
while words:
word = words.pop(0)
if len(lines[-1]) + len(word) + 1 > width:
lines.append("")
lines[-1] += (" " if lines[-1] else "") + word
return "\n".join(lines)
template = Forward()
text = Regex(r"[^@#{}[\]\\|<>_\n]+") >> LiteralGen
insert = (lit("@") & word) >> LookupGen
literal = (lit("_") & Regex(".")) >> LiteralGen
function = (
lit("\\")
& word
& Maybe(lit("{") & Maybe(template & Many(lit("|") & template)) & lit("}"))
) >> FunctionGen
choice = (lit("<") & template & Many(lit("|") & template) & lit(">")) >> ChoiceGen
option = (lit("[") & template & lit("]")) >> MaybeGen
comment = (lit("#") & Regex(r"[^\n]*")) > LiteralGen(" ")
linebreak = Regex(r"\n +") > LiteralGen(" ")
template.p = (
Many(
text | insert | literal | function | choice | option | comment | linebreak,
allow_none=False,
)
>> concatgen
)
defn = (word + lit("=") + template) >> tuplize
parser = Many((defn & lit("\n")) | lit("\n") | ~comment) >> Director
specials = r"""
@ - insert template
# - comment
^ - capitalize
{} - grouping
[] - optional
\ - function call
| - separator
_ - literal
~ - paragraph break
<> - choice
`
"""
@stdlib("retry")
def retry(director, gen):
tries = 0
while True:
old_data = copy.deepcopy(director.data)
try:
return gen()
except AssertionError:
tries += 1
if tries > 3:
raise
director.data = old_data
@stdlib("ignore")
def ignore(director, gen):
return ""
@stdlib("error")
def error(director):
raise Exception
@stdlib("if")
def if_(director, query, yes):
q = query()
if q.strip():
return yes()
else:
return ""
@stdlib("some")
def some_(director, *gens):
genlist = list(gens)
random.shuffle(genlist)
n = random.randrange(2, 5)
return " ".join(g() for g in genlist[:n])
@stdlib("fix")
def fix(director, gen):
if director["fix"] is None:
director["fix"] = {}
df = director["fix"]
if gen not in df:
df[gen] = gen()
return df[gen]
@stdlib("once")
def once(director, gen=None):
if director["once"] is None:
director["once"] = set()
assert director.current not in director["once"]
director["once"].add(director.current)
if gen:
return gen()
return ""
@stdlib("choose", float)
def choose(director, value, *gens):
n = len(gens) - 1
p = 1 / (1 + math.exp(-value / 2))
k = 0
for _ in range(n):
k += random.random() < p
return gens[k]()
@stdlib("repeat", int)
def repeat(director, n, gen):
return " ".join(gen() for _ in range(n))
@stdlib("lorem")
def lorem(director):
return loremipsum.get_sentence()