Hermes Bot commited on
Commit
62071c9
·
unverified ·
1 Parent(s): 49bd205

feat: Anishinaabe Solarpunk Gradio UI with choice input, save/load, and CRT aesthetic

Browse files
Files changed (1) hide show
  1. projects/tinybard/app.py +576 -22
projects/tinybard/app.py CHANGED
@@ -258,23 +258,461 @@ def generate_llm_choices(genre: str, story_context: str) -> List[str]:
258
  # Gradio Blocks — API endpoints (exposed as MCP tools)
259
  # ---------------------------------------------------------------------------
260
  def create_gradio_app() -> gr.Blocks:
261
- """Build the Gradio Blocks app with API endpoints for MCP integration."""
262
 
263
- with gr.Blocks(title="TinyBard API") as blocks:
264
- # Hidden state — not rendered in UI, used by API
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  genre_input = gr.Textbox(label="Genre", value="fantasy", visible=False)
266
  step_input = gr.Number(label="Step", value=0, visible=False)
267
  health_input = gr.Number(label="Health", value=100, visible=False)
268
- choice_input = gr.Textbox(label="Choice", visible=False)
269
  history_input = gr.Textbox(label="History JSON", value="[]", visible=False)
270
 
271
- # Output fields
272
- story_output = gr.Textbox(label="Story")
273
- choices_output = gr.JSON(label="Choices")
274
- health_output = gr.Number(label="Health")
275
- step_output = gr.Number(label="Step")
276
- game_over_output = gr.Checkbox(label="Game Over")
277
- history_output = gr.Textbox(label="History JSON")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
 
279
  def api_start_game(genre: str):
280
  """Start a new interactive text adventure. Exposed as MCP tool."""
@@ -282,11 +720,9 @@ def create_gradio_app() -> gr.Blocks:
282
  if genre not in ["fantasy", "scifi", "cyberpunk"]:
283
  genre = "fantasy"
284
 
285
- # Try LLM first (will skip if cooldown is active)
286
  instruction = "Narrate the beginning of the adventure. What happens first? Do not offer choices yet."
287
  story = generate_llm_story(genre, [], instruction)
288
  if not story:
289
- # Procedural fallback
290
  result = generate_procedural_step(genre, 0, 100)
291
  return (
292
  result["story"], result["choices"], result["health"],
@@ -297,7 +733,6 @@ def create_gradio_app() -> gr.Blocks:
297
  history = [{"role": "narrator", "text": story}]
298
  choices = generate_llm_choices(genre, story)
299
  if len(choices) < 2:
300
- # Use the procedural choices
301
  fallback = generate_procedural_step(genre, 0, 100)
302
  choices = fallback["choices"]
303
 
@@ -314,7 +749,6 @@ def create_gradio_app() -> gr.Blocks:
314
  step = int(step or 0)
315
  health = int(health or 100)
316
 
317
- # First try LLM narration
318
  history.append({"role": "player", "text": choice})
319
 
320
  health_delta = random.choice([-15, 0, 10])
@@ -328,7 +762,6 @@ def create_gradio_app() -> gr.Blocks:
328
  [], 0, step + 1, True, json.dumps(history)
329
  )
330
 
331
- # No step cap — adventure continues infinitely until health reaches 0
332
  instruction = "Narrate what happens next as a result of the player's choice."
333
  story = generate_llm_story(genre, history, instruction)
334
  if not story:
@@ -347,19 +780,140 @@ def create_gradio_app() -> gr.Blocks:
347
 
348
  return (story, choices[:3], new_health, step + 1, False, json.dumps(history))
349
 
350
- # Register API endpoints
351
- gr.Button("Start Game").click(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
352
  fn=api_start_game,
353
  inputs=[genre_input],
354
  outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output],
355
- api_name="start_game"
 
 
 
 
 
 
 
356
  )
357
 
358
- gr.Button("Make Choice").click(
 
359
  fn=api_make_choice,
360
- inputs=[choice_input, genre_input, step_input, health_input, history_input],
361
  outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output],
