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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
463
464
465
466
467
468
"""
Mad Libs AI Prompt Generator
An interactive step-by-step wizard where an AI co-pilot suggests
creative ideas to spark imagination. Fill in the blanks bit by bit!
"""

import gradio as gr
import random
import json
from typing import List, Dict

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# CREATIVE SUGGESTION DATABASE โ€” The AI Co-Pilot's imagination engine
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

CREATIVE_BANK: Dict[str, List[str]] = {
    "setting": [
        "a cyberpunk city where neon rain never stops",
        "an abandoned space station orbiting a dying star",
        "a tiny village that exists inside a giant tree",
        "a library where every book is a portal to another world",
        "a post-apocalyptic carnival frozen in time",
        "a submarine city deep beneath Europa's ice ocean",
        "a desert where the sand sings memories aloud",
        "a Victorian mansion that rearranges its rooms each night",
        "a floating marketplace suspended between two cliffs",
        "a world where gravity works sideways after sunset",
        "a garden where forgotten ideas grow as strange flowers",
        "a train that travels through dreams instead of towns",
    ],
    "character": [
        "a retired superhero who runs a coffee shop",
        "a sentient AI that writes poetry in binary",
        "a ghost who doesn't realize they're dead",
        "a time-traveling librarian from the 23rd century",
        "a cat who secretly runs an underground information network",
        "a former villain trying to make amends one small act at a time",
        "a child who can hear the thoughts of buildings",
        "a robot learning what it means to be afraid",
        "a bard whose songs literally reshape reality",
        "a detective who solves crimes by tasting emotions",
        "a character who ages backwards and knows the future",
        "a shapeshifter stuck in the wrong form for a decade",
    ],
    "mood": [
        "nostalgic yet unsettling, like dรฉjร  vu that won't fade",
        "wildly optimistic despite overwhelming darkness",
        "bittersweet with a hint of cosmic wonder",
        "tense and electric, like the moment before lightning strikes",
        "dreamy and surreal with sudden moments of sharp clarity",
        "warm and cozy but with something watching from the shadows",
        "chaotic and joyful, like a symphony played by fireworks",
        "melancholic yet strangely comforting",
        "adrenaline-fueled wonder mixed with childlike awe",
        "quietly profound, the feeling of reading a secret message",
        "playfully sinister with unexpected heart",
        "ethereal and transcendent, beyond ordinary emotion",
    ],
    "action": [
        "discovers a door in their home that leads to their own childhood",
        "accidentally swaps bodies with their worst enemy for 24 hours",
        "finds a message in a bottle from their future self",
        "invents a machine that translates animal thoughts into music",
        "challenges Death to a game of their own creation",
        "discovers they've been fictional all along and meets their author",
        "trades one memory for one wish at a mysterious pawn shop",
        "befriends the monster under their bed who turns out to be lonely",
        "tries to return a library book that's 500 years overdue",
        "learns the city they live in is actually a giant spaceship waking up",
        "finds a camera that shows photos of tomorrow",
        "becomes the first human to understand whale songs completely",
    ],
    "twist": [
        "the villain was trying to save everyone all along",
        "the magic was actually advanced forgotten technology",
        "the protagonist has been dead since chapter one",
        "the world is a simulation, but the real world is worse",
        "the sidekick was the main character's future self in disguise",
        "the quest object was inside them the entire time",
        "everyone else is lying, and only the 'crazy' person tells the truth",
        "time is running backward, and only the reader realizes it",
        "the narrator is unreliable and hiding a terrible secret",
        "the love interest is actually a manifestation of the protagonist's guilt",
        "the fantasy kingdom is a metaphor for a mental health journey",
        "the happy ending requires an impossible sacrifice no one foresaw",
    ],
    "style": [
        "in the style of a noir detective story with poetic flourishes",
        "written as a series of unsent letters and found objects",
        "like a fairy tale told by someone who never believed in them",
        "as a dialogue-only screenplay with stage directions that lie",
        "in second person, putting YOU directly in the story",
        "as fragmented journal entries from multiple unreliable perspectives",
        "like an ancient myth being retold by a sarcastic modern narrator",
        "as a choose-your-own-adventure where every choice leads to wonder",
        "in the rhythm and structure of a villanelle poem but as prose",
        "as an IKEA instruction manual that slowly reveals a tragedy",
        "like a nature documentary narrating human behavior with alien detachment",
        "as a recipe that gradually becomes a love story",
    ],
    "object": [
        "a pocket watch that ticks only when lies are told nearby",
        "a pair of sunglasses that show people's true desires",
        "an umbrella that makes it rain only where you point it",
        "a compass that points to what you need, not where you want",
        "a mirror that reflects who you will be in ten years",
        "a pen that writes stories that come true for 24 hours",
        "a music box that plays the soundtrack of your best day",
        "a key that opens any door but locks one memory away forever",
        "a pair of shoes that walk you to where you're needed most",
        "a candle that burns with the color of your current emotion",
        "a photograph frame that shows the last moment of its previous owner",
        "a coin that always lands on what would make the best story",
    ],
}

