Codex Codex commited on
Commit
3e8abf3
Β·
1 Parent(s): 782f6e2

Improve story quality: richer 2-3 sentence pages, better narration

Browse files

Storybook and bedtime stories were generating 1-2 sentence pages (~1 min
of audio total). This updates all story generation to produce richer,
more emotionally engaging 2-3 sentence pages (~3 min of narration).

Changes:
- FEW_SHOT_EXEMPLAR: rewritten with 2-3 vivid sentences per page,
sensory details, clear story arc (introduce / build / resolve / teach)
- build_story_prompt: rules now ask for 2-3 warm, detailed sentences
with colours, sounds, emotions; clearer arc guidance
- generate_story_gpu: max_new_tokens 800 -> 1200, duration 60s -> 90s
- BEDTIME_FEW_SHOT: rewritten with 2-3 calm, lullaby-paced sentences,
soothing sensory details (moonlight, moss, slow breathing)
- generate_bedtime_story_gpu: rules updated, 800 -> 1200 tokens, 90s
- THEME_TEMPLATES arc A for all 6 themes: rewritten with 2-3 sentence
pages that are vivid, emotional, and meaningful as fallback stories

Co-Authored-By: Codex <noreply@codex.ai>

Files changed (1) hide show
  1. app.py +69 -63
