| """Procedural story generator — the "not in the world" dataset engine. |
| |
| Each call to ``generate_story`` synthesises a unique fable by sampling from |
| combinatorial pools of realms, creatures, archetypes, magic systems, and plot |
| scaffolds, then weaving the chosen ingredients through natural-language |
| templates. Because the pools are large and the templates branch on sampled |
| attributes, the space of possible stories is astronomically larger than the |
| target corpus size — so every generated fable is essentially unique. |
| |
| A small fraction of stories (``curated_fraction``) draw their moral from a |
| hand-written list of public-domain-style aphorisms, blending synthetic |
| structure with curated linguistic flavour. No external data is downloaded. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import random |
| import re |
| from typing import List, Tuple |
|
|
| from .config import DATA |
|
|
| |
| |
| |
| REALMS: List[str] = [ |
| "the Glasslands", "the Hollow Mountain", "the Verdant Mire", "the Sunken City", |
| "the Ashen Coast", "the Ember Steppes", "the Whispering Tundra", |
| "the Obsidian Reach", "the Mossy Hollow", "the Crystal Vale", |
| "the Forgotten Sky", "the Pale Marshlands", "the Bramblewilds", |
| "the Singing Caverns", "the Coral Reaches", "the Duskwood", |
| "the Glittering Dunes", "the Frozen Hollow", "the Lacquered Lake", |
| "the Stargrove", "the Tidemarsh", "the Vexing Cliffs", |
| "the Lantern Fields", "the Quiet Reaches", "the Bone Hollow", |
| "the Saltwood", "the Copper Hills", "the Indigo Wilds", |
| ] |
|
|
| CREATURES: List[str] = [ |
| "a mossback tortoise", "a will-o-wisp", "a glimmer-fox", "a hollow crow", |
| "a stone-hearted golem", "a tide serpent", "a lantern moth", |
| "a frost salamander", "a whisper-hare", "a bramble cat", |
| "a copperfin koi", "a glass spider", "a storm owl", "a mirror stag", |
| "a moss wyrm", "a sun-bleached heron", "a velvet viper", |
| "a mist lynx", "a rust badger", "a gilded beetle", |
| "a paper crane", "a salt-crab", "a hollow wolf", "a moon-calf", |
| "a thorn lizard", "a vapour eel", "a cinder rat", "a dusk moth", |
| ] |
|
|
| ARCHETYPES: List[str] = [ |
| "a lonely lantern-keeper", "an exiled cartographer", |
| "a wandering apothecary", "a river-tongue translator", |
| "a forgotten heir", "a hedge inventor", |
| "a tide-reader", "a soft-spoken blacksmith", |
| "a wandering musician", "a half-blind archivist", |
| "a reluctant ferryman", "a child of the marshes", |
| "a retired monster-hunter", "a dream-stitched seamstress", |
| "a clockwork tinkerer", "a wandering judge", |
| "a stone-carver", "a comet-watcher", "a toll-keeper", |
| "a knot-weaver", "a wind-listener", "a mirror-polisher", |
| ] |
|
|
| MAGIC_SYSTEMS: List[str] = [ |
| "binding spoken promises", "weaving light into thread", |
| "reading the tides of memory", "singing iron to sleep", |
| "bargaining with shadows", "knitting wounds with song", |
| "borrowing the eyes of birds", "steaming lies into the air", |
| "freezing moments in glass", "trading years for favours", |
| "whispering to roots and stone", "summoning rain from grief", |
| "folding distance like paper", "pouring courage into water", |
| "binding names to candles", "weighing hearts with starlight", |
| ] |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
| def _cap(text: str) -> str: |
| """Capitalise the first letter of a sentence.""" |
| return text[0].upper() + text[1:] if text else text |
|
|
|
|
| def _sentence_join(parts: List[str]) -> str: |
| """Join clause fragments into sentences, capitalising each sentence start.""" |
| text = " ".join(p.strip() for p in parts if p.strip()) |
| text = re.sub(r"\s+", " ", text) |
| return _cap(text) |
|
|
|
|
| def _quest(ctx): |
| rng = ctx["rng"] |
| hero = ctx["hero_full"] |
| creature_full = ctx["creature_full"] |
| realm, magic = ctx["realm"], ctx["magic"] |
| target = rng.choice(["a stolen song", "a lost name", "a sunken key", |
| "a broken crown", "a silver seed", |
| "a forgotten map", "a glass heart"]) |
| obstacle = rng.choice([ |
| "the river that forgot how to flow", |
| "a bridge woven only from apologies", |
| "a field where spoken lies turn to stone", |
| "a gate that opens only to grief", |
| "a forest that eats the names of strangers", |
| ]) |
| return [ |
| f"One morning {hero} set out across {realm} to recover {target}.", |
| f"The path was barred by {creature_full}, who guarded {obstacle}.", |
| f"Remembering the old art of {magic}, {hero} offered a bargain.", |
| "The bargain was accepted, though it cost more than expected.", |
| f"In the end {hero} carried {target} home, lighter than before.", |
| ] |
|
|
|
|
| def _betrayal(ctx): |
| rng = ctx["rng"] |
| hero = ctx["hero_full"] |
| creature_full = ctx["creature_full"] |
| realm, magic = ctx["realm"], ctx["magic"] |
| ally_full = rng.choice(ARCHETYPES) |
| if ally_full == hero: |
| ally_full = "an old companion" |
| secret = rng.choice([ |
| "had been hiding the true name of the realm", |
| "had sold the village's silence for safe passage", |
| "was never mortal to begin with", |
| "had been shaping the hero's dreams for years", |
| ]) |
| return [ |
| f"For years {hero} and {ally_full} shared the work of {realm}.", |
| f"Then {creature_full} appeared at the door with a confession.", |
| f"It seemed the companion {secret}.", |
| f"{_cap(hero)} answered not with anger but with {magic}.", |
| "What was broken could not be mended, only understood.", |
| ] |
|
|
|
|
| def _discovery(ctx): |
| rng = ctx["rng"] |
| hero = ctx["hero_full"] |
| creature_full = ctx["creature_full"] |
| realm, magic = ctx["realm"], ctx["magic"] |
| found = rng.choice([ |
| "a sealed letter from a dead king", |
| "a door standing in the middle of an empty field", |
| "a well that whispered in a forgotten tongue", |
| "a child's drawing of a place that did not exist", |
| "a clock running backwards", |
| "a mirror showing a room that was not there", |
| ]) |
| return [ |
| f"While walking the edges of {realm}, {hero} found {found}.", |
| "At first it seemed harmless, even quaint.", |
| f"But {creature_full} would not come near it, and would say why.", |
| f"Slowly {hero} understood the old craft of {magic} was the only key.", |
| "What was uncovered could not be buried again.", |
| ] |
|
|
|
|
| def _transformation(ctx): |
| rng = ctx["rng"] |
| hero = ctx["hero_full"] |
| creature_full = ctx["creature_full"] |
| realm, magic = ctx["realm"], ctx["magic"] |
| change = rng.choice([ |
| "into a creature of bark and slow water", |
| "into someone who could not be remembered", |
| "into a keeper of small, impossible fires", |
| "into a version of themselves ten years younger", |
| "into a bridge between two feuding villages", |
| ]) |
| return [ |
| f"On the longest night of the year, {hero} changed {change}.", |
| f"The folk of {realm} did not know whether to mourn or rejoice.", |
| f"Only {creature_full} seemed unsurprised, and waited patiently.", |
| f"To learn to live in this new shape, {hero} studied {magic}.", |
| "Some changes, once made, choose not to be undone.", |
| ] |
|
|
|
|
| def _meeting(ctx): |
| rng = ctx["rng"] |
| hero = ctx["hero_full"] |
| creature_full = ctx["creature_full"] |
| realm, magic = ctx["realm"], ctx["magic"] |
| stranger_full = rng.choice(ARCHETYPES) |
| if stranger_full == hero: |
| stranger_full = "a hooded traveller" |
| bargain = rng.choice([ |
| "a year of silence in exchange for one true answer", |
| "their shadow, traded for safe passage home", |
| "three questions, no more and no less", |
| "the memory of their first love", |
| "a single seed from the heart-tree", |
| ]) |
| return [ |
| f"At the boundary of {realm}, {hero} met {stranger_full}.", |
| f"The stranger offered a bargain: {bargain}.", |
| f"{_cap(creature_full)} watched from the reeds and said nothing.", |
| f"{_cap(hero)} weighed the cost in the old way of {magic}.", |
| "Whatever was decided, both walked away changed.", |
| ] |
|
|
|
|
| |
| SCAFFOLDS = [_quest, _betrayal, _discovery, _transformation, _meeting] |
|
|
| |
| |
| |
| MORALS: List[str] = [ |
| "A kindness given in secret returns when it is most needed.", |
| "The cost of a thing is rarely its price.", |
| "What we cannot name, we cannot truly keep.", |
| "A road walked twice is never the same road.", |
| "Patience is the quietest form of courage.", |
| "The smallest promise weighs the most.", |
| "Even the lost have a direction; it is simply not ours.", |
| "To listen is to lend someone a piece of your life.", |
| "A wound ignored does not heal; it waits.", |
| "We are remembered not for what we took, but what we carried.", |
| "The map is not the land, but it can break your heart.", |
| "Silence, like salt, preserves and ruins in equal measure.", |
| "Grief is the tuition the living pay for love.", |
| "A door closed in kindness is still a door closed.", |
| "The brave are seldom the loudest.", |
| "Old debts do not rust.", |
| "Mercy costs nothing but the will to give it.", |
| "The longest journey is the one postponed.", |
| "What fires forge, fires also test.", |
| "Truth travels slowly, but it does travel.", |
| "Beware the bargain that costs only your silence.", |
| "The hand that feeds the wolf still feeds the wolf.", |
| "Hope is a habit, not a feeling.", |
| "Even shattered glass once held the morning.", |
| "You cannot outrun the name you have earned.", |
| ] |
|
|
| |
| |
| |
| class StoryGenerator: |
| """Procedurally generates unique fables.""" |
|
|
| def __init__(self, seed: int = DATA.seed) -> None: |
| self.rng = random.Random(seed) |
|
|
| |
| def sample_ingredients(self) -> dict: |
| """Sample hero/creature/realm/magic and return a scaffold context dict.""" |
| hero_full = self.rng.choice(ARCHETYPES) |
| creature_full = self.rng.choice(CREATURES) |
| realm = self.rng.choice(REALMS) |
| magic = self.rng.choice(MAGIC_SYSTEMS) |
| return { |
| "hero_full": hero_full, |
| "creature_full": creature_full, |
| "realm": realm, |
| "magic": magic, |
| "rng": self.rng, |
| } |
|
|
| def _opening(self, hero_full: str, realm: str) -> str: |
| templates = [ |
| f"In {realm} there lived {hero_full}.", |
| f"Long ago, when {realm} was still young, {hero_full} kept a quiet life.", |
| f"Few in {realm} knew the name of {hero_full}, but those who did did not forget.", |
| f"This is the story of {hero_full}, and of the trouble that found them in {realm}.", |
| f"To understand {realm}, you must first understand {hero_full}.", |
| ] |
| return self.rng.choice(templates) |
|
|
| def generate_story(self, index: int) -> dict: |
| """Generate a single fable. Returns a dict with text + metadata.""" |
| ctx = self.sample_ingredients() |
| scaffold = self.rng.choice(SCAFFOLDS) |
| body = scaffold(ctx) |
|
|
| |
| if self.rng.random() < DATA.curated_fraction: |
| moral = self.rng.choice(MORALS) |
| moral_source = "curated" |
| else: |
| moral = self._synthesised_moral() |
| moral_source = "synthetic" |
|
|
| text = ( |
| self._opening(ctx["hero_full"], ctx["realm"]) |
| + " " + _sentence_join(body) |
| + " " + moral |
| ) |
| return { |
| "id": index, |
| "text": text.strip(), |
| "hero": ctx["hero_full"], |
| "creature": ctx["creature_full"], |
| "realm": ctx["realm"], |
| "magic": ctx["magic"], |
| "scaffold": scaffold.__name__.lstrip("_"), |
| "moral_source": moral_source, |
| "moral": moral, |
| } |
|
|
| def _synthesised_moral(self) -> str: |
| """Build a fresh aphorism from fragments (keeps vocab diverse).""" |
| subject = self.rng.choice([ |
| "the keeper of the path", "a stranger in need", |
| "those who listen", "the patient heart", |
| "the one who waits", "a stubborn hope", |
| "an unspoken name", "a quiet promise", |
| ]) |
| verb = self.rng.choice([ |
| "outlasts", "outlives", "finds", "remembers", |
| "rewrites", "redeems", "outwaits", "unmakes", |
| ]) |
| obj = self.rng.choice([ |
| "the loudest storm", |
| "the cleverest lie", |
| "the sharpest blade", |
| "the deepest wound", |
| "the longest winter", |
| "the brightest crown", |
| "the swiftest river", |
| ]) |
| return f"In the end, {subject} {verb} {obj}." |
|
|
| |
| def generate_batch(self, n: int, start_index: int = 0) -> List[dict]: |
| return [self.generate_story(start_index + i) for i in range(n)] |
|
|
|
|
| def estimate_combination_space() -> int: |
| """Lower bound on the number of distinct ingredient combos.""" |
| return ( |
| len(ARCHETYPES) * len(CREATURES) * len(REALMS) * len(MAGIC_SYSTEMS) * |
| len(SCAFFOLDS) |
| ) |
|
|