362
- api_name="make_choice"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
  )
364
 
365
  return blocks
 
258
  # Gradio Blocks — API endpoints (exposed as MCP tools)
259
  # ---------------------------------------------------------------------------
260
  def create_gradio_app() -> gr.Blocks:
261
+ """Build the Gradio Blocks app with Anishinaabe Solarpunk CRT aesthetic.
262
 
263
+ API endpoints (start_game, make_choice) are preserved for MCP integration.
264
+ On HF Spaces, this Gradio UI IS the only interface.
265
+ """
266
+
267
+ # Anishinaabe Solarpunk CRT custom CSS
268
+ ASP_CSS = """
269
+ :root {
270
+ --asp-sky: #5BA4D9;
271
+ --asp-water: #1B4965;
272
+ --asp-frost: #CAF0F8;
273
+ --asp-sun: #F2A93B;
274
+ --asp-sunlight: #FFB347;
275
+ --asp-ember: #E76F51;
276
+ --asp-birch: #F5F1E8;
277
+ --asp-moss: #588157;
278
+ --asp-spruce: #1B4332;
279
+ --asp-night: #0F1A2C;
280
+ --asp-earth: #8B3A1F;
281
+ --asp-stone: #A89F91;
282
+ }
283
+
284
+ /* Page background */
285
+ .gradio-container, .app, body {
286
+ background:
287
+ radial-gradient(ellipse at top, #1B4965 0%, transparent 60%),
288
+ radial-gradient(ellipse at bottom right, #1B4332 0%, transparent 70%),
289
+ #0F1A2C !important;
290
+ color: #F5F1E8 !important;
291
+ font-family: Georgia, 'Iowan Old Style', serif !important;
292
+ }
293
+
294
+ /* CRT scanline overlay */
295
+ .gradio-container::after {
296
+ content: "";
297
+ position: fixed;
298
+ top: 0; left: 0; right: 0; bottom: 0;
299
+ background: repeating-linear-gradient(
300
+ 0deg,
301
+ transparent,
302
+ transparent 2px,
303
+ rgba(91, 164, 217, 0.04) 2px,
304
+ rgba(91, 164, 217, 0.04) 4px
305
+ );
306
+ pointer-events: none;
307
+ z-index: 9999;
308
+ }
309
+
310
+ /* Banner */
311
+ .asp-banner {
312
+ background: linear-gradient(95deg, #5BA4D9 0%, #1B4965 100%);
313
+ color: #F5F1E8;
314
+ border: 1px solid rgba(255, 179, 71, 0.3);
315
+ border-radius: 10px;
316
+ padding: 14px 20px;
317
+ margin-bottom: 16px;
318
+ font-family: Georgia, serif;
319
+ text-align: center;
320
+ text-shadow: 0 1px 2px rgba(15, 26, 44, 0.45);
321
+ box-shadow: 0 4px 24px rgba(0, 0, 0, 0.4);
322
+ letter-spacing: 0.5px;
323
+ }
324
+ .asp-banner .syll { font-size: 1.6em; opacity: 0.9; }
325
+ .asp-banner .glyph { color: #FFB347; font-size: 1.15em; }
326
+ .asp-banner .title {
327
+ font-size: 1.1em; font-weight: 700;
328
+ letter-spacing: 2px; text-transform: uppercase;
329
+ }
330
+ .asp-banner .subtitle {
331
+ color: #CAF0F8; font-size: 0.85em;
332
+ font-style: italic; opacity: 0.85;
333
+ }
334
+
335
+ /* Section containers */
336
+ .asp-section {
337
+ background: linear-gradient(160deg, rgba(139, 58, 31, 0.25) 0%, rgba(15, 26, 44, 0.6) 100%);
338
+ border: 1px solid rgba(91, 164, 217, 0.2);
339
+ border-radius: 10px;
340
+ padding: 16px 20px;
341
+ margin-bottom: 12px;
342
+ box-shadow:
343
+ inset 0 0 40px rgba(0, 0, 0, 0.3),
344
+ 0 8px 32px rgba(0, 0, 0, 0.4);
345
+ }
346
+ .asp-section::before {
347
+ content: "\\25C8";
348
+ display: block;
349
+ color: #F2A93B;
350
+ font-size: 0.7rem;
351
+ letter-spacing: 6px;
352
+ margin-bottom: 6px;
353
+ opacity: 0.5;
354
+ text-align: center;
355
+ }
356
+
357
+ /* Section labels */
358
+ .asp-label {
359
+ color: #CAF0F8 !important;
360
+ font-family: Georgia, serif !important;
361
+ font-size: 0.72rem !important;
362
+ text-transform: uppercase !important;
363
+ letter-spacing: 2px !important;
364
+ margin-bottom: 8px !important;
365
+ text-shadow: 0 0 6px rgba(91, 164, 217, 0.3);
366
+ }
367
+
368
+ /* Genre radio buttons */
369
+ .asp-genre label {
370
+ background: rgba(15, 26, 44, 0.4) !important;
371
+ border: 1px solid rgba(91, 164, 217, 0.3) !important;
372
+ border-radius: 4px !important;
373
+ color: #CAF0F8 !important;
374
+ padding: 10px 18px !important;
375
+ font-family: Georgia, serif !important;
376
+ font-size: 0.82rem !important;
377
+ letter-spacing: 1.5px !important;
378
+ text-transform: uppercase !important;
379
+ cursor: pointer !important;
380
+ transition: all 0.2s !important;
381
+ }
382
+ .asp-genre label:hover {
383
+ background: rgba(242, 169, 59, 0.15) !important;
384
+ border-color: #F2A93B !important;
385
+ color: #FFB347 !important;
386
+ text-shadow: 0 0 12px rgba(242, 169, 59, 0.5);
387
+ }
388
+ .asp-genre input[type="radio"]:checked + span {
389
+ color: #FFB347 !important;
390
+ text-shadow: 0 0 8px rgba(242, 169, 59, 0.5);
391
+ }
392
+
393
+ /* Choice radio buttons */
394
+ .asp-choices label {
395
+ display: block !important;
396
+ background: rgba(15, 26, 44, 0.3) !important;
397
+ border: 1px solid rgba(91, 164, 217, 0.25) !important;
398
+ border-radius: 3px !important;
399
+ color: #CAF0F8 !important;
400
+ padding: 10px 16px !important;
401
+ margin-bottom: 4px !important;
402
+ font-family: 'JetBrains Mono', 'Fira Code', 'SF Mono', Menlo, monospace !important;
403
+ font-size: 0.82rem !important;
404
+ cursor: pointer !important;
405
+ transition: all 0.15s !important;
406
+ text-shadow: 0 0 3px rgba(91, 164, 217, 0.2);
407
+ }
408
+ .asp-choices label:hover {
409
+ background: rgba(91, 164, 217, 0.1) !important;
410
+ border-color: #F2A93B !important;
411
+ color: #FFB347 !important;
412
+ padding-left: 26px !important;
413
+ box-shadow: 0 0 12px rgba(242, 169, 59, 0.15);
414
+ }
415
+
416
+ /* Buttons */
417
+ .asp-btn {
418
+ background: linear-gradient(95deg, rgba(139, 58, 31, 0.4) 0%, rgba(27, 67, 50, 0.4) 100%) !important;
419
+ border: 1px solid rgba(91, 164, 217, 0.35) !important;
420
+ border-radius: 4px !important;
421
+ color: #CAF0F8 !important;
422
+ font-family: Georgia, serif !important;
423
+ font-size: 0.82rem !important;
424
+ letter-spacing: 1.5px !important;
425
+ text-transform: uppercase !important;
426
+ padding: 10px 22px !important;
427
+ cursor: pointer !important;
428
+ transition: all 0.2s !important;
429
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
430
+ }
431
+ .asp-btn:hover {
432
+ background: linear-gradient(95deg, rgba(242, 169, 59, 0.25) 0%, rgba(91, 164, 217, 0.25) 100%) !important;
433
+ border-color: #F2A93B !important;
434
+ color: #FFB347 !important;
435
+ box-shadow: 0 0 18px rgba(242, 169, 59, 0.3);
436
+ text-shadow: 0 0 8px rgba(242, 169, 59, 0.4);
437
+ }
438
+ .asp-btn-primary {
439
+ background: linear-gradient(95deg, #8B3A1F 0%, #1B4332 100%) !important;
440
+ border-color: rgba(242, 169, 59, 0.5) !important;
441
+ box-shadow: 0 0 16px rgba(242, 169, 59, 0.15);
442
+ }
443
+ .asp-btn-primary:hover {
444
+ box-shadow: 0 0 24px rgba(242, 169, 59, 0.4) !important;
445
+ }
446
+
447
+ /* Story output */
448
+ .asp-story textarea {
449
+ background: rgba(15, 26, 44, 0.5) !important;
450
+ border: none !important;
451
+ border-left: 3px solid #F2A93B !important;
452
+ border-radius: 0 6px 6px 0 !important;
453
+ color: #F5F1E8 !important;
454
+ font-family: Georgia, 'Iowan Old Style', serif !important;
455
+ font-size: 0.92rem !important;
456
+ line-height: 1.7 !important;
457
+ padding: 14px 18px !important;
458
+ text-shadow: 0 0 6px rgba(242, 169, 59, 0.12);
459
+ box-shadow: inset 0 0 30px rgba(15, 26, 44, 0.4);
460
+ animation: fadeSlideIn 0.5s ease-out;
461
+ }
462
+
463
+ /* Textbox inputs */
464
+ .asp-input textarea, .asp-input input {
465
+ background: rgba(15, 26, 44, 0.5) !important;
466
+ border: 1px solid rgba(91, 164, 217, 0.3) !important;
467
+ border-radius: 4px !important;
468
+ color: #F5F1E8 !important;
469
+ font-family: 'JetBrains Mono', 'Fira Code', 'SF Mono', Menlo, monospace !important;
470
+ font-size: 0.88rem !important;
471
+ caret-color: #F2A93B !important;
472
+ }
473
+ .asp-input textarea:focus, .asp-input input:focus {
474
+ border-color: #F2A93B !important;
475
+ box-shadow: 0 0 12px rgba(242, 169, 59, 0.2);
476
+ outline: none !important;
477
+ }
478
+
479
+ /* Status row */
480
+ .asp-status {
481
+ background: rgba(15, 26, 44, 0.4) !important;
482
+ border: 1px solid rgba(91, 164, 217, 0.15) !important;
483
+ border-radius: 6px !important;
484
+ padding: 10px 16px !important;
485
+ }
486
+ .asp-status label {
487
+ color: #CAF0F8 !important;
488
+ font-family: Georgia, serif !important;
489
+ font-size: 0.7rem !important;
490
+ text-transform: uppercase !important;
491
+ letter-spacing: 1.5px !important;
492
+ }
493
+
494
+ /* Footer */
495
+ .asp-footer {
496
+ text-align: center;
497
+ padding: 10px 0 4px;
498
+ border-top: 1px solid rgba(91, 164, 217, 0.15);
499
+ margin-top: 8px;
500
+ font-size: 0.65rem;
501
+ color: #A89F91;
502
+ letter-spacing: 1.5px;
503
+ font-family: Georgia, serif;
504
+ }
505
+
506
+ @keyframes fadeSlideIn {
507
+ from { opacity: 0; transform: translateX(-10px); }
508
+ to { opacity: 1; transform: translateX(0); }
509
+ }
510
+
511
+ label, .wrap > label {
512
+ color: #CAF0F8 !important;
513
+ font-family: Georgia, serif !important;
514
+ }
515
+
516
+ ::-webkit-scrollbar { width: 6px; }
517
+ ::-webkit-scrollbar-track { background: transparent; }
518
+ ::-webkit-scrollbar-thumb {
519
+ background: rgba(91, 164, 217, 0.25);
520
+ border-radius: 3px;
521
+ }
522
+
523
+ @media (max-width: 600px) {
524
+ .asp-banner { padding: 10px 14px; font-size: 0.85em; }
525
+ .asp-section { padding: 12px; }
526
+ }
527
+ """
528
+
529
+ with gr.Blocks(title="TinyBard") as blocks:
530
+
531
+ blocks.theme = gr.themes.Base(
532
+ primary_hue="amber",
533
+ neutral_hue="slate",
534
+ ).set(
535
+ body_background_fill="#0F1A2C",
536
+ body_text_color="#F5F1E8",
537
+ block_background_fill="rgba(15, 26, 44, 0.3)",
538
+ block_border_color="rgba(91, 164, 217, 0.2)",
539
+ block_label_text_color="#CAF0F8",
540
+ input_background_fill="rgba(15, 26, 44, 0.5)",
541
+ input_border_color="rgba(91, 164, 217, 0.3)",
542
+ button_primary_background_fill="linear-gradient(95deg, #8B3A1F, #1B4332)",
543
+ button_primary_border_color="rgba(242, 169, 59, 0.5)",
544
+ button_primary_text_color="#CAF0F8",
545
+ button_secondary_background_fill="rgba(139, 58, 31, 0.3)",
546
+ button_secondary_border_color="rgba(91, 164, 217, 0.35)",
547
+ button_secondary_text_color="#CAF0F8",
548
+ )
549
+
550
+ # Inject CSS via HTML since Gradio 6.0 has no css= param on Blocks
551
+ gr.HTML(f"<style>{ASP_CSS}</style>")
552
+
553
+ # Banner
554
+ gr.HTML(
555
+ '<div class="asp-banner">'
556
+ '<span class="syll">\u1434</span> '
557
+ '<span class="glyph">\u263C</span> '
558
+ '<span class="title">TINYBARD</span> '
559
+ '<span class="glyph">\u2618</span> '
560
+ '<span class="subtitle">\u2014 a fire-fly storyteller in cedar and copper \u2014</span> '
561
+ '<span class="syll">\u1514</span>'
562
+ '</div>'
563
+ )
564
+
565
+ # Hidden state fields (for internal tracking + MCP API)
566
  genre_input = gr.Textbox(label="Genre", value="fantasy", visible=False)
