byte-vortex commited on
Commit
f59e4b0
·
verified ·
1 Parent(s): 51a2b91

Delete ui/copy--gradio_app.py

Browse files
Files changed (1) hide show
  1. ui/copy--gradio_app.py +0 -423
ui/copy--gradio_app.py DELETED
@@ -1,423 +0,0 @@
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,
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
- """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
33
- try:
34
- return json.loads(s)
35
- except Exception:
36
- pass
37
- try:
38
- return ast.literal_eval(s)
39
- except Exception:
40
- pass
41
- try:
42
- s_json = s.replace("None", "null").replace("True", "true").replace("False", "false")
43
- return json.loads(s_json)
44
- except Exception:
45
- pass
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("}")):
56
- parsed = force_parse_json_or_literal(val_stripped)
57
- if isinstance(parsed, str):
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:
72
- cleaned = extract_clean_text(item)
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))
104
- elif isinstance(item, (list, tuple)) and len(item) == 2:
105
- user_side, bot_side = item
106
- if user_side:
107
- raw_normalized.append({"role": "user", "content": extract_clean_text(user_side)})
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("{")):
115
- nested_parsed = force_parse_json_or_literal(clean_text)
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"]
126
- content = msg["content"]
127
- if reconciled and reconciled[-1]["role"] == 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):
135
- return _normalize_history(history)
136
-
137
- def mushroom_card_from_state(current):
138
- if current is None:
139
- return mushroom_card(None)
140
- if isinstance(current, str):
141
- current = force_parse_json_or_literal(current)
142
- if isinstance(current, str):
143
- return mushroom_card(None)
144
- return mushroom_card(
145
- Mushroom.from_dict(current),
146
- current.get("clue"),
147
- current.get("secret"),
148
- current,
149
- )
150
-
151
- def search_forest(position, collection):
152
- pos = _safe_pos(position)
153
- mushroom, current, history = discover_mushroom(collection)
154
- if isinstance(current, str):
155
- current = force_parse_json_or_literal(current)
156
- return (
157
- forest_scene(current, collection, pos),
158
- game_status_markdown(current, collection, pos),
159
- mushroom_card_from_state(current),
160
- current,
161
- _normalize_history(history),
162
- dex_markdown(collection),
163
- progress_markdown(collection),
164
- )
165
-
166
- def ask_companion(message, history, current, collection, position):
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])
174
- return "", _normalize_history(result)
175
-
176
- def collect_discovery(current, collection, history, position):
177
- legacy_hist = _denormalize_history(history)
178
- updated_coll, updated_hist = collect_current(current, collection, legacy_hist)
179
- pos = _safe_pos(position)
180
- if isinstance(current, str):
181
- current = force_parse_json_or_literal(current)
182
- return (
183
- updated_coll,
184
- forest_scene(current, updated_coll, pos),
185
- game_status_markdown(current, updated_coll, pos),
186
- dex_markdown(updated_coll),
187
- world_map_markdown(updated_coll),
188
- _normalize_history(updated_hist),
189
- progress_markdown(updated_coll),
190
- )
191
-
192
- def pick_discovery(current, collection, history, position):
193
- legacy_hist = _denormalize_history(history)
194
- updated_coll, updated_current, updated_hist = pick_current(current, collection, legacy_hist)
195
- if isinstance(updated_current, str):
196
- updated_current = force_parse_json_or_literal(updated_current)
197
- pos = _safe_pos(position)
198
- return (
199
- updated_coll,
200
- updated_current,
201
- forest_scene(updated_current, updated_coll, pos),
202
- game_status_markdown(updated_current, updated_coll, pos),
203
- mushroom_card_from_state(updated_current),
204
- dex_markdown(updated_coll),
205
- world_map_markdown(updated_coll),
206
- _normalize_history(updated_hist),
207
- progress_markdown(updated_coll),
208
- )
209
-
210
- def follow_story_whisper(current, collection, history, position):
211
- legacy_hist = _denormalize_history(history)
212
- updated_current, updated_hist = follow_whisper(current, collection, legacy_hist)
213
- if isinstance(updated_current, str):
214
- updated_current = force_parse_json_or_literal(updated_current)
215
- pos = _safe_pos(position)
216
- return (
217
- updated_current,
218
- forest_scene(updated_current, collection, pos),
219
- game_status_markdown(updated_current, collection, pos),
220
- mushroom_card_from_state(updated_current),
221
- _normalize_history(updated_hist),
222
- )
223
-
224
- def study_discovery(current, history, collection, position):
225
- legacy_hist = _denormalize_history(history)
226
- updated_current, updated_hist = study_current(current, legacy_hist)
227
- if isinstance(updated_current, str):
228
- updated_current = force_parse_json_or_literal(updated_current)
229
- pos = _safe_pos(position)
230
- return (
231
- updated_current,
232
- forest_scene(updated_current, collection, pos),
233
- game_status_markdown(updated_current, collection, pos),
234
- mushroom_card_from_state(updated_current),
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
242
- elif direction == "west": x -= 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
- )
259
-
260
- def block_unsafe_eating(current, history):
261
- legacy_hist = _denormalize_history(history)
262
- updated_hist = eat_current(current, legacy_hist)
263
- return _normalize_history(updated_hist)
264
-
265
- def open_play_tab():
266
- return gr.update(selected="play")
267
-
268
- def _safe_pos(position):
269
- if position is None:
270
- return START_POSITION
271
- x, y = position
272
- return (max(0, min(2, int(x))), max(0, min(2, int(y))))
273
-
274
- GUIDE_MARKDOWN = """
275
- ## How to play
276
-
277
- 1. Go to **🎮 Play** and click **🎮 Search Clearing** to discover a mushroom.
278
- 2. **Myco (the AI) reacts** — read what it senses about the mushroom.
279
- 3. Choose your action:
280
- - **🔍 Study** — Myco examines the mushroom and updates its magic field.
281
- - **🍄 Pick** — grab it as a game item. Poisonous picks = Game Over!
282
- - **📖 Collect** — add it to the MycoDex for safe keeping and score.
283
- - **🌌 Follow Whisper** — reveal mystery fragments. Risky on unstudied mushrooms!
284
- - **🍽️ Eat?** — Myco will stop you every time (for good reason).
285
- 4. **Ask Myco** anything in the chat — it knows the forest, the mystery, and the mushrooms.
286
- 5. Use **⬆️⬇️⬅️➡️** to move through the 3×3 forest grid.
287
-
288
- **Scoring:** Common = 10 spores · Rare = 35 · Legendary = 100 · Poison = −25 + Game Over
289
-
290
- **Poisonous mushrooms:** Ghost Gill · Pepper Pixie · Ruby Knuckle · Clockwork Chanterelle
291
- """
292
-
293
- def build_app():
294
- with gr.Blocks(title="Myco — Forest Adventure") as demo:
295
- gr.HTML("""
296
- <style>
297
- .gradio-container { background: #1a1a2e !important; }
298
- #forest-scene, #discovery-card { contain: layout style; content-visibility: auto; }
299
- .progress-level, .progress-level-inner, .generating { display: none !important; }
300
- </style>
301
- """)
302
-
303
- current_mushroom = gr.State(None)
304
- collection = gr.State([])
305
- player_position = gr.State(START_POSITION)
306
-
307
- gr.HTML(hero_markdown())
308
-
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")
328
- with gr.Column(scale=1):
329
- gr.Markdown("**Move Myco**")
330
- with gr.Row():
331
- gr.HTML("<div></div>")
332
- north_button = gr.Button("⬆️", size="sm")
333
- gr.HTML("<div></div>")
334
- with gr.Row():
335
- west_button = gr.Button("⬅️", size="sm")
336
- pick_button = gr.Button("🍄 Pick", variant="primary", size="sm")
337
- east_button = gr.Button("➡️", size="sm")
338
- with gr.Row():
339
- gr.HTML("<div></div>")
340
- south_button = gr.Button("⬇️", size="sm")
341
- gr.HTML("<div></div>")
342
-
343
- status = gr.Markdown(game_status_markdown(None, EMPTY_COLLECTION, START_POSITION))
344
-
345
- with gr.Row(equal_height=True, elem_id="discovery-card"):
346
- with gr.Column(scale=2):
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")
358
- chat = gr.Chatbot(value=cast(Any, _normalize_history(welcome_history())), label="Myco", height=400, show_label=False)
359
- with gr.Row():
360
- prompt = gr.Textbox(placeholder="Ask Myco about this place...", show_label=False, scale=4, lines=1)
361
- ask_button = gr.Button("Ask 🍄", variant="primary", scale=1)
362
-
363
- with gr.Tab("📖 MycoDex"):
364
- with gr.Row():
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()
422
- return demo
423
-