WIZARD_STEPS = [
    {
        "id": "setting",
        "title": "๐ŸŒ Where does your story live?",
        "label": "Setting / World",
        "description": "Paint the canvas. Is it a crumbling castle? A neon future? A world made of cake?",
        "placeholder": "Describe your setting...",
        "emoji": "๐ŸŒ",
    },
    {
        "id": "character",
        "title": "๐Ÿง™โ€โ™‚๏ธ Who is your hero (or villain)?",
        "label": "Main Character",
        "description": "Every tale needs a heart. What makes them weird, wonderful, or wonderfully flawed?",
        "placeholder": "Describe your character...",
        "emoji": "๐Ÿง™โ€โ™‚๏ธ",
    },
    {
        "id": "object",
        "title": "๐Ÿ”ฎ What mysterious object appears?",
        "label": "Magical Object / MacGuffin",
        "description": "The plot needs a spark. A cursed coin? A singing toaster? A door to yesterday?",
        "placeholder": "Describe your mysterious object...",
        "emoji": "๐Ÿ”ฎ",
    },
    {
        "id": "action",
        "title": "โšก What wild thing happens?",
        "label": "Inciting Incident / Action",
        "description": "Shake things up! What impossible, hilarious, or terrifying event kicks it all off?",
        "placeholder": "Describe the key event...",
        "emoji": "โšก",
    },
    {
        "id": "mood",
        "title": "๐ŸŽญ What should it FEEL like?",
        "label": "Mood / Atmosphere",
        "description": "Set the emotional temperature. Creepy-cozy? Wildly hopeful? Melancholy magic?",
        "placeholder": "Describe the mood...",
        "emoji": "๐ŸŽญ",
    },
    {
        "id": "twist",
        "title": "๐ŸŒ€ What jaw-dropping twist awaits?",
        "label": "Plot Twist / Surprise",
        "description": "Drop the mic. What revelation flips everything upside down?",
        "placeholder": "Describe your twist...",
        "emoji": "๐ŸŒ€",
    },
    {
        "id": "style",
        "title": "โœ๏ธ How should it be TOLD?",
        "label": "Writing Style / Format",
        "description": "Form follows function. A noir monologue? A recipe that becomes a tragedy? Found letters?",
        "placeholder": "Describe the style or format...",
        "emoji": "โœ๏ธ",
    },
]


def get_suggestions(category: str, count: int = 5) -> List[str]:
    pool = CREATIVE_BANK.get(category, [])
    if not pool:
        return []
    shuffled = random.sample(pool, min(count, len(pool)))
    return shuffled


def format_suggestions(suggestions: List[str], category: str) -> str:
    lines = [f"### ๐Ÿ’ก AI Co-Pilot Suggestions for **{category}**"]
    for i, s in enumerate(suggestions, 1):
        lines.append(f"**{i}.** {s}")
    return "\n\n".join(lines)


def init_state():
    return {"step": 0, "answers": {}, "history": []}


def next_step(state):
    state = json.loads(state)
    step_idx = state["step"]
    if step_idx < len(WIZARD_STEPS):
        step_idx += 1
    state["step"] = step_idx
    return json.dumps(state)


def prev_step(state):
    state = json.loads(state)
    step_idx = state["step"]
    if step_idx > 0:
        step_idx -= 1
    state["step"] = step_idx
    return json.dumps(state)


def save_answer(state, answer: str):
    state = json.loads(state)
    step_idx = state["step"]
    if step_idx < len(WIZARD_STEPS):
        cat = WIZARD_STEPS[step_idx]["id"]
        state["answers"][cat] = answer
    return json.dumps(state)