567
  step_input = gr.Number(label="Step", value=0, visible=False)
568
  health_input = gr.Number(label="Health", value=100, visible=False)
 
569
  history_input = gr.Textbox(label="History JSON", value="[]", visible=False)
570
 
571
+ # Genre selector
572
+ with gr.Group(elem_classes=["asp-section"]):
573
+ gr.HTML('<div class="asp-label">\u1434 INAABANDA\u0027IWIN / SELECT GENRE \u1514</div>')
574
+ genre_radio = gr.Radio(
575
+ choices=[
576
+ ("\u263C Aadizookaan / Fantasy", "fantasy"),
577
+ ("\u25C8 Ishpiming / Sci-Fi", "scifi"),
578
+ ("\u25C6 Mashkodewaazibi / Cyberpunk", "cyberpunk"),
579
+ ],
580
+ value="fantasy",
581
+ label=None,
582
+ show_label=False,
583
+ elem_classes=["asp-genre"],
584
+ )
585
+
586
+ # Story output
587
+ with gr.Group(elem_classes=["asp-section"]):
588
+ gr.HTML('<div class="asp-label">\u1434 AADIZOOKAAN / STORY \u1514</div>')
589
+ story_output = gr.Textbox(
590
+ label="Story",
591
+ show_label=False,
592
+ lines=8,
593
+ max_lines=20,
594
+ interactive=False,
595
+ elem_classes=["asp-story"],
596
+ )
597
+
598
+ # Choices radio (populated after game start)
599
+ with gr.Group(elem_classes=["asp-section"]):
600
+ gr.HTML('<div class="asp-label">\u1434 INAABANDA\u0027IWIN / CHOOSE \u1514</div>')
601
+ choice_radio = gr.Radio(
602
+ choices=[],
603
+ label=None,
604
+ show_label=False,
605
+ interactive=True,
606
+ elem_classes=["asp-choices"],
607
+ )
608
+
609
+ # Choice text input (fallback / custom choice)
610
+ with gr.Group(elem_classes=["asp-section"]):
611
+ gr.HTML('<div class="asp-label">\u1434 NINDANOKIMAA / TYPE YOUR ACTION \u1514</div>')
612
+ choice_text_input = gr.Textbox(
613
+ label="Type your choice",
614
+ show_label=False,
615
+ placeholder="Type your action or select above...",
616
+ lines=1,
617
+ max_lines=3,
618
+ elem_classes=["asp-input"],
619
+ )
620
+
621
+ # Action buttons
622
+ with gr.Row():
623
+ start_btn = gr.Button(
624
+ "\u263C START GAME",
625
+ variant="primary",
626
+ elem_classes=["asp-btn", "asp-btn-primary"],
627
+ scale=2,
628
+ )
629
+ choice_btn = gr.Button(
630
+ "\u25C8 MAKE CHOICE",
631
+ variant="secondary",
632
+ elem_classes=["asp-btn"],
633
+ scale=2,
634
+ )
635
+ save_btn = gr.Button(
636
+ "\u25C6 SAVE",
637
+ variant="secondary",
638
+ elem_classes=["asp-btn"],
639
+ scale=1,
640
+ )
641
+ load_btn = gr.Button(
642
+ "\u2618 LOAD",
643
+ variant="secondary",
644
+ elem_classes=["asp-btn"],
645
+ scale=1,
646
+ )
647
+
648
+ # Save slot input
649
+ with gr.Group(elem_classes=["asp-section"]):
650
+ gr.HTML('<div class="asp-label">\u1434 OZHIIMAAGAN / SAVE SLOT \u1514</div>')
651
+ save_slot_input = gr.Textbox(
652
+ label="Slot Name",
653
+ show_label=False,
654
+ placeholder="my-adventure",
655
+ lines=1,
656
+ elem_classes=["asp-input"],
657
+ )
658
+ save_status = gr.Textbox(
659
+ label="Save Status",
660
+ show_label=False,
661
+ interactive=False,
662
+ lines=1,
663
+ elem_classes=["asp-input"],
664
+ )
665
+
666
+ # Status bar
667
+ with gr.Row(elem_classes=["asp-status"]):
668
+ health_output = gr.Number(label="NOOSISKAAZOWIN / Health", value=100, interactive=False)
669
+ step_output = gr.Number(label="DIBIK / Step", value=0, interactive=False)
670
+ game_over_output = gr.Checkbox(label="GIIZHIG / Game Over", value=False, interactive=False)
671
+
672
+ # Choices JSON (hidden for MCP/debug)
673
+ choices_output = gr.JSON(label="Choices JSON", visible=False, elem_classes=["asp-json"])
674
+ history_output = gr.Textbox(label="History JSON", visible=False)
675
+
676
+ # Footer
677
+ gr.HTML(
678
+ '<div class="asp-footer">'
679
+ '\u1434 TinyBard \u00b7 FastAPI + Gradio + MCP \u00b7 Anishinaabe Solarpunk \u1514'
680
+ '</div>'
681
+ )
682
+
683
+ # ================================================================
684
+ # Event Handlers
685
+ # ================================================================
686
+
687
+ # Sync genre radio to hidden genre_input
688
+ def sync_genre(genre_val):
689
+ return genre_val or "fantasy"
690
+
691
+ genre_radio.change(
692
+ fn=sync_genre,
693
+ inputs=[genre_radio],
694
+ outputs=[genre_input],
695
+ )
696
+
697
+ # Sync choice radio selection to text input
698
+ def sync_choice_to_text(radio_val, current_text):
699
+ if radio_val:
700
+ return radio_val
701
+ return current_text
702
+
703
+ choice_radio.change(
704
+ fn=sync_choice_to_text,
705
+ inputs=[choice_radio, choice_text_input],
706
+ outputs=[choice_text_input],
707
+ )
708
+
709
+ # Update choice radio from choices JSON
710
+ def update_choices_radio(choices_json):
711
+ if not choices_json:
712
+ return gr.update(choices=[], value=None)
713
+ if isinstance(choices_json, list):
714
+ return gr.update(choices=choices_json, value=None)
715
+ return gr.update(choices=[], value=None)
716
 
