Spaces:
Sleeping

byte-vortex commited on
Commit
207b44a
ยท
verified ยท
1 Parent(s): fcd98b7

Deploy Myco from CI

Browse files
Files changed (1) hide show
  1. ui/gradio_app.py +62 -48
ui/gradio_app.py CHANGED
@@ -8,7 +8,7 @@ import gradio as gr
8
  from game.engine import (
9
  collect_current, discover_mushroom, eat_current,
10
  follow_whisper, hf_companion_status, myco_reply,
11
- pick_current, study_current, check_auto_pickup,
12
  )
13
  from game.state import welcome_history
14
  from models.mushroom import Mushroom
@@ -26,6 +26,7 @@ EMPTY_COLLECTION = None
26
  START_POSITION = (1, 1)
27
 
28
  def force_parse_json_or_literal(s: str) -> Any:
 
29
  s = s.strip()
30
  if not (s.startswith("[") or s.startswith("{")):
31
  return s
@@ -45,8 +46,10 @@ def force_parse_json_or_literal(s: str) -> Any:
45
  return s
46
 
47
  def extract_clean_text(val: Any) -> str:
 
48
  if val is None:
49
  return ""
 
50
  if isinstance(val, str):
51
  val_stripped = val.strip()
52
  if (val_stripped.startswith("[") and val_stripped.endswith("]")) or (val_stripped.startswith("{") and val_stripped.endswith("}")):
@@ -55,12 +58,14 @@ def extract_clean_text(val: Any) -> str:
55
  return parsed
56
  return extract_clean_text(parsed)
57
  return val
 
58
  if isinstance(val, dict):
59
  if "text" in val:
60
  return extract_clean_text(val["text"])
61
  if "content" in val:
62
  return extract_clean_text(val["content"])
63
  return " ".join([extract_clean_text(v) for v in val.values() if v])
 
64
  if isinstance(val, list):
65
  segments = []
66
  for item in val:
@@ -68,23 +73,31 @@ def extract_clean_text(val: Any) -> str:
68
  if cleaned:
69
  segments.append(cleaned)
70
  return "\n".join(segments)
 
71
  return str(val)
72
 
73
  def _normalize_history(history):
 
74
  if not history:
75
  return []
 
76
  if isinstance(history, str):
77
  history = force_parse_json_or_literal(history)
 
78
  if not isinstance(history, (list, tuple)):
79
  history = [history]
 
80
  raw_normalized = []
81
  for item in history:
82
  if item is None:
83
  continue
 
84
  if isinstance(item, str):
85
  item = force_parse_json_or_literal(item)
 
86
  role = "assistant"
87
  content_val = item
 
88
  if isinstance(item, dict):
89
  role = item.get("role", "assistant")
90
  content_val = item.get("content", item.get("text", item))
@@ -95,6 +108,7 @@ def _normalize_history(history):
95
  if bot_side:
96
  raw_normalized.append({"role": "assistant", "content": extract_clean_text(bot_side)})
97
  continue
 
98
  clean_text = extract_clean_text(content_val)
99
  if clean_text:
100
  if isinstance(clean_text, str) and (clean_text.strip().startswith("[") or clean_text.strip().startswith("{")):
@@ -102,7 +116,10 @@ def _normalize_history(history):
102
  if isinstance(nested_parsed, (list, dict)):
103
  raw_normalized.extend(_normalize_history(nested_parsed))
104
  continue
 
105
  raw_normalized.append({"role": role, "content": clean_text})
 
 
106
  reconciled = []
107
  for msg in raw_normalized:
108
  role = msg["role"]
@@ -111,6 +128,7 @@ def _normalize_history(history):
111
  reconciled[-1]["content"] += f"\n{content}"
112
  else:
113
  reconciled.append({"role": role, "content": content})
 
114
  return reconciled
115
 
116
  def _denormalize_history(history):
@@ -149,6 +167,7 @@ def ask_companion(message, history, current, collection, position):
149
  legacy_hist = _denormalize_history(history)
150
  if legacy_hist and legacy_hist[-1]["role"] == "user":
151
  legacy_hist.append({"role": "assistant", "content": "..."})
 