app.py CHANGED
@@ -144,12 +144,12 @@ import random as _random
144
  THEME_TEMPLATES = {
145
  "brave adventure": [
146
  [ # arc A: overcoming fear of the dark
147
- ("{hero} was afraid of the dark, but wanted to be brave.", "{hero} looking nervously at the dark forest path"),
148
- ("One night, a baby bird cried from inside the dark trees.", "{hero} hearing a bird cry from the shadowy forest"),
149
- ("{hero} took one small step forward, then another.", "{hero} stepping carefully into the dark with a tiny lantern"),
150
- ("Inside the forest, moonlight made everything look magical.", "{hero} looking around in wonder at the moonlit trees"),
151
- ("{hero} found the bird and gently carried it home.", "{hero} cradling a small bird carefully in both hands"),
152
- ("Back safe, {hero} smiled β€” brave hearts face their fears.", "{hero} smiling proudly outside the forest, holding the bird"),
153
  ],
154
  [ # arc B: the broken bridge
155
  ("{hero} set off to bring bread to grandmother across the river.", "{hero} walking cheerfully with a basket of bread"),
@@ -170,12 +170,12 @@ THEME_TEMPLATES = {
170
  ],
171
  "making a new friend": [
172
  [ # arc A: the new kid
173
- ("{hero} was nervous β€” today was the first day at a new place.", "{hero} standing at a doorway looking shy and unsure"),
174
- ("Everyone already seemed to know each other.", "{hero} watching other children play together"),
175
- ("Then {hero} saw someone else sitting alone by the fence.", "{hero} noticing another child sitting quietly alone"),
176
- ("{hero} walked over and said, 'Hi, I'm {hero}. Want to play?'", "{hero} walking towards the lonely child with a warm smile"),
177
- ("The child's face lit up like sunshine.", "{hero} and the new friend laughing and playing together"),
178
- ("{hero} learned β€” one small hello can change everything.", "{hero} and the new friend waving goodbye, happy and tired"),
179
  ],
180
  [ # arc B: the robot who didn't know how
181
  ("{hero} met a little robot who had never played before.", "{hero} meeting a small friendly robot in a sunny park"),
@@ -196,12 +196,12 @@ THEME_TEMPLATES = {
196
  ],
197
  "overcoming a fear": [
198
  [ # arc A: scared of thunder
199
- ("{hero} hid under the blankets every time it thundered.", "{hero} buried under a pile of blankets during a storm"),
200
- ("Grandpa sat beside {hero} and told a secret.", "{hero} peeking out from the blankets while grandpa smiles"),
201
- ("'Thunder is just clouds bumping into each other,' grandpa said.", "{hero} listening with wide eyes to grandpa's story"),
202
- ("{hero} imagined grumpy clouds saying sorry to each other.", "{hero} imagining funny fluffy clouds arguing in the sky"),
203
- ("The next crash came β€” and {hero} laughed instead of hiding!", "{hero} laughing boldly at the window during the storm"),
204
- ("{hero} learned that knowing why things happen makes them less scary.", "{hero} and grandpa watching lightning together, smiling"),
205
  ],
206
  [ # arc B: the deep swimming pool
207
  ("{hero} loved watching others swim but wouldn't go past the steps.", "{hero} sitting on the pool steps, looking at the water"),
@@ -222,12 +222,12 @@ THEME_TEMPLATES = {
222
  ],
223
  "helping someone": [
224
  [ # arc A: the broken toy shop
225
- ("{hero} passed the old toy shop and saw the owner crying.", "{hero} stopping to look at a sad old toy-maker"),
226
- ("A shelf had fallen and smashed twenty toys on the floor.", "{hero} seeing broken toys scattered across the floor"),
227
- ("{hero} rolled up their sleeves without being asked.", "{hero} picking up toy pieces with determined eyes"),
228
- ("Piece by piece, {hero} and the owner fixed each one.", "{hero} and the toy-maker gluing pieces together carefully"),
229
- ("The last toy fixed was a little wooden bird that sang.", "{hero} and the owner listening to the bird sing again"),
230
- ("{hero} learned that helping turns someone's worst day around.", "{hero} and the toy-maker shaking hands and smiling"),
231
  ],
232
  [ # arc B: the garden in winter
233
  ("{hero} noticed old Mrs. Patel's garden was bare and sad.", "{hero} looking over a fence at a grey winter garden"),
@@ -248,12 +248,12 @@ THEME_TEMPLATES = {
248
  ],
249
  "lost and found": [
250
  [ # arc A: the missing story book
251
- ("{hero}'s favourite storybook had vanished β€” gone without a trace!", "{hero} searching through a pile of scattered books"),
252
- ("It wasn't under the bed, in the kitchen, or the garden shed.", "{hero} checking more places, hands on hips"),
253
- ("{hero} retraced every step from the whole day.", "{hero} thinking hard with a finger on chin, eyes closed"),
254
- ("At the library β€” someone had borrowed it by mistake!", "{hero} spotting the book on a shelf at the library"),
255
- ("{hero} found the reader and they shared it together instead.", "{hero} and a new friend reading the book side by side"),
256
- ("{hero} learned that some things are even better when shared.", "{hero} and the new friend high-fiving over the open book"),
257
  ],
258
  [ # arc B: the lost recipe
259
  ("Granny had lost her secret recipe for the best cookies ever.", "{hero} watching granny search through messy recipe cards"),
@@ -274,12 +274,12 @@ THEME_TEMPLATES = {
274
  ],
275
  "learning something new": [
276
  [ # arc A: first time on a bicycle
277
- ("{hero} wanted to ride a bicycle but kept falling off.", "{hero} lying on the grass next to a toppled bicycle"),
278
- ("Every try ended with a scraped knee and wobbly legs.", "{hero} wobbling badly on the bike, face determined"),
279
- ("Papa said, 'Look where you want to go, not at the ground.'", "{hero} listening carefully to papa who points ahead"),
280
- ("{hero} fixed their eyes on the garden gate and pedalled.", "{hero} cycling straight and steady for the first time"),
281
- ("Zoom! The bicycle went all the way to the gate!", "{hero} shooting past the gate with arms raised in joy"),
282
- ("{hero} learned that looking forward helps you move forward.", "{hero} cycling confidently down a sunny lane"),
283
  ],
284
  [ # arc B: cooking for the first time
285
  ("{hero} decided to make soup all by themselves.", "{hero} standing on a step stool by the big kitchen pot"),
@@ -306,8 +306,10 @@ Write a 6-page children's storybook for age 5 about Finn the red fox with theme:
306
  Rules:
307
  - Finn must appear by name in EVERY page text.
308
  - No new characters introduced after page 3.
309
- - Each page is 1–2 sentences, simple and vivid.
310
- - Page 6 ends with a clear lesson Finn has learned.
 
 
311
  - The scene describes only what can be drawn in one illustration.
312
  - Return ONLY valid JSON (no extra text).
313
 
@@ -315,12 +317,12 @@ Rules:
315
  "title": "Finn and the Thunderstorm",
316
  "character_description": "A small red fox named Finn with big amber eyes, white-tipped ears, and a fluffy striped tail",
317
  "pages": [
318
- {"page": 1, "text": "Finn the red fox loved sunny days, but hid under the sofa whenever thunder rumbled.", "scene": "Finn the red fox curled up under a blue sofa, looking scared"},
319
- {"page": 2, "text": "One afternoon, a storm rolled in and Finn could hear thunder booming outside.", "scene": "Finn the red fox peering nervously through a rain-streaked window"},
320
- {"page": 3, "text": "Grandma Fox sat beside Finn and whispered a secret.", "scene": "Grandma Fox sitting calmly next to Finn the red fox on a warm rug"},
321
- {"page": 4, "text": "'Thunder is just clouds bumping together and saying sorry,' she told Finn.", "scene": "Finn the red fox imagining two fluffy cartoon clouds bumping and giggling"},
322
- {"page": 5, "text": "The next rumble came β€” and Finn laughed instead of hiding!", "scene": "Finn the red fox laughing at the window while rain pours outside"},
323
- {"page": 6, "text": "Finn learned that understanding why things happen makes them far less scary.", "scene": "Finn the red fox and Grandma Fox watching the storm together from a cozy armchair"}
324
  ]
325
  }
326
  """
@@ -332,10 +334,12 @@ def build_story_prompt(hero_name: str, theme: str, age: int) -> str:
332
  Write a 6-page children's storybook for age {age} about {hero_name} with theme: {theme}.
333
 
334
  Rules:
335
- - {hero_name} must appear by name in EVERY page text.
336
  - Keep all characters consistent β€” do NOT introduce random new characters mid-story.
337
- - Each page is 1–2 short, vivid sentences a {age}-year-old can understand.
338
- - Page 6 ends with a gentle lesson {hero_name} has learned.
 
 
339
  - Scene describes exactly what would appear in ONE illustration.
340
  - Return ONLY valid JSON (no explanation, no markdown fences):
341
  """
@@ -484,7 +488,7 @@ def load_sample_book() -> str:
484
  # ZEROGPU INFERENCE FUNCTIONS
485
  # ============================================================================
486
 
487
- @spaces.GPU(duration=60)
488
  def generate_story_gpu(hero_name: str, theme: str, age: int = 5) -> dict:
489
  """Generate a story on ZeroGPU, falling back to a deterministic local story."""
490
  try:
@@ -500,7 +504,7 @@ def generate_story_gpu(hero_name: str, theme: str, age: int = 5) -> dict:
500
  with torch.no_grad():
501
  out = model.generate(
502
  **inputs,
503
- max_new_tokens=GENERATION_PARAMS.max_story_tokens,
504
  do_sample=True,
505
  temperature=0.85,
506
  top_p=0.92,
@@ -1039,9 +1043,10 @@ Write a 6-page children's bedtime story for age 5 about Mia the bunny. Genre: Fo
1039
 
1040
  Rules:
1041
  - Mia must appear by name in EVERY page text.
1042
- - Use calm, soft language β€” words slow down and the child feels sleepy.
1043
- - Each page is 1–2 short, gentle sentences.
1044
- - Page 6 ends with Mia (or the child) falling peacefully asleep.
 
1045
  - Scene describes exactly what appears in one illustration.
1046
  - Return ONLY valid JSON (no markdown fences, no extra text).
1047
 
@@ -1049,12 +1054,12 @@ Rules:
1049
  "title": "Mia and the Owl's Lullaby",
1050
  "character_description": "A tiny white bunny named Mia with long soft ears, a pink nose, and a star-shaped patch on her back",
1051
  "pages": [
1052
- {"page": 1, "text": "Mia the bunny hopped into the forest as the moon rose above the trees.", "scene": "Mia the white bunny stepping onto a silver moonlit forest path"},
1053
- {"page": 2, "text": "Everything was very quiet β€” the whole forest seemed to be waiting.", "scene": "Mia the white bunny standing still, ears up, listening"},
1054
- {"page": 3, "text": "Then Mia heard a soft sound from high in the oak β€” an old owl humming.", "scene": "Mia the white bunny looking up at a sleepy owl on a branch"},
1055
- {"page": 4, "text": "The owl's song was low and slow, like warm honey flowing.", "scene": "The owl humming softly, eyes half-closed, as Mia listens below"},
1056
- {"page": 5, "text": "Mia's eyelids grew heavy, and she lay down on a bed of moss.", "scene": "Mia the white bunny curling up on soft green moss"},
1057
- {"page": 6, "text": "The owl sang on, and Mia drifted into the sweetest dream.", "scene": "Mia the white bunny fast asleep in the moonlit forest, peaceful"}
1058
  ]
1059
  }
1060
  """
@@ -1088,7 +1093,7 @@ def build_bedtime_html(title: str, pages: list) -> str:
1088
  )
1089
 
1090
 
1091
- @spaces.GPU(duration=60)
1092
  def generate_bedtime_story_gpu(hero_name: str, genre: str, mood: str) -> dict:
1093
  """Generate a gentle bedtime story with MiniCPM5-1B."""
1094
  try:
@@ -1099,9 +1104,10 @@ def generate_bedtime_story_gpu(hero_name: str, genre: str, mood: str) -> dict:
1099
  f"Genre: {genre}. Mood: {mood}.\n\n"
1100
  f"Rules:\n"
1101
  f"- {hero_name} must appear by name in EVERY page text.\n"
1102
- f"- Use calm, slow, sleepy language throughout.\n"
1103
- f"- Each page: 1–2 gentle sentences only.\n"
1104
- f"- Page 6 must end with {hero_name} or the child falling peacefully asleep.\n"
 
1105
  f"- Do NOT introduce random unrelated characters.\n"
1106
  f"- Return ONLY valid JSON:\n"
1107
  )
@@ -1114,7 +1120,7 @@ def generate_bedtime_story_gpu(hero_name: str, genre: str, mood: str) -> dict:
1114
  ).to("cuda")
1115
  with torch.no_grad():
1116
  out = model.generate(
1117
- **inputs, max_new_tokens=800,
1118
  do_sample=True, temperature=0.85, top_p=0.92, repetition_penalty=1.1,
1119
  )
1120
  response = tok.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
 
144
  THEME_TEMPLATES = {
145
  "brave adventure": [
146
  [ # arc A: overcoming fear of the dark
147
+ ("{hero} loved golden daytime more than anything, but when the sun went down, a cold shiver always crept up their back. The shadows in the forest path twisted into strange shapes, and {hero}'s heart would beat very fast. {hero} dreamed of being brave β€” but brave felt so very far away.", "{hero} standing nervously at the edge of a dark forest path at dusk, a tiny lantern in hand"),
148
+ ("One night, a tiny bird cried out from deep inside the dark trees β€” a small, lost sound. {hero} stood very still at the forest's edge, listening hard. The bird needed help, and {hero} was the only one close enough to hear it.", "{hero} listening with wide eyes at the forest entrance, a faint bird cry coming from the dark trees"),
149
+ ("{hero} took one shaky breath and stepped onto the dark path, one careful foot at a time. The lantern cast a warm golden circle around {hero}, pushing back the shadows just enough. 'One step at a time,' {hero} whispered to the lantern.", "{hero} stepping carefully down the dark forest path, holding a small glowing lantern"),
150
+ ("Inside the trees, something surprising happened β€” the dark was full of beauty, not danger. Moonlight turned the leaves silver and made the dewdrops sparkle like tiny stars. {hero} felt the fear beginning to melt, replaced by wide-eyed wonder.", "{hero} standing in moonlit forest, looking around in amazement at glowing leaves and sparkling dewdrops"),
151
+ ("{hero} found the baby bird on a low branch, ruffled and trembling. Gently, gently, {hero} cupped both hands around the tiny creature and felt its quick little heartbeat. Walking home through the moonlit trees, {hero} felt ten times taller than before.", "{hero} carefully cradling a tiny bird in cupped hands, walking home through the glowing moonlit forest"),
152
+ ("Back in the warm light of home, {hero} placed the bird safely in a nest of soft cloth. Brave hearts don't need the fear to disappear β€” they just need to start walking, {hero} had discovered. {hero} looked out at the dark night and, for the very first time, thought it looked beautiful.", "{hero} smiling proudly in the warm doorway light, holding the safe little bird, with the moonlit forest behind"),
153
  ],
154
  [ # arc B: the broken bridge
155
  ("{hero} set off to bring bread to grandmother across the river.", "{hero} walking cheerfully with a basket of bread"),
 
170
  ],
171
  "making a new friend": [
172
  [ # arc A: the new kid
173
+ ("{hero} stood at the entrance of the new place with a tight feeling in their chest. Everyone inside already seemed to know each other β€” laughing, running, belonging. {hero} didn't know a single name, and the morning felt very long.", "{hero} standing shyly at a doorway watching other children play happily together"),
174
+ ("Then {hero} noticed someone else β€” sitting alone by the fence, watching the others too. The child had the same tight look on their face that {hero} had. Something about that made {hero} feel a little less alone.", "{hero} noticing a lonely child sitting quietly by a fence, looking the same way {hero} feels"),
175
+ ("{hero} took a deep breath, walked over, and said the five most important words: 'Hi. Do you want to play?' The words came out a bit wobbly, but they came out. The other child looked up slowly.", "{hero} walking towards the lonely child with a warm, nervous smile, hand raised in greeting"),
176
+ ("The child's whole face changed β€” like sunshine breaking through clouds. 'Yes,' they said, and both of them stood up at exactly the same time. {hero} had never been so glad to ask a question.", "{hero} and the new friend laughing together as they stand up at the same time"),
177
+ ("By lunchtime, {hero} and the new friend were making up the rules of an entirely new game. They had invented their own handshake and a secret name for their team. The morning that had felt so long was suddenly over.", "{hero} and the new friend playing their new game together, both laughing"),
178
+ ("{hero} waved goodbye at the end of the day with a full, happy heart. One small hello had turned a stranger into a friend, and a lonely morning into the best day in a long time. {hero} had learned that the bravest thing can be the simplest thing.", "{hero} and the new friend waving goodbye happily, both tired and smiling"),
179
  ],
180
  [ # arc B: the robot who didn't know how
181
  ("{hero} met a little robot who had never played before.", "{hero} meeting a small friendly robot in a sunny park"),
 
196
  ],
197
  "overcoming a fear": [
198
  [ # arc A: scared of thunder
199
+ ("Every time thunder rumbled, {hero} dove under the blankets and held on very tight. The sound was so big and so sudden β€” it seemed to fill the whole world. {hero} had tried to be brave, but the thunder was always louder than the bravery.", "{hero} burrowed completely under a pile of colourful blankets while a storm rages outside"),
200
+ ("One stormy afternoon, Grandpa came and sat quietly beside {hero}'s blanket fort. He didn't say 'don't be scared' or 'it's nothing.' He just sat there, calm and warm, until {hero} peeked out. 'Want to know a secret?' he whispered.", "{hero} peeking out from under the blankets to see Grandpa sitting calmly and smiling"),
201
+ ("'Thunder,' said Grandpa softly, 'is just two big clouds bumping into each other by accident β€” and then saying sorry very loudly.' {hero} blinked. That was not what {hero} had expected thunder to be. A tiny smile appeared.", "{hero} listening with wide eyes to Grandpa's explanation, a small surprised smile on their face"),
202
+ ("{hero} closed both eyes and tried to imagine it β€” two enormous fluffy clouds bonking heads and making embarrassed faces. A giggle escaped before {hero} could stop it. The next rumble came and for the first time, it sounded almost funny.", "{hero} grinning with eyes closed, imagining two cartoon clouds bumping together and looking sheepish"),
203
+ ("BOOM! The biggest thunder of the night shook the windows β€” and {hero} burst out laughing. Grandpa laughed too, and together they ran to the window to watch the lightning put on its show. The storm looked completely different now.", "{hero} and Grandpa laughing at the window together as dramatic lightning flashes outside in the dark"),
204
+ ("When the storm finally passed, {hero} and Grandpa stepped outside and breathed in the clean, rain-washed air. {hero} had learned something that night that no book could teach β€” understanding a thing is the first step to not being afraid of it. {hero} looked up at the clearing sky and felt proud.", "{hero} and Grandpa standing outside after the storm, looking up at a clearing sky with smiles"),
205
  ],
206
  [ # arc B: the deep swimming pool
207
  ("{hero} loved watching others swim but wouldn't go past the steps.", "{hero} sitting on the pool steps, looking at the water"),
 
222
  ],
223
  "helping someone": [
224
  [ # arc A: the broken toy shop
225
+ ("{hero} was walking past the old toy shop when the sound of quiet crying stopped them in their tracks. Through the window, {hero} could see the toy-maker sitting on the floor with her head in her hands. A long wooden shelf had fallen and scattered twenty carefully painted toys across the floorboards.", "{hero} stopping outside the toy shop window, seeing the sad toy-maker among broken toys"),
226
+ ("The toy-maker looked up at {hero} with red eyes. 'Years of work,' she said softly, 'all broken in a moment.' {hero} looked at the jumble of wings, wheels, and tiny painted faces. Without being asked, {hero} stepped inside and knelt down.", "{hero} kneeling on the toy-shop floor, gently picking up pieces of broken toys"),
227
+ ("{hero} sorted the pieces carefully β€” wings in one pile, wheels in another, tiny hats and buttons in a third. The toy-maker watched for a moment, then picked up the glue and sat down beside {hero}. They didn't need to say anything. They just began.", "{hero} and the toy-maker sitting together on the shop floor, sorting toy pieces into careful groups"),
228
+ ("Piece by careful piece, the toys came back together. {hero} held the pieces steady while the toy-maker's practiced hands glued and pressed. Some were wonky; some had chips missing. But each one was whole again, and that was what mattered.", "{hero} and the toy-maker carefully gluing a toy together, their hands working side by side"),
229
+ ("The very last toy was a small wooden bird with a key in its back. The toy-maker wound it gently, set it on the counter, and they both held their breath. Then β€” the most perfect little song rang through the quiet shop. {hero} felt the hairs on their arms stand up.", "{hero} and the toy-maker listening with soft smiles as a small wooden bird on the counter plays its song"),
230
+ ("{hero} and the toy-maker stood at the door as the afternoon light turned golden. 'You didn't have to stop,' said the toy-maker quietly. 'I know,' said {hero}. {hero} had learned that helping someone on their worst day costs nothing β€” but can change everything.", "{hero} and the toy-maker standing at the sunny shop door, shaking hands warmly with smiles"),
231
  ],
232
  [ # arc B: the garden in winter
233
  ("{hero} noticed old Mrs. Patel's garden was bare and sad.", "{hero} looking over a fence at a grey winter garden"),
 
248
  ],
249
  "lost and found": [
250
  [ # arc A: the missing story book
251
+ ("{hero}'s most treasured storybook had vanished β€” completely, utterly gone. {hero} checked under the bed, behind the sofa cushions, and inside every drawer twice. The whole morning felt grey without it.", "{hero} searching through a pile of scattered books with a worried, determined expression"),
252
+ ("It wasn't in the kitchen, the garden shed, or the coat-pocket where lost things often hid. {hero} stood in the middle of the room with hands on hips, thinking hard. 'Where,' said {hero} very firmly, 'did you go?'", "{hero} standing hands-on-hips in the middle of the room, looking puzzled"),
253
+ ("{hero} closed both eyes and retraced every single step of the day before. Morning β€” the bench by the door. Then the walk. Then... the library. {hero}'s eyes flew open. The library!", "{hero} eyes suddenly wide with an idea, finger pointing up"),
254
+ ("Sure enough, there it was β€” sitting on a library shelf between two books that didn't belong to it. But it wasn't alone. A child was holding it carefully, almost at the last page. {hero} stopped and watched.", "{hero} spotting the beloved book on a library shelf, a child sitting nearby reading it"),
255
+ ("{hero} waited until the child finished the last page, and the child's face went soft and quiet the way it does at the end of a perfect story. {hero} smiled and sat down beside the child. 'That's my favourite book,' {hero} said. 'I know all the best bits by heart.' And they read it again, together.", "{hero} and a new friend sitting side-by-side at the library, reading the book together"),
256
+ ("{hero} walked home with the book tucked under one arm and a warm feeling tucked inside their chest. Some things are better when they're shared β€” stories most of all. {hero} had lost a book and found a friend, which was a much better trade.", "{hero} walking home smiling with the book under their arm, waving goodbye to the new friend"),
257
  ],
258
  [ # arc B: the lost recipe
259
  ("Granny had lost her secret recipe for the best cookies ever.", "{hero} watching granny search through messy recipe cards"),
 
274
  ],
275
  "learning something new": [
276
  [ # arc A: first time on a bicycle
277
+ ("{hero} had wanted to ride the bicycle since the very first day of summer. But every single time, the wheels wobbled and {hero} tumbled sideways onto the grass. By the fourth fall, {hero}'s knees were scraped and the bicycle looked very pleased with itself.", "{hero} sitting on the grass beside the fallen bicycle, looking frustrated but determined"),
278
+ ("Every try ended the same way β€” a moment of hope, then a wobble, then the ground. {hero} sat up, brushed off the mud, and stared at the bicycle. The bicycle, {hero} decided, was not winning today.", "{hero} wobbling dramatically on the bicycle, trying hard not to fall"),
279
+ ("Papa crouched beside {hero} and said something that didn't make sense at first. 'Don't look at the ground. Look at where you want to go.' {hero} frowned at the gate at the end of the path. It felt very far away. But {hero} nodded.", "{hero} listening carefully as Papa points towards the garden gate ahead"),
280
+ ("{hero} climbed back on, fixed both eyes on the gate, and pedalled. The wheels still wobbled β€” but just a little. {hero} kept looking forward. The wobble got smaller. The gate got closer.", "{hero} cycling carefully with eyes fixed ahead, wheels wobbling less and less"),
281
+ ("Zoom! {hero} shot past the gate with a shout that startled every bird in the garden. The bicycle was going fast and straight and perfectly. {hero} had done it β€” had actually, genuinely, completely done it.", "{hero} flying past the garden gate on the bicycle, arms raised in triumph"),
282
+ ("{hero} rode up and down the lane until the sun went low. That evening, {hero} understood something new: looking forward isn't just how you ride a bicycle. It's how you do almost everything hard. {hero} couldn't wait to see what else was possible.", "{hero} cycling confidently down a golden sunny lane, a huge proud smile on their face"),
283
  ],
284
  [ # arc B: cooking for the first time
285
  ("{hero} decided to make soup all by themselves.", "{hero} standing on a step stool by the big kitchen pot"),
 
306
  Rules:
307
  - Finn must appear by name in EVERY page text.
308
  - No new characters introduced after page 3.
309
+ - Each page is 2–3 sentences β€” vivid, warm, and emotionally engaging.
310
+ - Use sensory details: colours, sounds, textures, and feelings.
311
+ - Pages 1–2 introduce the character and problem. Pages 3–4 build the challenge. Pages 5–6 resolve and teach.
312
+ - Page 6 ends with a warm lesson Finn has learned and a feeling of pride.
313
  - The scene describes only what can be drawn in one illustration.
314
  - Return ONLY valid JSON (no extra text).
315
 
 
317
  "title": "Finn and the Thunderstorm",
318
  "character_description": "A small red fox named Finn with big amber eyes, white-tipped ears, and a fluffy striped tail",
319
  "pages": [
320
+ {"page": 1, "text": "Finn the red fox loved sunny mornings more than anything in the world, but the very first rumble of thunder made Finn's whole body tremble. Whenever dark clouds rolled in, Finn would crawl under the sofa and squeeze both eyes tightly shut. Finn wanted to be brave β€” but brave seemed like something meant for bigger foxes.", "scene": "Finn the red fox curled tightly under a blue sofa, eyes shut, while dark storm clouds fill the window behind the curtains"},
321
+ {"page": 2, "text": "One stormy afternoon, thunder shook the whole cottage and rattled the teacups on the shelf. Finn buried deep under the blankets, heart going thump-thump-thump. Grandma Fox came quietly and sat on the edge of the bed without saying a word.", "scene": "Finn the red fox burrowed under a patchwork blanket on a bed, Grandma Fox sitting calmly beside in warm lamplight"},
322
+ {"page": 3, "text": "Grandma Fox leaned in close and whispered a secret into Finn's ear. 'Thunder is just two clouds bumping into each other and saying sorry,' she said softly. Finn's ears perked up, and one eye opened just a little.", "scene": "Grandma Fox leaning close to whisper to Finn the red fox peeking out from under the blanket"},
323
+ {"page": 4, "text": "Finn closed both eyes again and tried very hard to imagine it β€” two big fluffy clouds bumping heads and making an oops face. A tiny giggle bubbled up before Finn could stop it. The next rumble came, and this time it sounded almost funny instead of frightening.", "scene": "Finn the red fox grinning with closed eyes, imagining two round cartoon clouds bumping together with surprised faces"},
324
+ {"page": 5, "text": "The next crack of thunder boomed across the sky β€” and Finn laughed out loud. Grandma Fox laughed too, and together they ran to the window to watch the lightning flash and dance. The storm looked completely different now, like a wild and wonderful show put on just for them.", "scene": "Finn the red fox and Grandma Fox laughing at a rain-streaked window as bright lightning flashes outside in the dark sky"},
325
+ {"page": 6, "text": "When the storm finally passed, Finn stood in the doorway and breathed in the clean, rain-washed air. Grandma Fox held Finn's paw quietly β€” some lessons don't need extra words. Finn had learned that understanding why something happens is the very first step to not being afraid of it anymore.", "scene": "Finn the red fox and Grandma Fox standing in the open doorway watching a golden rainbow stretch across the sky after the storm"}
326
  ]
327
  }
328
  """
 
334
  Write a 6-page children's storybook for age {age} about {hero_name} with theme: {theme}.
335
 
336
  Rules:
337
+ - {hero_name} must appear by name in EVERY page text. Every single page.
338
  - Keep all characters consistent β€” do NOT introduce random new characters mid-story.
339
+ - Each page: 2–3 vivid, emotionally warm sentences a {age}-year-old can follow and feel.
340
+ - Use sensory details β€” colours, sounds, textures, emotions β€” to bring each moment alive.
341
+ - Pages 1–2 introduce {hero_name} and the problem. Pages 3–4 build the challenge. Pages 5–6 resolve it and teach.
342
+ - Page 6 ends with a clear, warm lesson {hero_name} has learned and a feeling of pride or joy.
343
  - Scene describes exactly what would appear in ONE illustration.
344
  - Return ONLY valid JSON (no explanation, no markdown fences):
345
  """
 
488
  # ZEROGPU INFERENCE FUNCTIONS
489
  # ============================================================================
490
 
491
+ @spaces.GPU(duration=90)
492
  def generate_story_gpu(hero_name: str, theme: str, age: int = 5) -> dict:
493
  """Generate a story on ZeroGPU, falling back to a deterministic local story."""
494
  try:
 
504
  with torch.no_grad():
505
  out = model.generate(
506
  **inputs,
507
+ max_new_tokens=1200,
508
  do_sample=True,
509
  temperature=0.85,
510
  top_p=0.92,
 
1043
 
1044
  Rules:
1045
  - Mia must appear by name in EVERY page text.
1046
+ - Use calm, slow, sleepy language β€” gentle sentences that feel like a lullaby.
1047
+ - Each page is 2–3 soft, unhurried sentences. No excitement; only warmth and peace.
1048
+ - Use soothing sensory details: soft moonlight, warm moss, quiet sounds, slow breathing.
1049
+ - Page 6 ends with Mia (or the child) drifting peacefully to sleep.
1050
  - Scene describes exactly what appears in one illustration.
1051
  - Return ONLY valid JSON (no markdown fences, no extra text).
1052
 
 
1054
  "title": "Mia and the Owl's Lullaby",
1055
  "character_description": "A tiny white bunny named Mia with long soft ears, a pink nose, and a star-shaped patch on her back",
1056
  "pages": [
1057
+ {"page": 1, "text": "As the sun dipped below the trees, Mia the bunny padded softly into the forest where everything was turning gold and purple. The air smelled of pine needles and cool evening dew. Mia's little paws made no sound at all on the mossy path.", "scene": "Mia the white bunny walking gently along a golden-purple evening forest path covered in soft moss"},
1058
+ {"page": 2, "text": "The forest grew very still, as if the whole world was taking a long, slow breath. Even the leaves stopped rustling, and the stream became barely a whisper. Mia sat down and listened to the quiet.", "scene": "Mia the white bunny sitting very still on a mossy log, eyes half-closed, surrounded by a calm twilight forest"},
1059
+ {"page": 3, "text": "Then, from somewhere high in the old oak tree, Mia heard the softest sound β€” an owl, humming a gentle tune. The notes floated down through the branches like feathers. Mia tilted her ears upward and smiled.", "scene": "Mia the white bunny looking up at a sleepy owl perched on a moonlit oak branch above"},
1060
+ {"page": 4, "text": "The owl's song was slow and low, like warm honey poured into a cup. With every note, Mia felt her shoulders soften and her eyes grow heavier. The whole forest seemed to hum along.", "scene": "The old owl humming with eyes half-shut, Mia the bunny below resting her cheek on her paws listening"},
1061
+ {"page": 5, "text": "Mia found a bed of the softest green moss she had ever touched, and curled herself into a tiny ball. Her breathing slowed, and the owl's song wrapped around her like a blanket. Everything felt very safe and very warm.", "scene": "Mia the white bunny curled in a tiny ball on thick green moss, eyes almost closed, moonlight filtering through the trees"},
1062
+ {"page": 6, "text": "The owl sang on and on, and Mia drifted into the most peaceful dream. Her pink nose twitched once, then was still. Somewhere above, a single star blinked goodnight.", "scene": "Mia the white bunny fast asleep on moonlit moss, a single star glowing above the peaceful forest"}
1063
  ]
1064
  }
1065
  """
 
1093
  )
1094
 
1095
 
1096
+ @spaces.GPU(duration=90)
1097
  def generate_bedtime_story_gpu(hero_name: str, genre: str, mood: str) -> dict:
1098
  """Generate a gentle bedtime story with MiniCPM5-1B."""
1099
  try:
 
1104
  f"Genre: {genre}. Mood: {mood}.\n\n"
1105
  f"Rules:\n"
1106
  f"- {hero_name} must appear by name in EVERY page text.\n"
1107
+ f"- Use calm, slow, sleepy language β€” each page should feel like a lullaby.\n"
1108
+ f"- Each page: 2–3 soft, unhurried sentences. No excitement; only warmth and peace.\n"
1109
+ f"- Include gentle sensory details: soft moonlight, quiet sounds, warm textures.\n"
1110
+ f"- Page 6 must end with {hero_name} or the child drifting peacefully asleep.\n"
1111
  f"- Do NOT introduce random unrelated characters.\n"
1112
  f"- Return ONLY valid JSON:\n"
1113
  )
 
1120
  ).to("cuda")
1121
  with torch.no_grad():
1122
  out = model.generate(
1123
+ **inputs, max_new_tokens=1200,
1124
  do_sample=True, temperature=0.85, top_p=0.92, repetition_penalty=1.1,
1125
  )
1126
  response = tok.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)