717
  def api_start_game(genre: str):
718
  """Start a new interactive text adventure. Exposed as MCP tool."""
 
720
  if genre not in ["fantasy", "scifi", "cyberpunk"]:
721
  genre = "fantasy"
722
 
 
723
  instruction = "Narrate the beginning of the adventure. What happens first? Do not offer choices yet."
724
  story = generate_llm_story(genre, [], instruction)
725
  if not story:
 
726
  result = generate_procedural_step(genre, 0, 100)
727
  return (
728
  result["story"], result["choices"], result["health"],
 
733
  history = [{"role": "narrator", "text": story}]
734
  choices = generate_llm_choices(genre, story)
735
  if len(choices) < 2:
 
736
  fallback = generate_procedural_step(genre, 0, 100)
737
  choices = fallback["choices"]
738
 
 
749
  step = int(step or 0)
750
  health = int(health or 100)
751
 
 
752
  history.append({"role": "player", "text": choice})
753
 
754
  health_delta = random.choice([-15, 0, 10])
 
762
  [], 0, step + 1, True, json.dumps(history)
763
  )
764
 
 
765
  instruction = "Narrate what happens next as a result of the player's choice."
766
  story = generate_llm_story(genre, history, instruction)
767
  if not story:
 
780
 
781
  return (story, choices[:3], new_health, step + 1, False, json.dumps(history))