def render_wizard(state_json: str, current_input: str = ""):
    state = json.loads(state_json)
    step_idx = state["step"]
    answers = state.get("answers", {})

    sidebar_lines = ["## ๐Ÿ“‹ Your Story So Far", ""]
    for i, step_def in enumerate(WIZARD_STEPS):
        emoji = step_def["emoji"]
        label = step_def["label"]
        ans = answers.get(step_def["id"], "")
        if i < step_idx:
            sidebar_lines.append(f"{emoji} **{label}** โœ“")
            sidebar_lines.append(f"\n> {ans[:60]}{'...' if len(ans) > 60 else ''}\n")
        elif i == step_idx:
            sidebar_lines.append(f"{emoji} **{label}** โ† ๐Ÿ–Š๏ธ *you are here*")
            sidebar_lines.append("\n> _filling in..._\n")
        else:
            sidebar_lines.append(f"{emoji} *{label}* โ—‹")
            sidebar_lines.append("")

    sidebar = "\n".join(sidebar_lines)

    if step_idx >= len(WIZARD_STEPS):
        return sidebar, render_final_prompt(answers), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)

    step = WIZARD_STEPS[step_idx]
    cat = step["id"]
    suggestions = get_suggestions(cat, 6)
    existing = answers.get(cat, "")

    header = f"## {step['emoji']} Step {step_idx + 1} of {len(WIZARD_STEPS)}: {step['title']}"
    desc = step["description"]
    sugg_md = format_suggestions(suggestions, step["label"])

    show_prev = step_idx > 0
    show_next = True
    show_generate = step_idx == len(WIZARD_STEPS) - 1

    textbox_val = existing if existing else (current_input if current_input else "")

    progress_pct = int((step_idx / len(WIZARD_STEPS)) * 100)
    progress_bar = f"### Progress: {progress_pct}%\n" + "โ–ˆ" * (progress_pct // 5) + "โ–‘" * (20 - progress_pct // 5)

    main_content = f"{progress_bar}\n\n{header}\n\n{desc}\n\n---\n\n{sugg_md}"

    return (
        sidebar,
        main_content,
        gr.update(value=textbox_val, visible=True),
        gr.update(visible=show_prev),
        gr.update(visible=show_next and not show_generate),
        gr.update(visible=show_generate),
        gr.update(visible=False),
    )


def render_final_prompt(answers: dict) -> str:
    setting = answers.get("setting", "[mysterious place]")
    character = answers.get("character", "[unlikely hero]")
    obj = answers.get("object", "[strange artifact]")
    action = answers.get("action", "[something impossible happens]")
    mood = answers.get("mood", "[indescribable feeling]")
    twist = answers.get("twist", "[revelation that changes everything]")
    style = answers.get("style", "[unique narrative voice]")

    return f"""# โœจ YOUR MAD LIBS AI PROMPT โœจ

---

## ๐Ÿ“œ The Prompt

Write a story **{style}** set in **{setting}**. 

The protagonist is **{character}**, who **{action}** after discovering **{obj}**. 

The tale should feel **{mood}**, and must end with the stunning revelation that **{twist}**.

---

## ๐ŸŽจ The Blanks You Filled

| Blank | Your Answer |
|-------|-------------|
| ๐ŸŒ Setting | {setting} |
| ๐Ÿง™โ€โ™‚๏ธ Character | {character} |
| ๐Ÿ”ฎ Object | {obj} |
| โšก Action | {action} |
| ๐ŸŽญ Mood | {mood} |
| ๐ŸŒ€ Twist | {twist} |
| โœ๏ธ Style | {style} |

---

## ๐Ÿš€ Ready to Use!

Copy the prompt above into your favorite AI (ChatGPT, Claude, Gemini, or an image generator like Midjourney/Stable Diffusion for visual storytelling) and watch your mad-libbed creation come to life!

*Want another spin? Hit **Start Over** and let the AI co-pilot suggest completely new wild ideas.*
"""


def handle_next(state_json, current_text):
    state_json = save_answer(state_json, current_text)
    state_json = next_step(state_json)
    return render_wizard(state_json)


def handle_prev(state_json, current_text):
    state_json = save_answer(state_json, current_text)
    state_json = prev_step(state_json)
    return render_wizard(state_json)


def handle_generate(state_json, current_text):
    state_json = save_answer(state_json, current_text)
    state = json.loads(state_json)
    state["step"] = len(WIZARD_STEPS)
    state_json = json.dumps(state)
    sidebar, main, tb, prev, nxt, gen, done = render_wizard(state_json)
    return sidebar, main, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True, value="๐Ÿ”„ Start Over")


def handle_start_over():
    return render_wizard(json.dumps(init_state()))


def handle_randomize_all():
    state = init_state()
    state["answers"] = {
        step["id"]: random.choice(CREATIVE_BANK.get(step["id"], ["something magical"]))
        for step in WIZARD_STEPS
    }
    state["step"] = len(WIZARD_STEPS)
    return render_wizard(json.dumps(state))


