Spaces:
Sleeping

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

Deploy Myco from CI

Browse files
Files changed (1) hide show
  1. ui/old--gradio_app.py +409 -0
ui/old--gradio_app.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gradio game UI for Myco โ€” LLM-powered forest adventure."""
2
+
3
+ import ast
4
+ import json
5
+ from typing import Any, cast
6
+ import gradio as gr
7
+
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
15
+
16
+ from ui.renderers import (
17
+ dex_markdown, forest_scene, game_intro_markdown,
18
+ game_status_markdown, hero_markdown, home_forest_markdown,
19
+ mushroom_card, play_hook_markdown, progress_markdown,
20
+ world_map_markdown,
21
+ )
22
+
23
+ from ui.interface import render_shroom_tab
24
+
25
+ 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
32
+ try:
33
+ return json.loads(s)
34
+ except Exception:
35
+ pass
36
+ try:
37
+ return ast.literal_eval(s)
38
+ except Exception:
39
+ pass
40
+ try:
41
+ s_json = s.replace("None", "null").replace("True", "true").replace("False", "false")
42
+ return json.loads(s_json)
43
+ except Exception:
44
+ pass
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("}")):
53
+ parsed = force_parse_json_or_literal(val_stripped)
54
+ if isinstance(parsed, 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:
67
+ cleaned = extract_clean_text(item)
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))
91
+ elif isinstance(item, (list, tuple)) and len(item) == 2:
92
+ user_side, bot_side = item
93
+ if user_side:
94
+ raw_normalized.append({"role": "user", "content": extract_clean_text(user_side)})
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("{")):
101
+ nested_parsed = force_parse_json_or_literal(clean_text)
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"]
109
+ content = msg["content"]
110
+ if reconciled and reconciled[-1]["role"] == role:
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):
117
+ return _normalize_history(history)
118
+
119
+ def mushroom_card_from_state(current):
120
+ if current is None:
121
+ return mushroom_card(None)
122
+ if isinstance(current, str):
123
+ current = force_parse_json_or_literal(current)
124
+ if isinstance(current, str):
125
+ return mushroom_card(None)
126
+ return mushroom_card(
127
+ Mushroom.from_dict(current),
128
+ current.get("clue"),
129
+ current.get("secret"),
130
+ current,
131
+ )
132
+
133
+ def search_forest(position, collection):
134
+ pos = _safe_pos(position)
135
+ mushroom, current, history = discover_mushroom(collection)
136
+ if isinstance(current, str):
137
+ current = force_parse_json_or_literal(current)
138
+ return (
139
+ forest_scene(current, collection, pos),
140
+ game_status_markdown(current, collection, pos),
141
+ mushroom_card_from_state(current),
142
+ current,
143
+ _normalize_history(history),
144
+ dex_markdown(collection),
145
+ progress_markdown(collection),
146
+ )
147
+
148
+ 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])
155
+ return "", _normalize_history(result)
156
+
157
+ def collect_discovery(current, collection, history, position):
158
+ legacy_hist = _denormalize_history(history)
159
+ updated_coll, updated_hist = collect_current(current, collection, legacy_hist)
160
+ pos = _safe_pos(position)
161
+ if isinstance(current, str):
162
+ current = force_parse_json_or_literal(current)
163
+ return (
164
+ updated_coll,
165
+ forest_scene(current, updated_coll, pos),
166
+ game_status_markdown(current, updated_coll, pos),
167
+ dex_markdown(updated_coll),
168
+ world_map_markdown(updated_coll),
169
+ _normalize_history(updated_hist),
170
+ progress_markdown(updated_coll),
171
+ )
172
+
173
+ def pick_discovery(current, collection, history, position):
174
+ legacy_hist = _denormalize_history(history)
175
+ updated_coll, updated_current, updated_hist = pick_current(current, collection, legacy_hist)
176
+ if isinstance(updated_current, str):
177
+ updated_current = force_parse_json_or_literal(updated_current)
178
+ pos = _safe_pos(position)
179
+ return (
180
+ updated_coll,
181
+ updated_current,
182
+ forest_scene(updated_current, updated_coll, pos),
183
+ game_status_markdown(updated_current, updated_coll, pos),
184
+ mushroom_card_from_state(updated_current),
185
+ dex_markdown(updated_coll),
186
+ world_map_markdown(updated_coll),
187
+ _normalize_history(updated_hist),
188
+ progress_markdown(updated_coll),
189
+ )
190
+
191
+ def follow_story_whisper(current, collection, history, position):
192
+ legacy_hist = _denormalize_history(history)
193
+ updated_current, updated_hist = follow_whisper(current, collection, legacy_hist)
194
+ if isinstance(updated_current, str):
195
+ updated_current = force_parse_json_or_literal(updated_current)
196
+ pos = _safe_pos(position)
197
+ return (
198
+ updated_current,
199
+ forest_scene(updated_current, collection, pos),
200
+ game_status_markdown(updated_current, collection, pos),
201
+ mushroom_card_from_state(updated_current),
202
+ _normalize_history(updated_hist),
203
+ )
204
+
205
+ def study_discovery(current, history, collection, position):
206
+ legacy_hist = _denormalize_history(history)
207
+ updated_current, updated_hist = study_current(current, legacy_hist)
208
+ if isinstance(updated_current, str):
209
+ updated_current = force_parse_json_or_literal(updated_current)
210
+ pos = _safe_pos(position)
211
+ return (
212
+ updated_current,
213
+ forest_scene(updated_current, collection, pos),
214
+ game_status_markdown(updated_current, collection, pos),
215
+ mushroom_card_from_state(updated_current),
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
224
+ elif direction == "west": x -= 1
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
+ )
250
+
251
+ def block_unsafe_eating(current, history):
252
+ legacy_hist = _denormalize_history(history)
253
+ updated_hist = eat_current(current, legacy_hist)
254
+ return _normalize_history(updated_hist)
255
+
256
+ def open_play_tab():
257
+ return gr.update(selected="play")
258
+
259
+ def _safe_pos(position):
260
+ if position is None:
261
+ return START_POSITION
262
+ x, y = position
263
+ return (max(0, min(2, int(x))), max(0, min(2, int(y))))
264
+
265
+ GUIDE_MARKDOWN = """
266
+ ## How to play
267
+
268
+ 1. Go to **๐ŸŽฎ Play** and click **๐ŸŽฎ Search Clearing** to discover a mushroom.
269
+ 2. **Myco (the AI) reacts** โ€” read what it senses about the mushroom.
270
+ 3. Choose your action:
271
+ - **๐Ÿ” Study** โ€” Myco examines the mushroom and updates its magic field.
272
+ - **๐Ÿ„ Pick** โ€” grab it as a game item. Poisonous picks = Game Over!
273
+ - **๐Ÿ“– Collect** โ€” add it to the MycoDex for safe keeping and score.
274
+ - **๐ŸŒŒ Follow Whisper** โ€” reveal mystery fragments. Risky on unstudied mushrooms!
275
+ - **๐Ÿฝ๏ธ Eat?** โ€” Myco will stop you every time (for good reason).
276
+ 4. **Ask Myco** anything in the chat โ€” it knows the forest, the mystery, and the mushrooms.
277
+ 5. Use **โฌ†๏ธโฌ‡๏ธโฌ…๏ธโžก๏ธ** to move through the 3ร—3 forest grid.
278
+
279
+ **Scoring:** Common = 10 spores ยท Rare = 35 ยท Legendary = 100 ยท Poison = โˆ’25 + Game Over
280
+
281
+ **Poisonous mushrooms:** Ghost Gill ยท Pepper Pixie ยท Ruby Knuckle ยท Clockwork Chanterelle
282
+ """
283
+
284
+ def build_app():
285
+ with gr.Blocks(title="Myco โ€” Forest Adventure") as demo:
286
+ gr.HTML("""
287
+ <style>
288
+ .gradio-container { background: #1a1a2e !important; }
289
+ #forest-scene, #discovery-card { contain: layout style; content-visibility: auto; }
290
+ .progress-level, .progress-level-inner, .generating { display: none !important; }
291
+ </style>
292
+ """)
293
+
294
+ current_mushroom = gr.State(None)
295
+ collection = gr.State([])
296
+ player_position = gr.State(START_POSITION)
297
+
298
+ gr.HTML(hero_markdown())
299
+
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")
317
+ with gr.Column(scale=1):
318
+ gr.Markdown("**Move Myco**")
319
+ with gr.Row():
320
+ gr.HTML("<div></div>")
321
+ north_button = gr.Button("โฌ†๏ธ", size="sm")
322
+ gr.HTML("<div></div>")
323
+ with gr.Row():
324
+ west_button = gr.Button("โฌ…๏ธ", size="sm")
325
+ pick_button = gr.Button("๐Ÿ„ Pick", variant="primary", size="sm")
326
+ east_button = gr.Button("โžก๏ธ", size="sm")
327
+ with gr.Row():
328
+ gr.HTML("<div></div>")
329
+ south_button = gr.Button("โฌ‡๏ธ", size="sm")
330
+ gr.HTML("<div></div>")
331
+
332
+ status = gr.Markdown(game_status_markdown(None, EMPTY_COLLECTION, START_POSITION))
333
+
334
+ with gr.Row(equal_height=True, elem_id="discovery-card"):
335
+ with gr.Column(scale=2):
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")
347
+ chat = gr.Chatbot(value=cast(Any, _normalize_history(welcome_history())), label="Myco", height=400, show_label=False)
348
+ with gr.Row():
349
+ prompt = gr.Textbox(placeholder="Ask Myco about this place...", show_label=False, scale=4, lines=1)
350
+ ask_button = gr.Button("Ask ๐Ÿ„", variant="primary", scale=1)
351
+
352
+ with gr.Tab("๐Ÿ“– MycoDex"):
353
+ with gr.Row():
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()
408
+ return demo
409
+