152
  result = myco_reply(message, legacy_hist, current, collection, position)
153
  if isinstance(result, (tuple, list)) and len(result) == 2:
154
  return result[0], _normalize_history(result[1])
@@ -216,8 +235,7 @@ def study_discovery(current, history, collection, position):
216
  _normalize_history(updated_hist),
217
  )
218
 
219
-
220
- def move_player(position, direction, current, collection):
221
  x, y = _safe_pos(position)
222
  if direction == "north": y -= 1
223
  elif direction == "south": y += 1
@@ -225,25 +243,16 @@ def move_player(position, direction, current, collection):
225
  elif direction == "east": x += 1
226
  pos = _safe_pos((x, y))
227
 
 
228
  if isinstance(current, str):
229
  current = force_parse_json_or_literal(current)
230
-
231
- # --- NEW ARCADE MAGIC STARTS HERE ---
232
- # Check if Myco's new position overlaps with any active mushrooms!
233
- current, collection = check_auto_pickup(pos[0], pos[1], current, collection)
234
- # --- NEW ARCADE MAGIC ENDS HERE ---
235
-
236
- # Moving just updates position โ€” no LLM call, no discovery.
237
- # The player clicks Search Clearing when they want to find a mushroom.
238
-
239
- # We pass the UPDATED current and collection to all your UI renderers
240
  return (
241
- pos,
242
- forest_scene(current, collection, pos),
243
  game_status_markdown(current, collection, pos),
244
  mushroom_card_from_state(current),
245
  current,
246
- gr.update(),
247
  dex_markdown(collection),
248
  progress_markdown(collection),
249
  )
@@ -300,17 +309,19 @@ def build_app():
300
  with gr.Tabs(selected="home") as tabs:
301
  with gr.Tab("๐Ÿ  Home", id="home"):
302
  gr.HTML(home_forest_markdown())
 
303
  start_play_button = gr.Button(
304
  "๐ŸŒฒ Enter the Forest",
305
  variant="primary",
306
  size="lg",
307
  elem_classes=["forest-start-btn"]
308
  )
309
-
310
  with gr.Tab("๐ŸŽฎ Play", id="play"):
311
  gr.HTML(game_intro_markdown())
312
  scene = gr.HTML(forest_scene(None, EMPTY_COLLECTION, START_POSITION), elem_id="forest-scene")
313
 
 
314
  with gr.Row():
315
  with gr.Column(scale=1):
316
  search_button = gr.Button("๐ŸŽฎ Search Clearing", variant="primary", size="lg")
@@ -336,11 +347,11 @@ def build_app():
336
  gr.Markdown("### ๐Ÿ„ Current Discovery")
337
  discovery = gr.Markdown(mushroom_card(None))
338
  with gr.Row():
339
- study_button = gr.Button("๐Ÿ” Study", variant="secondary")
340
- collect_button = gr.Button("๐Ÿงบ Collect", variant="secondary")
341
  with gr.Row():
342
  whisper_button = gr.Button("๐ŸŒŒ Follow Whisper", variant="secondary")
343
- eat_button = gr.Button("๐Ÿฝ๏ธ Eat?", variant="stop")
344
 
345
  with gr.Column(scale=3):
346
  gr.Markdown("### ๐Ÿ’ฌ Chat with Myco")
@@ -354,54 +365,57 @@ def build_app():
354
  progress = gr.Markdown(progress_markdown(EMPTY_COLLECTION))
355
  dex = gr.Markdown(dex_markdown(EMPTY_COLLECTION))
356
  with gr.Group(elem_classes="myco-image-2"):
357
- gr.Image(value="assets/images/Myco-2.png", show_label=False, container=False, interactive=False)
358
-
 
 
 
 
 
359
  with gr.Tab("๐Ÿ—บ๏ธ Map"):
360
  world_map = gr.HTML(world_map_markdown(EMPTY_COLLECTION))
361
 
362
  with gr.Tab("๐Ÿงญ Guide"):
363
  gr.Markdown(GUIDE_MARKDOWN)
364
  with gr.Group(elem_classes="myco-image"):
365
- gr.Image(value="assets/images/Myco.png", show_label=False, container=False, interactive=False)
366
-
 
 
 
 
 