782
 
783
+ # Helper: resolve choice from radio or text input
784
+ def resolve_choice(choice_text, choice_radio_val):
785
+ """Use text input if filled, otherwise use radio selection."""
786
+ if choice_text and choice_text.strip():
787
+ return choice_text.strip()
788
+ if choice_radio_val:
789
+ return choice_radio_val
790
+ return ""
791
+
792
+ # Make Choice: resolve choice, then call api_make_choice
793
+ def handle_make_choice(choice_text, choice_radio_val, genre, step, health, history_json):
794
+ resolved = resolve_choice(choice_text, choice_radio_val)
795
+ if not resolved:
796
+ return (
797
+ "Please type or select a choice before making your move.",
798
+ gr.update(), 100, 0, False, "[]",
799
+ "", gr.update()
800
+ )
801
+ story, choices, h, s, go, hist = api_make_choice(resolved, genre, step, health, history_json)
802
+ return story, choices, h, s, go, hist, "", gr.update(choices=choices or [], value=None)
803
+
804
+ # Start Game: call api_start_game, clear choice input, update radio
805
+ def handle_start_game(genre):
806
+ story, choices, h, s, go, hist = api_start_game(genre)
807
+ return story, choices, h, s, go, hist, "", gr.update(choices=choices or [], value=None)
808
+
809
+ # API endpoints (preserved for MCP)
810
+ start_btn.click(
811
  fn=api_start_game,
812
  inputs=[genre_input],
813
  outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output],
