byte-vortex commited on
Commit
b90b52d
·
verified ·
1 Parent(s): e4b7bb9

Delete ui/1-gradio_app.py

Browse files
Files changed (1) hide show
  1. ui/1-gradio_app.py +0 -601
ui/1-gradio_app.py DELETED
@@ -1,601 +0,0 @@
1
- """Gradio game UI for Myco — LLM-powered forest adventure."""
2
-
3
- import ast
4
- import json
5
- import copy
6
- import random
7
- import threading
8
- import time
9
- import logging
10
- from typing import Any, cast
11
- import gradio as gr
12
-
13
- from game.engine import (
14
- collect_current, discover_mushroom, eat_current,
15
- follow_whisper, hf_companion_status, myco_reply,
16
- pick_current, study_current, check_auto_pickup,
17
- get_myco_narrative, RARITY_WEIGHTS, POISONOUS,
18
- )
19
- from game.catalog import load_mushrooms
20
- from game.state import welcome_history
21
- from models.mushroom import Mushroom
22
-
23
- from ui.renderers import (
24
- dex_markdown, forest_scene, game_intro_markdown,
25
- game_status_markdown, hero_markdown, home_forest_markdown,
26
- mushroom_card, progress_markdown, world_map_markdown, bubble
27
- )
28
- from ui.interface import render_shroom_tab
29
-
30
- logger = logging.getLogger(__name__)
31
- EMPTY_COLLECTION = None
32
- START_POSITION = (1, 1)
33
-
34
- # ---------------------------------------------------------------------------
35
- # Autonomous roam state — pure Python, no LLM for decisions
36
- # ---------------------------------------------------------------------------
37
- _ROAM_LOCK = threading.Lock()
38
- _ROAM = {
39
- "position": [1, 1],
40
- "visited": set(),
41
- "thought": "The forest is waking up...",
42
- "ticks": 0,
43
- }
44
-
45
-
46
- def _roam_next_pos(x, y):
47
- candidates = []
48
- for dx, dy in [(0,-1),(0,1),(-1,0),(1,0)]:
49
- nx, ny = x+dx, y+dy
50
- if 0 <= nx <= 2 and 0 <= ny <= 2:
51
- w = 1 if (nx,ny) in _ROAM["visited"] else 4
52
- candidates.extend([(nx,ny)]*w)
53
- return list(random.choice(candidates)) if candidates else [x, y]
54
-
55
- def _autonomous_tick(current, collection, active_mushrooms, position):
56
- """Pure Python: move Myco, check pickup, return updated state."""
57
- with _ROAM_LOCK:
58
- x, y = _ROAM["position"]
59
- safe_mushrooms = list(active_mushrooms or [])
60
- coll = list(collection or [])
61
-
62
- # Check pickup at current position first
63
- if safe_mushrooms:
64
- current, coll, safe_mushrooms = check_auto_pickup(
65
- x, y, current, coll, safe_mushrooms
66
- )
67
-
68
- # Move to next cell
69
- nx, ny = _roam_next_pos(x, y)
70
- _ROAM["position"] = [nx, ny]
71
- _ROAM["visited"].add((nx, ny))
72
- _ROAM["ticks"] += 1
73
- pos = (nx, ny)
74
-
75
- # Check pickup at new position
76
- if safe_mushrooms:
77
- current, coll, safe_mushrooms = check_auto_pickup(
78
- nx, ny, current, coll, safe_mushrooms
79
- )
80
-
81
- thought = _ROAM["thought"]
82
-
83
- return (
84
- list(pos),
85
- forest_scene(current, coll, pos, active_mushrooms=safe_mushrooms),
86
- game_status_markdown(current, coll, pos),
87
- mushroom_card_from_state(current),
88
- current,
89
- coll,
90
- safe_mushrooms,
91
- gr.update(),
92
- dex_markdown(coll),
93
- progress_markdown(coll),
94
- )
95
-
96
- # ---------------------------------------------------------------------------
97
- # JSON / history helpers
98
- # ---------------------------------------------------------------------------
99
- def force_parse_json_or_literal(s: str) -> Any:
100
- s = s.strip()
101
- if not (s.startswith("[") or s.startswith("{")):
102
- return s
103
- try:
104
- return json.loads(s)
105
- except Exception:
106
- pass
107
- try:
108
- return ast.literal_eval(s)
109
- except Exception:
110
- pass
111
- try:
112
- return json.loads(s.replace("None","null").replace("True","true").replace("False","false"))
113
- except Exception:
114
- pass
115
- return s
116
-
117
- def extract_clean_text(val: Any) -> str:
118
- if val is None: return ""
119
- if isinstance(val, str):
120
- v = val.strip()
121
- if (v.startswith("[") and v.endswith("]")) or (v.startswith("{") and v.endswith("}")):
122
- parsed = force_parse_json_or_literal(v)
123
- if isinstance(parsed, str): return parsed
124
- return extract_clean_text(parsed)
125
- return val
126
- if isinstance(val, dict):
127
- for k in ("text","content"):
128
- if k in val: return extract_clean_text(val[k])
129
- return " ".join(extract_clean_text(v) for v in val.values() if v)
130
- if isinstance(val, list):
131
- return "\n".join(extract_clean_text(i) for i in val if i)
132
- return str(val)
133
-
134
- def _normalize_history(history):
135
- if not history: return []
136
- if isinstance(history, str): history = force_parse_json_or_literal(history)
137
- if not isinstance(history, (list, tuple)): history = [history]
138
- raw = []
139
- for item in history:
140
- if item is None: continue
141
- if isinstance(item, str): item = force_parse_json_or_literal(item)
142
- if isinstance(item, dict):
143
- role = item.get("role","assistant")
144
- content = item.get("content", item.get("text",""))
145
- raw.append({"role": role, "content": content})
146
- elif isinstance(item, (list,tuple)) and len(item)==2:
147
- u, b = item
148
- if u: raw.append({"role":"user","content": extract_clean_text(u)})
149
- if b: raw.append({"role":"assistant","content": extract_clean_text(b)})
150
- else:
151
- raw.append({"role":"assistant","content": extract_clean_text(item)})
152
- reconciled = []
153
- for msg in raw:
154
- role = str(msg.get("role","assistant")).lower()
155
- if role not in ("user","assistant","system"): role = "assistant"
156
- content = str(extract_clean_text(msg.get("content",""))).strip()
157
- if not content: continue
158
- if reconciled and reconciled[-1]["role"] == role:
159
- reconciled[-1]["content"] += f"\n{content}"
160
- else:
161
- reconciled.append({"role": role, "content": content})
162
- return reconciled
163
-
164
- def _denormalize_history(history):
165
- msgs = _normalize_history(history)
166
- out = []
167
- i = 0
168
- while i < len(msgs):
169
- role = msgs[i].get("role","assistant")
170
- content = msgs[i].get("content","")
171
- if role == "user":
172
- bot = ""
173
- if i+1 < len(msgs) and msgs[i+1].get("role") == "assistant":
174
- bot = msgs[i+1].get("content","")
175
- i += 2
176
- else:
177
- i += 1
178
- out.append((content, bot))
179
- else:
180
- out.append(("", content))
181
- i += 1
182
- return out
183
-
184
- # ---------------------------------------------------------------------------
185
- # Mushroom card helper
186
- # ---------------------------------------------------------------------------
187
- def mushroom_card_from_state(current):
188
- if current is None: return mushroom_card(None)
189
- if isinstance(current, str): current = force_parse_json_or_literal(current)
190
- if not isinstance(current, dict): return mushroom_card(None)
191
- state = copy.copy(current)
192
- state.setdefault("name","Unknown Mushroom")
193
- state.setdefault("rarity","Common")
194
- state.setdefault("habitat","Unknown")
195
- state.setdefault("lore","No lore available.")
196
- try:
197
- m = Mushroom.from_dict(state)
198
- except Exception:
199
- return mushroom_card(None)
200
- return mushroom_card(m, state.get("clue"), state.get("secret"), state)
201
-
202
- # ---------------------------------------------------------------------------
203
- # Search — spawns 4-6 mushrooms at random grid positions
204
- # ---------------------------------------------------------------------------
205
- def search_forest(position, collection):
206
- pos = _safe_pos(position)
207
- coll = list(collection or [])
208
- catalog = list(load_mushrooms())
209
-
210
- # Spawn 4-6 mushrooms at random grid positions
211
- count = random.randint(4, 6)
212
- used = set()
213
- batch = []
214
- for _ in range(count):
215
- if len(used) >= 9: break
216
- while True:
217
- mx, my = random.randint(0,2), random.randint(0,2)
218
- if (mx,my) not in used: break
219
- used.add((mx,my))
220
- weights = [RARITY_WEIGHTS.get(getattr(m,"rarity","Common"),12) for m in catalog]
221
- m = random.choices(catalog, weights=weights, k=1)[0]
222
- batch.append({
223
- "name": m.name,
224
- "rarity": m.rarity,
225
- "habitat": getattr(m,"habitat","Forest"),
226
- "lore": getattr(m,"lore",""),
227
- "edible": getattr(m,"edible","Unknown"),
228
- "magic": getattr(m,"magic","Unknown"),
229
- "danger": getattr(m,"danger","Unknown"),
230
- "poison": "Yes" if m.name in POISONOUS else "No",
231
- "mush_x": mx,
232
- "mush_y": my,
233
- "picked": "No",
234
- "studied": "No",
235
- "clue": "Move Myco onto this mushroom to collect it!",
236
- "score_delta": str({"Common":10,"Rare":35,"Legendary":100}.get(m.rarity,10)),
237
- })
238
-
239
- current = {
240
- "name": "Mushroom Patch",
241
- "rarity": "Multiple",
242
- "poison": "No",
243
- "game_over": "No",
244
- "picked": "No",
245
- "studied": "No",
246
- "encounter": f"{count} mushrooms sprouted! Move Myco to collect them!",
247
- "event_title": "Spore Influx",
248
- "event_emoji": "🍄",
249
- "mystery_title": "The Wrong Memory",
250
- "mystery_next": "Keep collecting to reveal the next chapter.",
251
- "score_total": str(sum(int(b.get("score_delta","10")) for b in batch
252
- if b.get("poison")=="No")),
253
- "health": "3",
254
- "reward_text": f"Move Myco to pick up {count} mushrooms!",
255
- "active_mushrooms": batch,
256
- }
257
-
258
- history = list(welcome_history()) + [
259
- {"role":"assistant","content":f"🍄 Whoa! {count} mushrooms just sprouted across the clearing! Move me around to collect them — but watch for the poisonous ones!"}
260
- ]
261
-
262
- return (
263
- forest_scene(current, coll, pos, active_mushrooms=batch),
264
- game_status_markdown(current, coll, pos),
265
- mushroom_card_from_state(batch[0] if batch else None),
266
- current,
267
- batch, # active_mushrooms state
268
- _normalize_history(history),
269
- dex_markdown(coll),
270
- progress_markdown(coll),
271
- )
272
-
273
- # ---------------------------------------------------------------------------
274
- # Movement — collision detection built in, no LLM call
275
- # ---------------------------------------------------------------------------
276
- def move_player(position, direction, current, collection, active_mushrooms):
277
- x, y = _safe_pos(position)
278
- if direction == "north": y = max(0, y-1)
279
- elif direction == "south": y = min(2, y+1)
280
- elif direction == "west": x = max(0, x-1)
281
- elif direction == "east": x = min(2, x+1)
282
- pos = (x, y)
283
-
284
- safe_mushrooms = list(active_mushrooms or [])
285
- coll = list(collection or [])
286
-
287
- # Collision check — pure Python, no LLM
288
- current, coll, safe_mushrooms = check_auto_pickup(
289
- x, y, current, coll, safe_mushrooms
290
- )
291
-
292
- # Update roam tracker
293
- with _ROAM_LOCK:
294
- _ROAM["position"] = [x, y]
295
- _ROAM["visited"].add((x, y))
296
-
297
- return (
298
- pos,
299
- forest_scene(current, coll, pos, active_mushrooms=safe_mushrooms),
300
- game_status_markdown(current, coll, pos),
301
- mushroom_card_from_state(current),
302
- current,
303
- coll,
304
- safe_mushrooms,
305
- gr.update(), # leave chat untouched
306
- dex_markdown(coll),
307
- progress_markdown(coll),
308
- )
309
-
310
- # ---------------------------------------------------------------------------
311
- # Other player actions
312
- # ---------------------------------------------------------------------------
313
- def ask_companion(message, history, current, collection, position):
314
- legacy = _denormalize_history(history)
315
- result = myco_reply(message, legacy, current, collection, position)
316
- if isinstance(result, (tuple,list)) and len(result)==2:
317
- return result[0], _normalize_history(result[1])
318
- return "", _normalize_history(result)
319
-
320
- def collect_discovery(current, collection, history, position):
321
- legacy = _denormalize_history(history)
322
- updated_coll, updated_hist = collect_current(current, collection, legacy)
323
- pos = _safe_pos(position)
324
- if isinstance(current,str): current = force_parse_json_or_literal(current)
325
- return (
326
- updated_coll,
327
- forest_scene(current, updated_coll, pos),
328
- game_status_markdown(current, updated_coll, pos),
329
- dex_markdown(updated_coll),
330
- world_map_markdown(updated_coll),
331
- _normalize_history(updated_hist),
332
- progress_markdown(updated_coll),
333
- )
334
-
335
- def pick_discovery(current, collection, history, position):
336
- legacy = _denormalize_history(history)
337
- updated_coll, updated_current, updated_hist = pick_current(current, collection, legacy)
338
- if isinstance(updated_current,str): updated_current = force_parse_json_or_literal(updated_current)
339
- pos = _safe_pos(position)
340
- return (
341
- updated_coll,
342
- updated_current,
343
- forest_scene(updated_current, updated_coll, pos),
344
- game_status_markdown(updated_current, updated_coll, pos),
345
- mushroom_card_from_state(updated_current),
346
- dex_markdown(updated_coll),
347
- world_map_markdown(updated_coll),
348
- _normalize_history(updated_hist),
349
- progress_markdown(updated_coll),
350
- )
351
-
352
- def follow_story_whisper(current, collection, history, position):
353
- legacy = _denormalize_history(history)
354
- updated_current, updated_hist = follow_whisper(current, collection, legacy)
355
- if isinstance(updated_current,str): updated_current = force_parse_json_or_literal(updated_current)
356
- pos = _safe_pos(position)
357
- return (
358
- updated_current,
359
- forest_scene(updated_current, collection, pos),
360
- game_status_markdown(updated_current, collection, pos),
361
- mushroom_card_from_state(updated_current),
362
- _normalize_history(updated_hist),
363
- )
364
-
365
- def study_discovery(current, history, collection, position):
366
- legacy = _denormalize_history(history)
367
- updated_current, updated_hist = study_current(current, legacy)
368
- if isinstance(updated_current,str): updated_current = force_parse_json_or_literal(updated_current)
369
- pos = _safe_pos(position)
370
- return (
371
- updated_current,
372
- forest_scene(updated_current, collection, pos),
373
- game_status_markdown(updated_current, collection, pos),
374
- mushroom_card_from_state(updated_current),
375
- _normalize_history(updated_hist),
376
- )
377
-
378
- def block_unsafe_eating(current, history):
379
- legacy = _denormalize_history(history)
380
- _, updated_hist = eat_current(current, None, legacy)
381
- return _normalize_history(updated_hist)
382
-
383
- def open_play_tab():
384
- return gr.update(selected="play")
385
-
386
- def _safe_pos(position):
387
- if position is None: return START_POSITION
388
- x, y = position
389
- return (max(0,min(2,int(x))), max(0,min(2,int(y))))
390
-
391
- # ---------------------------------------------------------------------------
392
- # Guide text
393
- # ---------------------------------------------------------------------------
394
- GUIDE_MARKDOWN = """
395
- ## How to play
396
-
397
- 1. Go to **🎮 Play** and click **🎮 Search Clearing** to spawn mushrooms across the grid.
398
- 2. Use **⬆️⬇️⬅️➡️** to move Myco — walk over mushrooms to collect them automatically!
399
- 3. **Watch out** — stepping on a poisonous mushroom triggers Game Over!
400
- 4. Myco also **roams autonomously** every 3 seconds collecting mushrooms for you.
401
- 5. Use the action buttons to Study, Collect, Pick, or Follow Whisper.
402
- 6. Ask Myco anything in the chat.
403
-
404
- **Scoring:** Common = 10 · Rare = 35 · Legendary = 100 · Poison = −25 + Game Over
405
-
406
- **Poisonous:** Ghost Gill · Pepper Pixie · Ruby Knuckle · Clockwork Chanterelle
407
- """
408
-
409
- # ---------------------------------------------------------------------------
410
- # App
411
- # ---------------------------------------------------------------------------
412
- def build_app():
413
- with gr.Blocks(title="Myco — Forest Adventure") as demo:
414
- gr.HTML("""<style>
415
- .gradio-container { background: #1a1a2e !important; }
416
- #forest-scene { contain: layout style; content-visibility: auto; }
417
- .progress-level, .progress-level-inner, .generating { display: none !important; }
418
- </style>""")
419
-
420
- # ── Shared state ──
421
- current_mushroom = gr.State(None)
422
- collection = gr.State([])
423
- player_position = gr.State(START_POSITION)
424
- active_mushrooms = gr.State([])
425
-
426
- gr.HTML(hero_markdown())
427
-
428
- status = gr.HTML()
429
-
430
- timer = gr.Timer(10)
431
-
432
- myco_bubble = gr.HTML()
433
-
434
- timer.tick(
435
- fn=lambda: bubble(get_myco_narrative()),
436
- outputs=myco_bubble
437
- )
438
-
439
-
440
- with gr.Tabs(selected="home") as tabs:
441
-
442
- with gr.Tab("🏠 Home", id="home"):
443
- gr.HTML(home_forest_markdown())
444
- start_play_button = gr.Button("🌲 Enter the Forest", variant="primary", size="lg")
445
-
446
- with gr.Tab("🎮 Play", id="play"):
447
- gr.HTML(game_intro_markdown())
448
- scene = gr.HTML(
449
- forest_scene(None, EMPTY_COLLECTION, START_POSITION),
450
- elem_id="forest-scene",
451
- )
452
-
453
- with gr.Row():
454
- with gr.Column(scale=1):
455
- search_button = gr.Button("🎮 Search Clearing", variant="primary", size="lg")
456
- with gr.Column(scale=1):
457
- gr.Markdown("**Move Myco**")
458
- with gr.Row():
459
- gr.HTML("<div></div>")
460
- north_button = gr.Button("⬆️", size="sm")
461
- gr.HTML("<div></div>")
462
- with gr.Row():
463
- west_button = gr.Button("⬅️", size="sm")
464
- pick_button = gr.Button("🍄 Pick", variant="primary", size="sm")
465
- east_button = gr.Button("➡️", size="sm")
466
- with gr.Row():
467
- gr.HTML("<div></div>")
468
- south_button = gr.Button("⬇️", size="sm")
469
- gr.HTML("<div></div>")
470
-
471
- status = gr.Markdown(game_status_markdown(None, EMPTY_COLLECTION, START_POSITION))
472
-
473
- with gr.Row(equal_height=True, elem_id="discovery-card"):
474
- with gr.Column(scale=2):
475
- gr.Markdown("### 🍄 Current Discovery")
476
- discovery = gr.Markdown(mushroom_card(None))
477
- with gr.Row():
478
- study_button = gr.Button("🔍 Study", variant="secondary")
479
- collect_button = gr.Button("🧺 Collect", variant="secondary")
480
- with gr.Row():
481
- whisper_button = gr.Button("🌌 Follow Whisper", variant="secondary")
482
- eat_button = gr.Button("🍽️ Eat?", variant="stop")
483
-
484
- with gr.Column(scale=3):
485
- gr.Markdown("### 💬 Chat with Myco")
486
- chat = gr.Chatbot(
487
- value=cast(Any, _normalize_history(welcome_history())),
488
- label="Myco", height=400, show_label=False,
489
- )
490
- with gr.Row():
491
- prompt = gr.Textbox(
492
- placeholder="Ask Myco about this place...",
493
- show_label=False, scale=4, lines=1,
494
- )
495
- ask_button = gr.Button("Ask 🍄", variant="primary", scale=1)
496
-
497
- with gr.Tab("📖 MycoDex"):
498
- with gr.Row():
499
- progress = gr.Markdown(progress_markdown(EMPTY_COLLECTION))
500
- dex = gr.Markdown(dex_markdown(EMPTY_COLLECTION))
501
- with gr.Group(elem_classes="myco-image-2"):
502
- gr.Image(value="assets/images/Myco-2.png",
503
- show_label=False, container=False, interactive=False)
504
-
505
- with gr.Tab("🗺️ Map"):
506
- world_map = gr.HTML(world_map_markdown(EMPTY_COLLECTION))
507
-
508
- with gr.Tab("🧭 Guide"):
509
- gr.Markdown(GUIDE_MARKDOWN)
510
- with gr.Group(elem_classes="myco-image"):
511
- gr.Image(value="assets/images/Myco.png",
512
- show_label=False, container=False, interactive=False)
513
-
514
- with gr.Tab("🍄 Myco"):
515
- render_shroom_tab()
516
-
517
- # ── Shared output lists ──
518
- _move_outputs = [
519
- player_position, scene, status, discovery,
520
- current_mushroom, collection, active_mushrooms,
521
- chat, dex, progress,
522
- ]
523
-
524
- # ── Event wiring ──
525
- start_play_button.click(open_play_tab, outputs=[tabs])
526
-
527
-
528
-
529
- # Roam timer — autonomous movement, pure Python
530
- timer.tick(
531
- fn=_autonomous_tick,
532
- inputs=[current_mushroom, collection, active_mushrooms, player_position],
533
- outputs=_move_outputs,
534
- )
535
-
536
- search_button.click(
537
- search_forest,
538
- inputs=[player_position, collection],
539
- outputs=[scene, status, discovery, current_mushroom,
540
- active_mushrooms, chat, dex, progress],
541
- show_progress="hidden",
542
- )
543
-
544
- ask_button.click(
545
- ask_companion,
546
- inputs=[prompt, chat, current_mushroom, collection, player_position],
547
- outputs=[prompt, chat], show_progress="hidden",
548
- )
549
- prompt.submit(
550
- ask_companion,
551
- inputs=[prompt, chat, current_mushroom, collection, player_position],
552
- outputs=[prompt, chat], show_progress="hidden",
553
- )
554
-
555
- # Arrow buttons — each hardcoded direction, correct inputs
556
- for direction, btn in [
557
- ("north", north_button), ("south", south_button),
558
- ("west", west_button), ("east", east_button),
559
- ]:
560
- btn.click(
561
- lambda pos, col, cur, am, d=direction: move_player(pos, d, cur, col, am),
562
- inputs=[player_position, collection, current_mushroom, active_mushrooms],
563
- outputs=_move_outputs,
564
- show_progress="hidden",
565
- )
566
-
567
- study_button.click(
568
- study_discovery,
569
- inputs=[current_mushroom, chat, collection, player_position],
570
- outputs=[current_mushroom, scene, status, discovery, chat],
571
- show_progress="hidden",
572
- )
573
- collect_button.click(
574
- collect_discovery,
575
- inputs=[current_mushroom, collection, chat, player_position],
576
- outputs=[collection, scene, status, dex, world_map, chat, progress],
577
- show_progress="hidden",
578
- )
579
- pick_button.click(
580
- pick_discovery,
581
- inputs=[current_mushroom, collection, chat, player_position],
582
- outputs=[collection, current_mushroom, scene, status,
583
- discovery, dex, world_map, chat, progress],
584
- show_progress="hidden",
585
- )
586
- whisper_button.click(
587
- follow_story_whisper,
588
- inputs=[current_mushroom, collection, chat, player_position],
589
- outputs=[current_mushroom, scene, status, discovery, chat],
590
- show_progress="hidden",
591
- )
592
- eat_button.click(
593
- block_unsafe_eating,
594
- inputs=[current_mushroom, chat],
595
- outputs=[chat],
596
- show_progress="hidden",
597
- )
598
-
599
- demo.queue()
600
- return demo
601
-