wincode commited on
Commit
0707cea
·
verified ·
1 Parent(s): c78dc30

Upload generator.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. generator.py +341 -0
generator.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Procedural story generator — the "not in the world" dataset engine.
2
+
3
+ Each call to ``generate_story`` synthesises a unique fable by sampling from
4
+ combinatorial pools of realms, creatures, archetypes, magic systems, and plot
5
+ scaffolds, then weaving the chosen ingredients through natural-language
6
+ templates. Because the pools are large and the templates branch on sampled
7
+ attributes, the space of possible stories is astronomically larger than the
8
+ target corpus size — so every generated fable is essentially unique.
9
+
10
+ A small fraction of stories (``curated_fraction``) draw their moral from a
11
+ hand-written list of public-domain-style aphorisms, blending synthetic
12
+ structure with curated linguistic flavour. No external data is downloaded.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import random
18
+ import re
19
+ from typing import List, Tuple
20
+
21
+ from .config import DATA
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # Word pools — the combinatorial ingredient shelf
25
+ # ---------------------------------------------------------------------------
26
+ REALMS: List[str] = [
27
+ "the Glasslands", "the Hollow Mountain", "the Verdant Mire", "the Sunken City",
28
+ "the Ashen Coast", "the Ember Steppes", "the Whispering Tundra",
29
+ "the Obsidian Reach", "the Mossy Hollow", "the Crystal Vale",
30
+ "the Forgotten Sky", "the Pale Marshlands", "the Bramblewilds",
31
+ "the Singing Caverns", "the Coral Reaches", "the Duskwood",
32
+ "the Glittering Dunes", "the Frozen Hollow", "the Lacquered Lake",
33
+ "the Stargrove", "the Tidemarsh", "the Vexing Cliffs",
34
+ "the Lantern Fields", "the Quiet Reaches", "the Bone Hollow",
35
+ "the Saltwood", "the Copper Hills", "the Indigo Wilds",
36
+ ]
37
+
38
+ CREATURES: List[str] = [
39
+ "a mossback tortoise", "a will-o-wisp", "a glimmer-fox", "a hollow crow",
40
+ "a stone-hearted golem", "a tide serpent", "a lantern moth",
41
+ "a frost salamander", "a whisper-hare", "a bramble cat",
42
+ "a copperfin koi", "a glass spider", "a storm owl", "a mirror stag",
43
+ "a moss wyrm", "a sun-bleached heron", "a velvet viper",
44
+ "a mist lynx", "a rust badger", "a gilded beetle",
45
+ "a paper crane", "a salt-crab", "a hollow wolf", "a moon-calf",
46
+ "a thorn lizard", "a vapour eel", "a cinder rat", "a dusk moth",
47
+ ]
48
+
49
+ ARCHETYPES: List[str] = [
50
+ "a lonely lantern-keeper", "an exiled cartographer",
51
+ "a wandering apothecary", "a river-tongue translator",
52
+ "a forgotten heir", "a hedge inventor",
53
+ "a tide-reader", "a soft-spoken blacksmith",
54
+ "a wandering musician", "a half-blind archivist",
55
+ "a reluctant ferryman", "a child of the marshes",
56
+ "a retired monster-hunter", "a dream-stitched seamstress",
57
+ "a clockwork tinkerer", "a wandering judge",
58
+ "a stone-carver", "a comet-watcher", "a toll-keeper",
59
+ "a knot-weaver", "a wind-listener", "a mirror-polisher",
60
+ ]
61
+
62
+ MAGIC_SYSTEMS: List[str] = [
63
+ "binding spoken promises", "weaving light into thread",
64
+ "reading the tides of memory", "singing iron to sleep",
65
+ "bargaining with shadows", "knitting wounds with song",
66
+ "borrowing the eyes of birds", "steaming lies into the air",
67
+ "freezing moments in glass", "trading years for favours",
68
+ "whispering to roots and stone", "summoning rain from grief",
69
+ "folding distance like paper", "pouring courage into water",
70
+ "binding names to candles", "weighing hearts with starlight",
71
+ ]
72
+
73
+ # ---------------------------------------------------------------------------
74
+ # Plot scaffolds — each yields a coherent narrative arc
75
+ # ---------------------------------------------------------------------------
76
+ # Every scaffold takes a single ``ctx`` dict with keys:
77
+ # hero_full, hero_bare, creature_full, creature_bare, realm, magic, rng
78
+ # ``*_full`` includes the leading article ("a wind-listener"), used for first
79
+ # mention; ``*_bare`` strips it ("wind-listener") for natural reuse later.
80
+ # Returning a list of clause fragments, joined + capitalised by the caller.
81
+
82
+
83
+ def _cap(text: str) -> str:
84
+ """Capitalise the first letter of a sentence."""
85
+ return text[0].upper() + text[1:] if text else text
86
+
87
+
88
+ def _sentence_join(parts: List[str]) -> str:
89
+ """Join clause fragments into sentences, capitalising each sentence start."""
90
+ text = " ".join(p.strip() for p in parts if p.strip())
91
+ text = re.sub(r"\s+", " ", text)
92
+ return _cap(text)
93
+
94
+
95
+ def _quest(ctx):
96
+ rng = ctx["rng"]
97
+ hero = ctx["hero_full"]
98
+ creature_full = ctx["creature_full"]
99
+ realm, magic = ctx["realm"], ctx["magic"]
100
+ target = rng.choice(["a stolen song", "a lost name", "a sunken key",
101
+ "a broken crown", "a silver seed",
102
+ "a forgotten map", "a glass heart"])
103
+ obstacle = rng.choice([
104
+ "the river that forgot how to flow",
105
+ "a bridge woven only from apologies",
106
+ "a field where spoken lies turn to stone",
107
+ "a gate that opens only to grief",
108
+ "a forest that eats the names of strangers",
109
+ ])
110
+ return [
111
+ f"One morning {hero} set out across {realm} to recover {target}.",
112
+ f"The path was barred by {creature_full}, who guarded {obstacle}.",
113
+ f"Remembering the old art of {magic}, {hero} offered a bargain.",
114
+ "The bargain was accepted, though it cost more than expected.",
115
+ f"In the end {hero} carried {target} home, lighter than before.",
116
+ ]
117
+
118
+
119
+ def _betrayal(ctx):
120
+ rng = ctx["rng"]
121
+ hero = ctx["hero_full"]
122
+ creature_full = ctx["creature_full"]
123
+ realm, magic = ctx["realm"], ctx["magic"]
124
+ ally_full = rng.choice(ARCHETYPES)
125
+ if ally_full == hero:
126
+ ally_full = "an old companion"
127
+ secret = rng.choice([
128
+ "had been hiding the true name of the realm",
129
+ "had sold the village's silence for safe passage",
130
+ "was never mortal to begin with",
131
+ "had been shaping the hero's dreams for years",
132
+ ])
133
+ return [
134
+ f"For years {hero} and {ally_full} shared the work of {realm}.",
135
+ f"Then {creature_full} appeared at the door with a confession.",
136
+ f"It seemed the companion {secret}.",
137
+ f"{_cap(hero)} answered not with anger but with {magic}.",
138
+ "What was broken could not be mended, only understood.",
139
+ ]
140
+
141
+
142
+ def _discovery(ctx):
143
+ rng = ctx["rng"]
144
+ hero = ctx["hero_full"]
145
+ creature_full = ctx["creature_full"]
146
+ realm, magic = ctx["realm"], ctx["magic"]
147
+ found = rng.choice([
148
+ "a sealed letter from a dead king",
149
+ "a door standing in the middle of an empty field",
150
+ "a well that whispered in a forgotten tongue",
151
+ "a child's drawing of a place that did not exist",
152
+ "a clock running backwards",
153
+ "a mirror showing a room that was not there",
154
+ ])
155
+ return [
156
+ f"While walking the edges of {realm}, {hero} found {found}.",
157
+ "At first it seemed harmless, even quaint.",
158
+ f"But {creature_full} would not come near it, and would say why.",
159
+ f"Slowly {hero} understood the old craft of {magic} was the only key.",
160
+ "What was uncovered could not be buried again.",
161
+ ]
162
+
163
+
164
+ def _transformation(ctx):
165
+ rng = ctx["rng"]
166
+ hero = ctx["hero_full"]
167
+ creature_full = ctx["creature_full"]
168
+ realm, magic = ctx["realm"], ctx["magic"]
169
+ change = rng.choice([
170
+ "into a creature of bark and slow water",
171
+ "into someone who could not be remembered",
172
+ "into a keeper of small, impossible fires",
173
+ "into a version of themselves ten years younger",
174
+ "into a bridge between two feuding villages",
175
+ ])
176
+ return [
177
+ f"On the longest night of the year, {hero} changed {change}.",
178
+ f"The folk of {realm} did not know whether to mourn or rejoice.",
179
+ f"Only {creature_full} seemed unsurprised, and waited patiently.",
180
+ f"To learn to live in this new shape, {hero} studied {magic}.",
181
+ "Some changes, once made, choose not to be undone.",
182
+ ]
183
+
184
+
185
+ def _meeting(ctx):
186
+ rng = ctx["rng"]
187
+ hero = ctx["hero_full"]
188
+ creature_full = ctx["creature_full"]
189
+ realm, magic = ctx["realm"], ctx["magic"]
190
+ stranger_full = rng.choice(ARCHETYPES)
191
+ if stranger_full == hero:
192
+ stranger_full = "a hooded traveller"
193
+ bargain = rng.choice([
194
+ "a year of silence in exchange for one true answer",
195
+ "their shadow, traded for safe passage home",
196
+ "three questions, no more and no less",
197
+ "the memory of their first love",
198
+ "a single seed from the heart-tree",
199
+ ])
200
+ return [
201
+ f"At the boundary of {realm}, {hero} met {stranger_full}.",
202
+ f"The stranger offered a bargain: {bargain}.",
203
+ f"{_cap(creature_full)} watched from the reeds and said nothing.",
204
+ f"{_cap(hero)} weighed the cost in the old way of {magic}.",
205
+ "Whatever was decided, both walked away changed.",
206
+ ]
207
+
208
+
209
+ # Registry of plot scaffolds — referenced by the engine via random.choice.
210
+ SCAFFOLDS = [_quest, _betrayal, _discovery, _transformation, _meeting]
211
+
212
+ # ---------------------------------------------------------------------------
213
+ # Curated morals — public-domain-style aphorisms (hand-written, no source)
214
+ # ---------------------------------------------------------------------------
215
+ MORALS: List[str] = [
216
+ "A kindness given in secret returns when it is most needed.",
217
+ "The cost of a thing is rarely its price.",
218
+ "What we cannot name, we cannot truly keep.",
219
+ "A road walked twice is never the same road.",
220
+ "Patience is the quietest form of courage.",
221
+ "The smallest promise weighs the most.",
222
+ "Even the lost have a direction; it is simply not ours.",
223
+ "To listen is to lend someone a piece of your life.",
224
+ "A wound ignored does not heal; it waits.",
225
+ "We are remembered not for what we took, but what we carried.",
226
+ "The map is not the land, but it can break your heart.",
227
+ "Silence, like salt, preserves and ruins in equal measure.",
228
+ "Grief is the tuition the living pay for love.",
229
+ "A door closed in kindness is still a door closed.",
230
+ "The brave are seldom the loudest.",
231
+ "Old debts do not rust.",
232
+ "Mercy costs nothing but the will to give it.",
233
+ "The longest journey is the one postponed.",
234
+ "What fires forge, fires also test.",
235
+ "Truth travels slowly, but it does travel.",
236
+ "Beware the bargain that costs only your silence.",
237
+ "The hand that feeds the wolf still feeds the wolf.",
238
+ "Hope is a habit, not a feeling.",
239
+ "Even shattered glass once held the morning.",
240
+ "You cannot outrun the name you have earned.",
241
+ ]
242
+
243
+ # ---------------------------------------------------------------------------
244
+ # Engine
245
+ # ---------------------------------------------------------------------------
246
+ class StoryGenerator:
247
+ """Procedurally generates unique fables."""
248
+
249
+ def __init__(self, seed: int = DATA.seed) -> None:
250
+ self.rng = random.Random(seed)
251
+
252
+ # ------------------------------------------------------------------
253
+ def sample_ingredients(self) -> dict:
254
+ """Sample hero/creature/realm/magic and return a scaffold context dict."""
255
+ hero_full = self.rng.choice(ARCHETYPES)
256
+ creature_full = self.rng.choice(CREATURES)
257
+ realm = self.rng.choice(REALMS)
258
+ magic = self.rng.choice(MAGIC_SYSTEMS)
259
+ return {
260
+ "hero_full": hero_full,
261
+ "creature_full": creature_full,
262
+ "realm": realm,
263
+ "magic": magic,
264
+ "rng": self.rng,
265
+ }
266
+
267
+ def _opening(self, hero_full: str, realm: str) -> str:
268
+ templates = [
269
+ f"In {realm} there lived {hero_full}.",
270
+ f"Long ago, when {realm} was still young, {hero_full} kept a quiet life.",
271
+ f"Few in {realm} knew the name of {hero_full}, but those who did did not forget.",
272
+ f"This is the story of {hero_full}, and of the trouble that found them in {realm}.",
273
+ f"To understand {realm}, you must first understand {hero_full}.",
274
+ ]
275
+ return self.rng.choice(templates)
276
+
277
+ def generate_story(self, index: int) -> dict:
278
+ """Generate a single fable. Returns a dict with text + metadata."""
279
+ ctx = self.sample_ingredients()
280
+ scaffold = self.rng.choice(SCAFFOLDS)
281
+ body = scaffold(ctx)
282
+
283
+ # curated moral on a fraction of stories, else a synthesised one
284
+ if self.rng.random() < DATA.curated_fraction:
285
+ moral = self.rng.choice(MORALS)
286
+ moral_source = "curated"
287
+ else:
288
+ moral = self._synthesised_moral()
289
+ moral_source = "synthetic"
290
+
291
+ text = (
292
+ self._opening(ctx["hero_full"], ctx["realm"])
293
+ + " " + _sentence_join(body)
294
+ + " " + moral
295
+ )
296
+ return {
297
+ "id": index,
298
+ "text": text.strip(),
299
+ "hero": ctx["hero_full"],
300
+ "creature": ctx["creature_full"],
301
+ "realm": ctx["realm"],
302
+ "magic": ctx["magic"],
303
+ "scaffold": scaffold.__name__.lstrip("_"),
304
+ "moral_source": moral_source,
305
+ "moral": moral,
306
+ }
307
+
308
+ def _synthesised_moral(self) -> str:
309
+ """Build a fresh aphorism from fragments (keeps vocab diverse)."""
310
+ subject = self.rng.choice([
311
+ "the keeper of the path", "a stranger in need",
312
+ "those who listen", "the patient heart",
313
+ "the one who waits", "a stubborn hope",
314
+ "an unspoken name", "a quiet promise",
315
+ ])
316
+ verb = self.rng.choice([
317
+ "outlasts", "outlives", "finds", "remembers",
318
+ "rewrites", "redeems", "outwaits", "unmakes",
319
+ ])
320
+ obj = self.rng.choice([
321
+ "the loudest storm",
322
+ "the cleverest lie",
323
+ "the sharpest blade",
324
+ "the deepest wound",
325
+ "the longest winter",
326
+ "the brightest crown",
327
+ "the swiftest river",
328
+ ])
329
+ return f"In the end, {subject} {verb} {obj}."
330
+
331
+ # ------------------------------------------------------------------
332
+ def generate_batch(self, n: int, start_index: int = 0) -> List[dict]:
333
+ return [self.generate_story(start_index + i) for i in range(n)]
334
+
335
+
336
+ def estimate_combination_space() -> int:
337
+ """Lower bound on the number of distinct ingredient combos."""
338
+ return (
339
+ len(ARCHETYPES) * len(CREATURES) * len(REALMS) * len(MAGIC_SYSTEMS) *
340
+ len(SCAFFOLDS)
341
+ )