367
  with gr.Tab("๐Ÿ„ Myco"):
368
- render_shroom_tab()
 
369
 
370
  # โ”€โ”€ Event wiring โ”€โ”€
371
  start_play_button.click(open_play_tab, outputs=[tabs])
372
 
373
- search_button.click(search_forest, inputs=[player_position, collection],
374
  outputs=[scene, status, discovery, current_mushroom, chat, dex, progress], show_progress="hidden")
375
 
376
- ask_button.click(ask_companion, inputs=[prompt, chat, current_mushroom, collection, player_position],
377
  outputs=[prompt, chat], show_progress="hidden")
378
- prompt.submit(ask_companion, inputs=[prompt, chat, current_mushroom, collection, player_position],
379
  outputs=[prompt, chat], show_progress="hidden")
380
 
381
- # FIX: each button gets its own .click() with a hardcoded gr.State string
382
- # so the direction value is baked in at definition time, not captured from
383
- # a loop variable (which would make all four buttons pass "east").
384
- north_button.click(move_player, inputs=[player_position, gr.State("north"), current_mushroom, collection],
385
- outputs=[player_position, scene, status, discovery, current_mushroom, chat, dex, progress], show_progress="hidden")
386
- south_button.click(move_player, inputs=[player_position, gr.State("south"), current_mushroom, collection],
387
- outputs=[player_position, scene, status, discovery, current_mushroom, chat, dex, progress], show_progress="hidden")
388
- west_button.click(move_player, inputs=[player_position, gr.State("west"), current_mushroom, collection],
389
- outputs=[player_position, scene, status, discovery, current_mushroom, chat, dex, progress], show_progress="hidden")
390
- east_button.click(move_player, inputs=[player_position, gr.State("east"), current_mushroom, collection],
391
- outputs=[player_position, scene, status, discovery, current_mushroom, chat, dex, progress], show_progress="hidden")
392
-
393
- study_button.click(study_discovery, inputs=[current_mushroom, chat, collection, player_position],
394
- outputs=[current_mushroom, scene, status, discovery, chat], show_progress="hidden")
395
 
396
- collect_button.click(collect_discovery, inputs=[current_mushroom, collection, chat, player_position],
 
 
 
397
  outputs=[collection, scene, status, dex, world_map, chat, progress], show_progress="hidden")
398
-
399
- pick_button.click(pick_discovery, inputs=[current_mushroom, collection, chat, player_position],
400
  outputs=[collection, current_mushroom, scene, status, discovery, dex, world_map, chat, progress], show_progress="hidden")
401
-
402
- whisper_button.click(follow_story_whisper, inputs=[current_mushroom, collection, chat, player_position],
403
  outputs=[current_mushroom, scene, status, discovery, chat], show_progress="hidden")
404
-
405
  eat_button.click(block_unsafe_eating, inputs=[current_mushroom, chat], outputs=[chat], show_progress="hidden")
406
 
407
  demo.queue()
 
8
  from game.engine import (
9
  collect_current, discover_mushroom, eat_current,
10
  follow_whisper, hf_companion_status, myco_reply,
11
+ pick_current, study_current,
12
  )
13
  from game.state import welcome_history
14
  from models.mushroom import Mushroom
 
26
  START_POSITION = (1, 1)
27
 
28
  def force_parse_json_or_literal(s: str) -> Any:
29
+ """Safely converts stringified JSON data blocks into native Python objects."""
30
  s = s.strip()
31
  if not (s.startswith("[") or s.startswith("{")):
32
  return s
 
46
  return s
47
 
48
  def extract_clean_text(val: Any) -> str:
49
+ """Isolates and returns pure dialogue strings from data payloads."""
50
  if val is None:
51
  return ""
52
+
53
  if isinstance(val, str):
54
  val_stripped = val.strip()
55
  if (val_stripped.startswith("[") and val_stripped.endswith("]")) or (val_stripped.startswith("{") and val_stripped.endswith("}")):
 
58
  return parsed
59
  return extract_clean_text(parsed)
60
  return val
61
+
62
  if isinstance(val, dict):
63
  if "text" in val:
64
  return extract_clean_text(val["text"])
65
  if "content" in val:
66
  return extract_clean_text(val["content"])
67
  return " ".join([extract_clean_text(v) for v in val.values() if v])
68
+
69
  if isinstance(val, list):
70
  segments = []
71
  for item in val:
 
73
  if cleaned:
74
  segments.append(cleaned)
75
  return "\n".join(segments)
76
+
77
  return str(val)
78
 
79
  def _normalize_history(history):
80
+ """Sanitizes incoming message histories and forces strict alternation to satisfy Jinja constraints."""
81
  if not history:
82
  return []
83
+
84
  if isinstance(history, str):
85
  history = force_parse_json_or_literal(history)
86
+
87
  if not isinstance(history, (list, tuple)):
88
  history = [history]
89
+
90
  raw_normalized = []
91
  for item in history:
92
  if item is None:
93
  continue
94
+
95
  if isinstance(item, str):
96
  item = force_parse_json_or_literal(item)
97
+
98
  role = "assistant"
99
  content_val = item
100
+
101
  if isinstance(item, dict):
102
  role = item.get("role", "assistant")
103
  content_val = item.get("content", item.get("text", item))
 
108
  if bot_side:
109
  raw_normalized.append({"role": "assistant", "content": extract_clean_text(bot_side)})
110
  continue
111
+
112
  clean_text = extract_clean_text(content_val)
113
  if clean_text:
114
  if isinstance(clean_text, str) and (clean_text.strip().startswith("[") or clean_text.strip().startswith("{")):
 
116
  if isinstance(nested_parsed, (list, dict)):
117
  raw_normalized.extend(_normalize_history(nested_parsed))
118
  continue
119
+
120
  raw_normalized.append({"role": role, "content": clean_text})
121
+
122
+ # Collapse consecutive identical roles
123
  reconciled = []
124
  for msg in raw_normalized:
125
  role = msg["role"]
 
128
  reconciled[-1]["content"] += f"\n{content}"
129
  else:
130
  reconciled.append({"role": role, "content": content})
131
+
132
  return reconciled
133
 
134
  def _denormalize_history(history):
 
167
  legacy_hist = _denormalize_history(history)
168
  if legacy_hist and legacy_hist[-1]["role"] == "user":
169
  legacy_hist.append({"role": "assistant", "content": "..."})
170
+
171
  result = myco_reply(message, legacy_hist, current, collection, position)
172
  if isinstance(result, (tuple, list)) and len(result) == 2:
173
  return result[0], _normalize_history(result[1])
 
235
  _normalize_history(updated_hist),
236
  )
237
 
238
+ def move_player(position, direction, collection):
 
239
  x, y = _safe_pos(position)
240
  if direction == "north": y -= 1
241
  elif direction == "south": y += 1
 
243
  elif direction == "east": x += 1
244
  pos = _safe_pos((x, y))
245
 
246
+ mushroom, current, history = discover_mushroom(collection)
247
  if isinstance(current, str):
248
  current = force_parse_json_or_literal(current)
 
 
 
 
 
 
 
 
 
 
249
  return (
250
+ pos,
251
+ forest_scene(current, collection, pos),
252
  game_status_markdown(current, collection, pos),
253
  mushroom_card_from_state(current),
254
  current,
255
+ _normalize_history(history),
256
  dex_markdown(collection),
257
  progress_markdown(collection),
258
  )
 
309
  with gr.Tabs(selected="home") as tabs:
310
  with gr.Tab("๐Ÿ  Home", id="home"):
311
  gr.HTML(home_forest_markdown())
312
+
313
  start_play_button = gr.Button(
314
  "๐ŸŒฒ Enter the Forest",
315
  variant="primary",
316
  size="lg",
317
  elem_classes=["forest-start-btn"]
318
  )
319
+
320
  with gr.Tab("๐ŸŽฎ Play", id="play"):
321
  gr.HTML(game_intro_markdown())
322
  scene = gr.HTML(forest_scene(None, EMPTY_COLLECTION, START_POSITION), elem_id="forest-scene")
323
 
324
+ # Left Column: Search Clearing / Right Column: Arrow D-Pad
325
  with gr.Row():