814
+ api_name="start_game",
815
+ )
816
+
817
+ # UI start game button: also updates choices radio and clears text
818
+ start_btn.click(
819
+ fn=handle_start_game,
820
+ inputs=[genre_input],
821
+ outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output, choice_text_input, choice_radio],
822
  )
823
 
824
+ # API make_choice endpoint (preserved for MCP)
825
+ choice_btn.click(
826
  fn=api_make_choice,
827
+ inputs=[choice_text_input, genre_input, step_input, health_input, history_input],
828
  outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output],
829
+ api_name="make_choice",
830
+ )
831
+
832
+ # UI make choice button: resolves radio/text, updates choices radio
833
+ choice_btn.click(
834
+ fn=handle_make_choice,
835
+ inputs=[choice_text_input, choice_radio, genre_input, step_input, health_input, history_input],
836
+ outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output, choice_text_input, choice_radio],
837
+ )
838
+
839
+ # Save game handler
840
+ def handle_save(slot_name, genre, step, health, history_json, game_over):
841
+ import urllib.request
842
+ import urllib.error
843
+ if not slot_name or not slot_name.strip():
844
+ return "Please enter a save slot name."
845
+ try:
846
+ history = json.loads(history_json) if history_json else []
847
+ except Exception:
848
+ history = []
849
+ payload = json.dumps({
850
+ "slot_name": slot_name.strip(),
851
+ "genre": genre or "fantasy",
852
+ "step": int(step or 0),
853
+ "health": int(health or 100),
854
+ "history": history,
855
+ "game_over": bool(game_over),
856
+ }).encode()
857
+ try:
858
+ req = urllib.request.Request(
859
+ "/api/game/save",
860
+ data=payload,
861
+ headers={"Content-Type": "application/json"},
862
+ method="POST",
863
+ )
864
+ with urllib.request.urlopen(req) as resp:
865
+ result = json.loads(resp.read())
866
+ return f"Saved to '{result.get('slot_name', slot_name)}'"
867
+ except Exception as e:
868
+ return f"Save failed: {e}"
869
+
870
+ save_btn.click(
871
+ fn=handle_save,
872
+ inputs=[save_slot_input, genre_input, step_input, health_input, history_input, game_over_output],
873
+ outputs=[save_status],
874
+ )
875
+
876
+ # Load game handler
877
+ def handle_load(slot_name):
878
+ import urllib.request
879
+ if not slot_name or not slot_name.strip():
880
+ return "Enter a slot name to load.", gr.update(), 100, 0, False, "[]", ""
881
+ try:
882
+ payload = json.dumps({"slot_name": slot_name.strip()}).encode()
883
+ req = urllib.request.Request(
884
+ "/api/game/load",
885
+ data=payload,
886
+ headers={"Content-Type": "application/json"},
887
+ method="POST",
888
+ )
889
+ with urllib.request.urlopen(req) as resp:
890
+ result = json.loads(resp.read())
891
+ if result.get("status") != "ok":
892
+ return f"Load failed: {result.get('message', 'Unknown error')}", gr.update(), 100, 0, False, "[]", ""
893
+ choices = result.get("choices", [])
894
+ history = result.get("history", [])
895
+ story = ""
896
+ if history:
897
+ for h in reversed(history):
898
+ if h.get("role") == "narrator":
899
+ story = h.get("text", "")
900
+ break
901
+ return (
902
+ story or "Game loaded.",
903
+ gr.update(choices=choices, value=None),
904
+ result.get("health", 100),
905
+ result.get("step", 0),
906
+ result.get("game_over", False),
907
+ json.dumps(history),
908
+ f"Loaded '{result.get('slot_name', slot_name)}'",
909
+ )
910
+ except Exception as e:
911
+ return f"Load failed: {e}", gr.update(), 100, 0, False, "[]", ""
912
+
913
+ load_btn.click(
914
+ fn=handle_load,
915
+ inputs=[save_slot_input],
916
+ outputs=[story_output, choice_radio, health_output, step_output, game_over_output, history_input, save_status],
917
  )
918
 
919
  return blocks