with gr.Blocks(
    title="๐ŸŽญ Mad Libs AI Prompt Generator",
    css="""
    .gradio-container {max-width: 1100px !important;}
    .suggestion-btn { margin: 4px 0; text-align: left !important; }
    .step-active { font-weight: bold; color: #6366f1; }
    .step-done { color: #22c55e; }
    .step-todo { color: #9ca3af; }
    """,
    theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="violet"),
) as demo:

    gr.Markdown("""
    # ๐ŸŽญ Mad Libs AI Prompt Generator
    ## *Your AI Co-Pilot for Wild, Weird, Wonderful Ideas*
    
    Fill in the blanks **bit by bit** like a classic Mad Libs game โ€” but with an AI assistant 
    whispering wildly creative suggestions at every step. Spark your imagination, then unleash 
    the final prompt on any AI (ChatGPT, Claude, Midjourney, Stable Diffusion, you name it)!
    """)

    state = gr.State(json.dumps(init_state()))

    with gr.Row():
        with gr.Column(scale=1, min_width=250):
            sidebar_md = gr.Markdown("## ๐Ÿ“‹ Your Story So Far\n\n*Start filling blanks to build your prompt!*")
            randomize_btn = gr.Button("๐ŸŽฒ I'm Feeling Lucky! (Randomize All)", variant="secondary", size="sm")
            gr.Markdown("---")
            gr.Markdown("๐Ÿ’ก **Pro tip:** Click any suggestion to instantly fill it in, or write your own wild idea!")

        with gr.Column(scale=3):
            main_md = gr.Markdown("### Click **Next** to begin your creative journey!")

            with gr.Row():
                with gr.Column(scale=3):
                    text_input = gr.Textbox(
                        label="โœ๏ธ Your Answer for This Blank",
                        placeholder="Type your own idea, or pick from suggestions below...",
                        lines=2,
                        show_copy_button=True,
                    )
                with gr.Column(scale=1):
                    gr.Markdown("### ๐ŸŽฐ Quick Pick")
                    sugg_btns = []
                    for i in range(6):
                        btn = gr.Button(f"Suggestion {i+1}", size="sm", variant="secondary")
                        sugg_btns.append(btn)

            with gr.Row():
                prev_btn = gr.Button("โฌ…๏ธ Previous", variant="secondary")
                next_btn = gr.Button("Next โžก๏ธ", variant="primary")
                generate_btn = gr.Button("โœจ Generate Final Prompt!", variant="primary", visible=False)
                restart_btn = gr.Button("๐Ÿ”„ Start Over", variant="secondary", visible=False)

    def _fill_suggestion(index: int):
        def fn(state_json):
            state = json.loads(state_json)
            step_idx = state["step"]
            if step_idx >= len(WIZARD_STEPS):
                return ""
            cat = WIZARD_STEPS[step_idx]["id"]
            suggestions = get_suggestions(cat, 6)
            if index < len(suggestions):
                return suggestions[index]
            return ""
        return fn

    for i, btn in enumerate(sugg_btns):
        btn.click(fn=_fill_suggestion(i), inputs=[state], outputs=[text_input])

    next_btn.click(
        fn=lambda s, t: handle_next(s, t),
        inputs=[state, text_input],
        outputs=[sidebar_md, main_md, text_input, prev_btn, next_btn, generate_btn, restart_btn],
    ).then(fn=lambda s: s, inputs=[state], outputs=[state])

    prev_btn.click(
        fn=lambda s, t: handle_prev(s, t),
        inputs=[state, text_input],
        outputs=[sidebar_md, main_md, text_input, prev_btn, next_btn, generate_btn, restart_btn],
    ).then(fn=lambda s: s, inputs=[state], outputs=[state])

    generate_btn.click(
        fn=lambda s, t: handle_generate(s, t),
        inputs=[state, text_input],
        outputs=[sidebar_md, main_md, text_input, prev_btn, next_btn, generate_btn, restart_btn],
    ).then(fn=lambda s: s, inputs=[state], outputs=[state])

    restart_btn.click(
        fn=handle_start_over,
        inputs=[],
        outputs=[sidebar_md, main_md, text_input, prev_btn, next_btn, generate_btn, restart_btn],
    ).then(fn=lambda: json.dumps(init_state()), inputs=[], outputs=[state])

    randomize_btn.click(
        fn=handle_randomize_all,
        inputs=[],
        outputs=[sidebar_md, main_md, text_input, prev_btn, next_btn, generate_btn, restart_btn],
    ).then(fn=lambda s: s, inputs=[state], outputs=[state])

    demo.load(
        fn=lambda s: render_wizard(s),
        inputs=[state],
        outputs=[sidebar_md, main_md, text_input, prev_btn, next_btn, generate_btn, restart_btn],
    )


if __name__ == "__main__":
    demo.launch()