326
  with gr.Column(scale=1):
327
  search_button = gr.Button("๐ŸŽฎ Search Clearing", variant="primary", size="lg")
 
347
  gr.Markdown("### ๐Ÿ„ Current Discovery")
348
  discovery = gr.Markdown(mushroom_card(None))
349
  with gr.Row():
350
+ study_button = gr.Button("๐Ÿ” Study", variant="secondary")
351
+ collect_button = gr.Button("๐Ÿงบ Collect", variant="secondary")
352
  with gr.Row():
353
  whisper_button = gr.Button("๐ŸŒŒ Follow Whisper", variant="secondary")
354
+ eat_button = gr.Button("๐Ÿฝ๏ธ Eat?", variant="stop")
355
 
356
  with gr.Column(scale=3):
357
  gr.Markdown("### ๐Ÿ’ฌ Chat with Myco")
 
365
  progress = gr.Markdown(progress_markdown(EMPTY_COLLECTION))
366
  dex = gr.Markdown(dex_markdown(EMPTY_COLLECTION))
367
  with gr.Group(elem_classes="myco-image-2"):
368
+ gr.Image(
369
+ value="assets/images/Myco-2.png",
370
+ show_label=False,
371
+ container=False,
372
+ interactive=False
373
+ )
374
+
375
  with gr.Tab("๐Ÿ—บ๏ธ Map"):
376
  world_map = gr.HTML(world_map_markdown(EMPTY_COLLECTION))
377
 
378
  with gr.Tab("๐Ÿงญ Guide"):
379
  gr.Markdown(GUIDE_MARKDOWN)
380
  with gr.Group(elem_classes="myco-image"):
381
+ gr.Image(
382
+ value="assets/images/Myco.png",
383
+ show_label=False,
384
+ container=False,
385
+ interactive=False
386
+ )
387
+
388
  with gr.Tab("๐Ÿ„ Myco"):
389
+ render_shroom_tab() # This now automatically renders both nested tabs cleanly!
390
+
391
 
392
  # โ”€โ”€ Event wiring โ”€โ”€
393
  start_play_button.click(open_play_tab, outputs=[tabs])
394
 
395
+ search_button.click(search_forest, inputs=[player_position, collection],
396
  outputs=[scene, status, discovery, current_mushroom, chat, dex, progress], show_progress="hidden")
397
 
398
+ ask_button.click(ask_companion, inputs=[prompt, chat, current_mushroom, collection, player_position],
399
  outputs=[prompt, chat], show_progress="hidden")
400
+ prompt.submit(ask_companion, inputs=[prompt, chat, current_mushroom, collection, player_position],
401
  outputs=[prompt, chat], show_progress="hidden")
402
 
403
+ for direction, button in [("north", north_button), ("south", south_button), ("west", west_button), ("east", east_button)]:
404
+ button.click(move_player, inputs=[player_position, gr.State(direction), collection],
405
+ outputs=[player_position, scene, status, discovery, current_mushroom, chat, dex, progress], show_progress="hidden")
 
 
 
 
 
 
 
 
 
 
 
406
 
407
+ study_button.click(study_discovery, inputs=[current_mushroom, chat, collection, player_position],
408
+ outputs=[current_mushroom, scene, status, discovery, chat], show_progress="hidden")
409
+
410
+ collect_button.click(collect_discovery, inputs=[current_mushroom, collection, chat, player_position],
411
  outputs=[collection, scene, status, dex, world_map, chat, progress], show_progress="hidden")
412
+
413
+ pick_button.click(pick_discovery, inputs=[current_mushroom, collection, chat, player_position],
414
  outputs=[collection, current_mushroom, scene, status, discovery, dex, world_map, chat, progress], show_progress="hidden")
415
+
416
+ whisper_button.click(follow_story_whisper, inputs=[current_mushroom, collection, chat, player_position],
417
  outputs=[current_mushroom, scene, status, discovery, chat], show_progress="hidden")
418
+
419
  eat_button.click(block_unsafe_eating, inputs=[current_mushroom, chat], outputs=[chat], show_progress="hidden")
420
 
421
  demo.queue()